sql sum在单元格上具有相同的值

时间:2017-12-12 11:09:02

标签: sql sum distinct

我有这两张桌子

[表1]

Name     |    cr      |   value   |   obs 
==============================================
John          500         2         obs1
John          500         2         value2
John          500         170        

[表2]

name  |  cr 1   |  cr 10    |   cr 12   |  cd 500  |  cr 401  | total
John     300        850          34          174        190     1548

我需要这个

select 
nome,
isnull(sum(distinct(case when cr = 1 then value end)),0) as 'cr 1',
isnull(sum(distinct(case when cr = 10 then value end)),0) as 'cr 10',
isnull(sum(distinct(case when cr = 12 then value end)),0) as 'cr 12',
isnull(sum(distinct(case when cr = 500 then value end)),0) as 'cr 500',
isnull(sum(distinct(case when cr = 401 then value end)),0) as 'cr 401',
(   isnull(sum(distinct(case when cr = 1 then value end)),0) +
    isnull(sum(distinct(case when cr = 10 then value end)),0) +
    isnull(sum(distinct(case when cr = 12 then value end)),0) +
    isnull(sum(distinct(case when cr = 500 then value end)),0) +
    isnull(sum(distinct(case when cr = 401 then value end)),0)
) AS Total

from table1 left join table2 on table1.name = table2.name

group by name

我正在尝试使用此查询但未获得正确的结果

{{1}}

问题是,使用此查询,我在'cr 500'

上没有正确的结果

欢迎任何帮助!

提前致谢!

2 个答案:

答案 0 :(得分:0)

您需要UNION ALL

select t.*, cr1 + cr10 + cr12 + cr500 + cr401 as total
from
(
    select 
        name,
        isnull(sum(distinct(case when cr = 1 then value end)),0) as cr1,
        isnull(sum(distinct(case when cr = 10 then value end)),0) as cr10,
        isnull(sum(distinct(case when cr = 12 then value end)),0) as cr12,
        isnull(sum(distinct(case when cr = 500 then value end)),0) as cr500,
        isnull(sum(distinct(case when cr = 401 then value end)),0) as cr401
    from (
      select * from table1 
      union all
      select * from table2
    ) t
    group by name
) t

答案 1 :(得分:0)

您确实需要union all,但我认为这是您想要的查询版本:

select name,
       sum(case when cr = 1 then value else 0 end) as cr1,
       sum(case when cr = 10 then value else 0 end) as cr10,
       sum(case when cr = 12 then value else 0 end) as cr12,
       sum(case when cr = 500 then value else 0 end) as cr500,
       sum(case when cr = 401 then value else 0 end) as cr401,
       sum(case when cr in (1, 10, 12, 500, 401) then value else 0 end) as total
from ((select name, cr, value from table1 
      ) union all
      (select name, cr, value from table2
      )
     ) t
group by name;

换句话说,当您使用sum(distinct)时,union all不再合适。事实上,sum(distinct) 永远不需要。至少,我从未发现它对任何查询都有用。