gpt4 book ai didi

sql - 编写高级 SQL 选择

转载 作者:行者123 更新时间:2023-12-02 05:33:59 25 4
gpt4 key购买 nike

项目表:

|   Item    |   Qnty    |   ProdSched   |
| a | 1 | 1 |
| b | 2 | 1 |
| c | 3 | 1 |
| a | 4 | 2 |
| b | 5 | 2 |
| c | 6 | 2 |

有没有办法使用 SQL SELECT 像这样输出它?

|   Item    |   ProdSched(1)(Qnty)  |   ProdSched(2)(Qnty)  |
| a | 1 | 4 |
| b | 2 | 5 |
| c | 3 | 6 |

最佳答案

您可以使用 PIVOT为了这。如果您有已知数量的要转换的值,那么您可以通过静态枢轴对这些值进行硬编码:

select item, [1] as ProdSched_1, [2] as ProdSched_2
from
(
select item, qty, prodsched
from yourtable
) x
pivot
(
max(qty)
for prodsched in ([1], [2])
) p

参见 SQL Fiddle with Demo

如果列数未知,则可以使用动态数据透视表:

DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(prodsched)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT item,' + @cols + ' from
(
select item, qty, prodsched
from yourtable
) x
pivot
(
max(qty)
for prodsched in (' + @cols + ')
) p '

execute(@query)

参见 SQL Fiddle with Demo

关于sql - 编写高级 SQL 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12505079/

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