Sql 将具有相同值的行合并到一行中
我编写了以下查询:Sql 将具有相同值的行合并到一行中,sql,sql-server,tsql,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'
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 |
我希望将质量行合并为以下格式:
2017-04-14 | Quality | 5 | 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;
我称之为条件聚合;这就是案例进入聚合函数的时候
注:
select distinct几乎不适用于group by。这通常表明存在问题。
没有聚合函数的group by通常表示存在问题。
使用“分组依据”定义结果集中所需的每个唯一行。在这种情况下,您似乎希望每个日期有一行。
仅对字符串和日期常量使用单引号;不要将它们用于列别名。
从分组中获取值并使用总和:
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
您可以将Count更改为SUM,并删除group by中的t1.itemcode。
删除distinct,因为您有分组依据
我经常与Microsoft Sql Server Management StudioTX合作。成功了。谢谢你的指点!!
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