2017-04-21 66 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 
相關問題