2012-08-29 47 views
1

希望大家都做得很好。總和列只有ID不同

我有以下的輸出...

 
+---------+--------------+--------------+-----------+---------+----------+ 
| ord_num | signoff_date | program_name | prod_desc | tx_comp | priority | 
+---------+--------------+--------------+-----------+---------+----------+ 
| 1234567 | 2012-08-12 | ilearn  | run  |  1 |  1 | 
| 1234567 | 2012-08-12 | ilearn  | plan  |  1 |  1 | 
| 1234568 | 2012-08-12 | other  | run  |  1 |  1 | 
| 1234569 | 2012-08-12 | other  | run  |  0 |  1 | 
+---------+--------------+--------------+-----------+---------+----------+ 

我想這樣做是SUMtx_comp每列獨特的「ord_num」一次。現在

我不能使用GROUP BY ord_num我還任務的類型做了sum

它喜歡我需要知道以前的ord_num然後總結如果有什麼不同?

任何想法將不勝感激。

謝謝。

*編輯*

SELECT 
    signoff_date, 
    SUM(IF(prod_desc = 'run', 1, 0)) AS run, 
    SUM(IF(prod_desc = 'plan', 1, 0)) AS plan, 
    SUM(tx_comp) AS tx_comp 
FROM 
(
    SELECT 
     ord_num, 
     signoff_date, 
     program_name, 
     prod_desc, 
     tx_comp, 
     priority 
    FROM 
     test.orders 
     LEFT JOIN test.tx_comp USING (ord_num) 
) AS grp 

顯然不是期望的輸出

 
+--------------+------+------+---------+ 
| signoff_date | run | plan | tx_comp | 
+--------------+------+------+---------+ 
| 2012-08-12 | 3 | 1 |  3 | 
+--------------+------+------+---------+ 

我之後...

 
+--------------+------+------+---------+ 
| signoff_date | run | plan | tx_comp | 
+--------------+------+------+---------+ 
| 2012-08-12 | 3 | 1 |  2 | 
+--------------+------+------+---------+ 
+0

所以,你想要兩個不同的總和,從不同的標準,在一個單一的查詢? –

+0

@MarcB是的,這是正確的...... – mybigman

+0

「只有在ord_num不同」 - 從什麼?前一行? –

回答

2

如果tx_comp的值始終爲1或零,則我們可以利用COUNT(),這可能會給我們更多的選擇。例如,我們可以在那裏tx_comp是1計數明顯ord_num:

COUNT(distinct IF(tx_comp, ord_num, NULL)) 

,給了我的最終查詢:

SELECT signoff_date, 
    SUM(IF(prod_desc = 'run', 1, 0)) AS run, 
    SUM(IF(prod_desc = 'plan', 1, 0)) AS plan, 
    COUNT(distinct IF(tx_comp, ord_num, NULL)) as tx_comp 
FROM 
    test.orders 
    JOIN test.tx_comp USING (ord_num) 
    GROUP BY signoff_date 

而且也沒有必要在這種情況下,子查詢。 (編輯:已更新爲您的JOIN)

我已經用您的示例數據對此進行了測試;唯一的依賴關係是tx_comp的語義性質。你一直在說「SUM」,並且這個假設值最多爲1(我知道它是一個布爾標誌,並且在你提到MAX(tx_comp)的另一個答案的評論中返回1,所以我認爲我們'重新好)。

+0

冠軍......這麼簡單但很難:)感謝堆 – mybigman

+0

如果tx_comp不同,說tx_comp = 1,2,3等,並希望SUM而不是計數。 –

0

也許只是使用MAX,而不是SUMtx_comp專欄?我不確定數據的語義,但我猜這就是你想要的。實際上,run和​​也可能是相同的。

對於這個問題,真的想要的是BIT_OR,因爲你正在使用布爾值。

+0

感謝您的答覆,最大不工作,因爲它只是給tx_comp輸出1。 – mybigman