我有一个选择查询,当前产生以下结果:
Description Code Price
Product 1 A 5
Product 1 B 4
Product 1 C 2
使用以下查询:
SELECT DISTINCT np.Description, p.promotionalCode, p.Price
FROM Price AS p INNER JOIN
nProduct AS np ON p.nProduct = np.Id
我想制作以下内容:
Description A B C
Product 1 5 4 2
答案 0 :(得分:6)
SELECT
np.Id,
np.Description,
MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',
MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',
MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'
FROM
Price AS p
INNER JOIN nProduct AS np ON p.nProduct = np.Id
GROUP BY
np.Id,
np.Description
这是一个简单的测试示例:
DECLARE @temp TABLE (
id INT,
description varchar(50),
promotionalCode char(1),
Price smallmoney
)
INSERT INTO @temp
select 1, 'Product 1', 'A', 5
union
SELECT 1, 'Product 1', 'B', 4
union
SELECT 1, 'Product 1', 'C', 2
SELECT
id,
description,
MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',
MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',
MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'
FROM
@temp
GROUP BY
id,
description
答案 1 :(得分:2)
如果您使用的是SQL Server 2005,则可以使用新的PIVOT运算符。
简单PIVOT - 客户为单个产品下达的订单数量。
简单订单表的结构:
CREATE TABLE Sales.[Order]
(Customer varchar(8), Product varchar(5), Quantity int)
该表包含以下值:
Customer Product Quantity
Mike Bike 3
Mike Chain 2
Mike Bike 5
Lisa Bike 3
Lisa Chain 3
Lisa Chain 4
Ex:Order表上的PIVOT操作:
SELECT *
FROM Sales.[Order]
PIVOT (SUM(Quantity) FOR Product IN ([Bike],[Chain])) AS PVT
此查询的预期输出为:
Customer Bike Chain
Lisa 3 7
Mike 8 2
如果您不使用SQL Server,则可以搜索数据库的“pivot”。
答案 2 :(得分:1)
如果您的DBMS支持它,您可能还需要查看交叉表查询或数据透视查询。例如,MS Access具有交叉表查询。