使用 SQL 重组数据

Restructure data with SQL

假设我有一个这样的 table

Store   |   Fruit   |   Quantity  
--------+-----------+-----------
Lincoln |  cherry   | 2  
Lincoln |  apple    | 3  
Lincoln |  pear     | 4  
Abe     |  cherry   | 1  
Abe     |  apple    | 2

我需要一个 SQL 查询 return 这个:

Store   | Cherry | Apple | Pear
--------+--------+-------+------
Lincoln | 2      | 2     | 4  
Abe     | 1      | 2     |   

如果 "cherry, apple, and pear" 列在查询中是 "hardcoded" 就没问题,但理想情况下(不确定是否可能)是当数据中出现新水果时新列将由 SQL 查询

创建

如果您使用的是 MS SQL SERVER,请使用 pivot。您可以使用以下查询并将表名替换为您的表名:

MS SQL 服务器

SELECT *
FROM
(
  SELECT [Store], [Fruit], [Quantity]
  FROM [Your-TableName]
) src
pivot
(
  SUM([Quantity])
  FOR [Fruit] IN (Cherry, Apple, Pear)
) piv;

因为你的问题只用 标记,这是标准的 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;