2017-04-21 76 views
0

我写了下面的查询:合并具有相同值的行成单排

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  | 

我该怎么做?

+0

我与Microsoft SQL Server Management Studio中 –

回答

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可以在结果集中定义所需的每个唯一行。在这种情况下,您似乎每个日期都需要一行。
  • 只对字符串和日期常量使用单引号;不要将它们用于列别名。
+0

Thankx了很多工作。有效。并感谢您的指针! –

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 
0

你可以改变CountSUMgroup by删除t1.itemcode。 删除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 
相关问题