如何计算组中的总和

时间:2018-05-17 07:30:55

标签: sql sql-server

我有一张像

这样的表格
  person    type     date
  Tom       day     4/1/2018
  Tom      night    3/2/2018
  Tom       rest    4/3/2018
  Jack      day     4/1/2018
  Jack      day     4/2/2018
  Jack     night    4/3/2018
  Peter     day     4/1/2018
  Peter     day     3/2/2018
  Peter     day     4/3/2018

我想计算四月份每个人的工作时间。白班是8小时,夜晚是11小时。所以结果就像

  Person   hours
   Tom      8
   Jack     27
   Peter    16

我尝试过像

这样的SQL
select person,count(Type),
    case type when 'day' then count(type)*8 when 'night' then count(type)*11  
from table where date>'3/30/2018' 
group by person,type

它有效 然后我尝试像对待一样对待它,并在外面添加一个组,如

select * 
from (select person,count(Type),
    case type when 'day' then count(type)*8 when 'night' then count(type)*11  
    from table where date>'3/30/2018' group by person,type)

并且它不起作用。为什么?任何有用的帮助。

3 个答案:

答案 0 :(得分:3)

您可以使用以下案例 - 何时将类型转换为相应的小时数:

case
  when type='day' then 8
  when type='night' then 11
end

然后你可以加总相应的小时数:

select
  person,
  sum(
    case
      when type='day' then 8
      when type='night' then 11
    end
  ) as hours
from
  table_name
where
   date>='4/01/2018' and date<'5/01/2018'
group by
  person

答案 1 :(得分:2)

试试这个:

SELECT person,
SUM(Case WHEN type='day' THEN 8
     WHEN type='night' THEN 11
     ELSE 0 END)
FROM Table1
WHERE [date]>'2018/03/30'
Group by person

SQL小提琴:http://sqlfiddle.com/#!18/5b946/1

答案 2 :(得分:1)

获得结果的关键是使用case语句来转换&#34;转换&#34; type适当的小时数。试试这个:

select person, SUM([hrs]), [date] from (
    select person,
           case [TYPE_ID] when 'day' then 8
                          when 'night' then 11
                      else 0 end [hrs],
           [date]
    from MY_TABLE
    where date between '4/01/2018' and '5/01/2018'
) [a] group by person