如何根据类别进行组合和添加?

时间:2017-05-06 12:46:32

标签: sql database

例如,我有一个包含以下内容的表:

Product Name         Quantity       Category

Mechanical Pencil       3           Stationary
Lead                    4           Stationary
Sherlock Holmes         2           Book
Great Gatsby            2           Book
Paint Brush             1           Art Supplies
Acrylic Paint           5           Art Supplies

我想在列标题中创建类别,然后根据它添加数量,如:

Stationary         Books         Art Supplies
     7               4                6

2 个答案:

答案 0 :(得分:0)

通常,您可以通过将值放在结果集中的不同行中来执行此操作:

select category, sum(quantity)
from t
group by category;

这更灵活,因为为新类别添加了新行。

你可以做你想做的事。一种方法使用条件聚合:

select sum(case when category = 'Stationary' then quantity else 0 end) as Stationary,
       sum(case when category = 'Books' then quantity else 0 end) as Books,
       sum(case when category = 'Art Supplies' then quantity else 0 end) as ArtSupplies
from t;

答案 1 :(得分:0)

您可以使用pivot

select * from ( select quantity, category from #yourproducts ) c
pivot(sum(Quantity) for category in ([Stationary],[Book],[Art Supplies])) p

您的输入表:

create table #yourproducts ([Prodcut Name] varchar(20), quantity int, Category varchar(20))

insert into #yourproducts ([Prodcut Name], quantity, Category ) values
 ('Mechanical Pencil',       3      ,'Stationary')
,('Lead             ',       4      ,'Stationary')
,('Sherlock Holmes  ',       2      ,'Book')
,('Great Gatsby     ',       2      ,'Book')
,('Paint Brush      ',       1      ,'Art Supplies')
,('Acrylic Paint    ',       5      ,'Art Supplies')