有条件地对SQl求和项

时间:2016-10-13 10:31:17

标签: sql sql-server sql-server-2008 ms-access

我有以下代码。如果是某些工作则计为1,如果是其他工作则计为0。如果它是第三部作品,我需要一种方法来计算0.5。我试过这个,似乎总是数不胜数。有没有办法使用SQL?我搜索过,找不到这样的方法来计算一些项目为0.5。这将有助于访问数据库中的生产总计

SELECT TOP 1000 
 [Type of Work],
COUNT(case when  [Type of Work] IN 
('LEP Decisions',
'Creditable Coverage',
'Pends','Demographics',
'Consents','POA','PCP','Housing Verifications',
'LEP Cases') 
then 1 else Null END)as count
  ,[User ID]
FROM [Medicare_Enrollment].[dbo].[Sample]
group by [Type of Work], [User ID]

2 个答案:

答案 0 :(得分:1)

SELECT TOP 1000 
[Type of Work], 
SUM(case when  [Type of Work] IN ('LEP Decisions','Creditable Coverage','Pends','Demographics','Consents','POA','PCP','Housing Verifications','LEP Cases') then 1 
WHEN [Type of Work] IN ('') -- Put your work list
THEN 0.5
else 0 END)as count
,[User ID]
FROM [Medicare_Enrollment].[dbo].[Sample]
group by [Type of Work], [User ID]

答案 1 :(得分:1)

我建议将COUNT更改为SUM(从而总结10.50 - 而不是计算Null):

  select top 1000 
         [Type of Work], 
         sum (case 
                when [Type of Work] in ('LEP Decisions','Creditable Coverage','Pends','Demographics','Consents','POA','PCP','Housing Verifications','LEP Cases') then 
                  1
                when [Type of Work] in ('SOME OTHER WORK', 'THIRD WORK') then
                  0.5  
                else 
                  0 -- nothing to add 
              end) as count,
         [User ID]
    from [Medicare_Enrollment].[dbo].[Sample]
group by [Type of Work], 
         [User ID]