2017-05-06 76 views
-1

例如,我有一個包含以下內容的表:如何根據類別進行組合和添加?

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 
+1

你嘗試過什麼?網上有很多例子來彙總表格中的數字。不幸的是,這個問題目前被解讀爲「爲我編寫代碼」。請相應編輯。 –

回答

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; 
0

可以使用旋轉

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')