我dbo.Sales在 SQL Server 中有下表:
| 物品 | 英國 | 德國 | 法國 | 西班牙 |
|---|---|---|---|---|
| X1 | 1 | 1 | 1 | 0 |
| X2 | 0 | 0 | 1 | 1 |
| X3 | 1 | 0 | 0 | 0 |
我想準備資料集,以便將二進制列轉換為具有逗號分隔值的單行,其中二進制值 = 1。但是,我希望使用列名而不是二進制值。
| 物品 | 國家 |
|---|---|
| X1 | 英國、德國、法國 |
| X2 | 法國、西班牙 |
| X3 | 英國 |
我試過使用pivot但unpivot沒有任何成功。任何人都可以建議最好的方法。
uj5u.com熱心網友回復:
假設您的列是固定的,您可以在值子句中使用條件案例運算式和string_agg - 需要 SQL Server 2017
select item, String_Agg(Countries, ', ') Countries
from t
cross apply(values
(case when [united kingdom] = 1 then 'United Kingdom' end),
(case when Germany = 1 then 'Germany' end),
(case when France = 1 then 'France' end),
(case when Spain = 1 then 'Spain' end)
)c(Countries)
group by Item
uj5u.com熱心網友回復:
如果您的列是固定的:
SELECT item, STRING_AGG(countries, ',')
FROM (
SELECT item, countries, value
FROM sales p
UNPIVOT(value FOR countries IN ([United Kingdom],Germany,France,Spain)) AS unpvt
WHERE VALUE = 1
) a
GROUP BY item
如果不:
declare @columns varchar(max)
select @columns = STUFF((select ',[' name ']'
from sys.columns
where object_id = Object_id('sales') and
name <>'item' FOR XML PATH('')), 1, 1, '')
exec('
SELECT item, STRING_AGG(countries, '','')
FROM (
SELECT item, countries, value
FROM sales p
UNPIVOT(value FOR countries IN (' @columns ')) AS unpvt
WHERE VALUE = 1
) a
GROUP BY item')
uj5u.com熱心網友回復:
您可以使用 UNPIVOT,您的查詢將是(SQL server 2017 或更高版本):
SELECT item
,STRING_AGG(countries, ',')
FROM (
SELECT item
,countries
,value
FROM (
SELECT item
,[United Kingdom]
,Germany
,France
,Spain
FROM dbo.Sales
) p
UNPIVOT(value FOR countries IN (
[United Kingdom]
,Germany
,France
,Spain
)) AS unpvt
WHERE VALUE = 1
) a
GROUP BY item;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431245.html
標籤:sql服务器
