带条件的和字段

时间:2014-08-29 16:12:45

标签: sql-server

我有以下表格测试

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

我该怎么办?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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