假设我有一张这样的表
Store | Fruit | Quantity
--------+-----------+-----------
Lincoln | cherry | 2
Lincoln | apple | 3
Lincoln | pear | 4
Abe | cherry | 1
Abe | apple | 2
我需要一个可以返回的SQL查询:
Store | Cherry | Apple | Pear
--------+--------+-------+------
Lincoln | 2 | 2 | 4
Abe | 1 | 2 |
如果“樱桃,苹果和梨”列在查询中被“硬编码”,那就没关系了,但理想的是什么(不确定是否可能),如果数据中出现新的水果新列由SQL查询创建
答案 0 :(得分:1)
如果您使用的是 MS SQL SERVER ,请使用pivot
。您可以使用以下查询并将tablename替换为您的tablename:
MS SQL SERVER
SELECT *
FROM
(
SELECT [Store], [Fruit], [Quantity]
FROM [Your-TableName]
) src
pivot
(
SUM([Quantity])
FOR [Fruit] IN (Cherry, Apple, Pear)
) piv;
答案 1 :(得分:1)
由于您的问题仅使用sql标记,因此这是标准SQL:
select store,
sum(case when fruit = 'Cherry' then quantity end) as cherry_count,
sum(case when fruit = 'Apple' then quantity end) as apple_count,
sum(case when fruit = 'Pear' then quantity end) as pear_count
from the_Table
group by store;