2014-08-29 38 views
0

總場我有如下表測試與條件

id order hour 

我有兩種情況:

第一種情況:無關

id order hour 
1 1  20 
2 1  40 
3 1  50 

情況二:

id order hour 
1 1  20 
1 2  50 
1 3  70 
2 1  40 
2 2  10 
2 3  20 
2 4  90 
3 1  50 

我需要得到 ID小時

1 120 //hour total=50+70 for id=1 when order >1 
2 120//hour total for=10+20+90 id=2 when order >1 
3 50 // nothing to do because I have one row for id=3 

我怎麼能這樣做?

回答

1

請嘗試以下操作。對於id = 3的SUM將是50,所以在這種情況下仍然可以使用SUM。

SELECT id, SUM(hour) AS HourTotal 
FROM YourTable t1 
WHERE [order] > 1 OR 
     NOT EXISTS (SELECT 1 FROM YourTable t2 WHERE t1.id = t2.id AND [order] > 1) 
GROUP BY id 
+0

我不明白下投票。該問題要求總計3行作爲答案,因爲id = 3的總數是50. – wdosanjos 2014-08-29 16:27:36

+0

因爲在id 1和2的情況下總和錯誤 - 它太高了。訂單> 1的行不應包括在內,除非它是單行(id 3的情況)。 – jpw 2014-08-29 16:28:40

+0

好點。修復瞭解決其他情況。 – wdosanjos 2014-08-29 16:32:59

0

以下代碼正在工作。我測試過了。請嘗試

select ID,SUM(HourTotal) as hourtotal from (
    select id,HourTotal,row_num 
    from (SELECT id, hour_n AS HourTotal ,ROW_NUMBER() over(partition by id order by id) row_num 
    FROM id)a 
    where a.id!=a.row_num)b 
    group by id 
+0

編輯現有答案比嘗試發佈新答案更好... – AHiggins 2014-08-29 17:25:38

+0

他的意思是編輯自己的答案(我這麼說是因爲@AdiT試圖編輯wdosanjos答案) – Vache 2014-08-29 17:29:36

0

請嘗試以下code.it工作

select ID,SUM(HourTotal) as hourtotal from (
     select id,HourTotal,row_num 
     from (SELECT id, hour_n AS HourTotal ,ROW_NUMBER() over(partition by id order by id) row_num 
     FROM id)a 
     where a.id!=a.row_num)b 
     group by id