从多个结果中添加具有不同名称的2行

时间:2012-08-14 08:33:15

标签: sql-server-2008

我有一个非常简单的SQL -

SELECT      QUEUE,
            COUNT (QUEUE) AS 'TOTAL'
FROM        MY_TABLE
GROUP BY    QUEUE

这导致10行数据,例如 -

First Queue    15  
Second Queue   23  
Third Queue    48  
Fourth Queue   12  
etc

我需要做的是将First Queue的结果添加到Second Queue的结果中,然后将Second Queue的名称更改为New Second Queue,所以我应该最终得到 -

New Second Queue   38  
Third Queue        48  
Fourth Queue       12  
etc

我没有长时间编写SQL,并且花了很多时间试图解决这个问题而没有成功。

2 个答案:

答案 0 :(得分:1)

select queue,
       count(*) as total
from
  (
  select case queue
           when 'First Queue' then 'New Second Queue'
           when 'Second Queue' then 'New Second Queue'
           else queue
         end as queue
  from YourTable
  ) as Q
group by queue      

答案 1 :(得分:0)

试试这个:

with cte as(
SELECT      QUEUE,
            COUNT (QUEUE) AS 'TOTAL',
            ROW_NUMBER() over(order by QUEUE) as rownum
FROM        MY_TABLE
GROUP BY    QUEUE)
select 'New '+QUEUE [QUEUE],TOTAL+(select TOTAL from cte where rownum=1) [TOTAL]
 from cte where rownum=2
 union all
 select QUEUE,TOTAL from cte where rownum>2