gpt4 book ai didi

sql - 行在自己的列中,具体取决于它们的值

转载 作者:行者123 更新时间:2023-12-01 09:11:47 25 4
gpt4 key购买 nike

我有一个选择查询,目前产生以下结果:

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

最佳答案

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

关于sql - 行在自己的列中,具体取决于它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/236236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com