【问题标题】:SQl sum items conditionallySQL 有条件地对项目求和
【发布时间】:2016-10-13 10:31:17
【问题描述】:

我有以下代码。如果是某项工作则计为 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]

【问题讨论】:

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


    【解决方案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]
    

    【讨论】:

      【解决方案2】:
      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]
      

      【讨论】:

      • 我相信 COUNT 也应该换成 SUM
      • 哦,是的。我的错。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多