组合查询中的行

时间:2014-12-11 12:31:43

标签: sql sql-server-2008

我有一个SQL查询:

select el as COL_1, sum(volume) as COL_2 
from table1
where el like 'False%' and Month = 'SEP' and year(RollUpDate) = '2014' group by el
union
select el as COL_1, sum(volume) as COL_2 
from table1
where el = 'True' and Month = 'SEP' and year(RollUpDate) = '2014' group by el

将带回来:

true   | 12
false a| 12
false b| 13
false 2| 3

我想要做的就是结合这些谬误,这样我就可以用一个错误和一个假卷的总和带回一个更清晰的结果 即。

true   | 12
false  | 55

任何帮助表示赞赏,sql server 2008 btw

编辑:嗯,这些解决方案很棒,大多数都按照描述工作,但是我不能在严格的jdbc设置中使用它们,所以我不能使用case语句。 Jarlh的答案很接近,但是当返回null结果时,它仍然有那些已创建的列,如果有一个简单的方法通过不使用case语句返回null,那将是完美的

4 个答案:

答案 0 :(得分:1)

您可以将查询用作表格,并从中选择与常规表格或临时表格相同的表格。

SELECT t.COL_1, sum(t.COL_2) FROM
    ((select el as COL_1, sum(volume) as COL_2 
    from table1
    where el like 'False%' and Month = 'SEP' and year(RollUpDate) = '2014' group by el)
    union all
    (select el as COL_1, sum(volume) as COL_2 
    from table1
    where el = 'True' and Month = 'SEP' and year(RollUpDate) = '2014' group by el)) t
WHERE t.COL_1 = 'false'
GROUP BY t.COL_1

答案 1 :(得分:1)

使用子查询和聚合:

select col_1, sum(Col_2)
from ((select el as COL_1, sum(volume) as COL_2 
       from table1
       where el like 'False%' and Month = 'SEP' and year(RollUpDate) = '2014'
       group by el
      ) union all
      (select el as COL_1, sum(volume) as COL_2 
       from table1
       where el = 'True' and Month = 'SEP' and year(RollUpDate) = '2014'
       group by el
      )
     ) t
group by col_1;

但是,这太复杂了。你可以这样做:

select (case when el like 'False%' then 'false'
             else 'True'
        end) as COL_1, sum(volume) as COL_2 
from table1
where (el = 'True' or el like 'False%') and Month = 'SEP' and year(RollUpDate) = '2014'
group by (case when el like 'False%' then 'false'
               else 'True'
          end)

也就是说,您根本不需要union。只需对用于聚合的列使用case语句。

编辑:

实际上,原始查询区分了各种形式的“虚假”。上一个查询可能是OP想要的,但以下更类似于原始查询:

select el as COL_1, sum(volume) as COL_2 
from table1
where (el = 'True' or el like 'False%') and Month = 'SEP' and year(RollUpDate) = '2014'
group by el;

答案 2 :(得分:1)

select 'False' as COL_1, sum(volume) as COL_2 
from table1 where el like 'False%' and Month = 'SEP' and year(RollUpDate) = '2014'
union all
select 'True' as COL_1, sum(volume) as COL_2 
from table1
where el = 'True' and Month = 'SEP' and year(RollUpDate) = '2014'

答案 3 :(得分:0)

嗯,虽然所有的答案都是正确的,但尽管@Jarlh已经接近,但它们并不是我想要的。

我想创建一个提供true和false行的临时列,但是当volume row为null时没有出现。 这就是我最终的结果:

    select 'False' as COL_1, coalesce(sum(volume),0) as COL_2 from tl1 where el like 'False%' and Month = :month and year(RollUpDate) = :year having sum(Volume) is not null 
union 
select 'True' as COL_1, coalesce(sum(volume),0) as COL_2 from tbl1 where el = 'True' and Month = :month and year(RollUpDate) = :year having sum(Volume) is not null