将具有相同值的行合并为一行

时间:2017-04-21 15:37:59

标签: sql sql-server tsql

我写了以下查询:

select distinct
t0.DocDate
,t4.U_SES_VS as 'Value stream'

,case when (t1.ItemCode) = 'WC-QA' then count(t1.itemcode)  else 0 end as 'WC-QA'
,case when  (t1.ItemCode) = 'WC-REC_INSPECTION' then count(t1.itemcode)  else 0 end as 'Inspection'


from ige1 t1 
INNER JOIN OIGE T0 ON T1.DOCENTRY = T0.DOCENTRY 
and few other tables T2,T3,T4,T5 all on Inner Join

Where t1.qty > = t3.qty

group by t0.docdate,t4.u_ses_vs,t1.itemcode

我有以下输出:

 **DocDate** |   **Value Stream** | **WC-QA**  | **Inspection**    |
2017-04-14   |   Engineering      |       0    |       0           |
2017-04-14   |   Production       |       14   |       0           |
2017-04-14   |   Quality          |       5    |       0           |
2017-04-14   |   Quality          |       0    |       1           |

我想将Quality Row合并为以下格式:

2017-04-14    |    Quality    |      5     |   1      | 

我该怎么做?

3 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

select t0.DocDate
       sum(case when t1.ItemCode = 'WC-QA' then 1 else 0 end) as WC_QA,
       sum(case when t1.ItemCode = 'WC-REC_INSPECTION' then 1 else 0 end) as Inspection
from ige1 t1 INNER JOIN
     OIGE T0
     ON T1.DOCENTRY = T0.DOCENTRY 
    and few other tables T2,T3,T4,T5 all on Inner Join
Where t1.qty > = t3.qty
group by t0.docdate;

我称之为“条件聚合”;那就是case进入聚合函数的时候。

注意:

  • select distinct几乎永远不适合group by。这通常表明存在问题。
  • 没有聚合功能的
  • group by通常表示存在问题。
  • 使用group by在结果集中定义所需的每个唯一行。在这种情况下,您似乎希望每个日期有一行。
  • 仅对字符串和日期常量使用单引号;不要将它们用于列别名。

答案 1 :(得分:0)

从分组中获取值并使用SUM:

select 
t0.DocDate
,t4.U_SES_VS as 'Value stream'
,SUM(case when (t1.ItemCode) = 'WC-QA' then count(t1.itemcode)  else 0 end) as 'WC-QA'
,sum(case when  (t1.ItemCode) = 'WC-REC_INSPECTION' then count(t1.itemcode)  else 0 end) as 'Inspection'
from ige1 t1 
INNER JOIN OIGE T0 ON T1.DOCENTRY = T0.DOCENTRY 
and few other tables T2,T3,T4,T5 all on Inner Join
Where t1.qty > = t3.qty
group by t0.docdate,t4.u_ses_vs

答案 2 :(得分:0)

您可以将Count更改为SUM并删除t1.itemcode中的group by。 删除distinct,因为您有group by

select 
t0.DocDate
,t4.U_SES_VS as 'Value stream'
,SUM(case when (t1.ItemCode) = 'WC-QA' then 1  else 0 end) as 'WC-QA'
,SUM(case when  (t1.ItemCode) = 'WC-REC_INSPECTION' then 1  else 0 end) as 'Inspection'

from ige1 t1 
INNER JOIN OIGE T0 ON T1.DOCENTRY = T0.DOCENTRY 
and few other tables T2,T3,T4,T5 all on Inner Join
Where t1.qty > = t3.qty
group by t0.docdate,t4.u_ses_vs