SQL group by,sum,total query

时间:2016-11-28 18:36:52

标签: tsql

有人可以帮助查询吗? 我这里有一张桌子:

CREATE TABLE [dbo].[aas](
    [id] [int] IDENTITY(1,1) NOT NULL,

    [Status] [nchar](10) NULL,
    [price] [int] NOT NULL
) ON [PRIMARY]

GO

insert into [dbo].[aas] ([Status], [price])
values ('a', 23)
insert into [dbo].[aas] ([Status], [price])
values ('a', 23)
insert into [dbo].[aas] ([Status], [price])
values ('a', 23)
insert into [dbo].[aas] ([Status], [price])
values ('b', 4)
insert into [dbo].[aas] ([Status], [price])
values ('b', 4)
insert into [dbo].[aas] ([Status], [price])
values ('b', 4)
insert into [dbo].[aas] ([Status], [price])
values ('b', 4)
insert into [dbo].[aas] ([Status], [price])
values ('c', 8)
insert into [dbo].[aas] ([Status], [price])
values ('c', 8)
insert into [dbo].[aas] ([Status], [price])
values ('c', 8)
insert into [dbo].[aas] ([Status], [price])
values ('c', 8)
insert into [dbo].[aas] ([Status], [price])
values ('c', 8)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)
insert into [dbo].[aas] ([Status], [price])
values ('y', 2)

我期待这样的输出:

TotalA TotalPriceA TotalB TotalPriceB TotalC TotalPriceC TotalY TotalPriceY
3 69 4 16 5 40 12 24

但是这个查询返回了冗余数据:

select 
COUNT(CASE WHEN [status] = 'a' THEN 1 ELSE 0 END) as [TotalA],
case when [status] = 'a' then
    sum(price)
    else 0
END as [TotalpriceA],

COUNT(CASE WHEN [status] = 'b' THEN 1 ELSE 0 END) as [TotalB],
case when [status] = 'b' then
    sum(price)
    else 0
END as [TotalpriceB],

COUNT(CASE WHEN [status] = 'c' THEN 1 ELSE 0 END) as [TotalC],
case when [status] = 'c' then
    sum(price)
    else 0
END as [TotalpriceC],

COUNT(CASE WHEN [status] = 'y' THEN 1 ELSE 0 END) as [TotalY],
case when [status] = 'y' then
    sum(price)
    else 0
END as [TotalpriceY]
from [dbo].[aas]
group by [status]

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

分组依据每个'状态'将返回一行,这就是你获得4行的原因。

这是您想要的查询。虽然您可能想要转动数据。

SELECT  [status], count(*) as 'Total', sum(price) as 'TotalPrice'
from aas
group by [status]