我是PIVOT函数的新手,到目前为止,在旋转表时我无法成功运行任何查询。
这是数据源:
region countries
Africa 180
Antarctica 3
Asia 99
Europe 154
Middle East 54
North America 123
Oceania 87
South America 48
我需要每个区域都变成一列-仅包含该区域中国家/地区的一行。
兼容性级别:SQL Server 2019(150)
我尝试了所有可以在网上找到的建议,但仍然不明白我在做什么错。
SELECT [Africa], [Asia], [Middle East], [North America],
[Oceania], [South America], [Antarctica]
FROM (
SELECT region, count(name) as countries
FROM dbo.country
Group by region
) AS pDataSource
PIVOT
(
countries
FOR region IN ([Africa], [Asia], [Middle East], [North America],
[Oceania], [South America], [Antarctica])
) AS pPivotTable
第156条消息,第15级,状态1,第10行
关键字“ FOR”附近的语法不正确。
答案 0 :(得分:1)
您缺少聚合通知sum(countries)
...
PIVOT
(
sum(countries)
FOR region IN ([Africa], [Asia], [Middle East], [North America],
[Oceania], [South America], [Antarctica])
) AS pPivotTable
答案 1 :(得分:0)
为什么不只使用条件聚合?
const isUnknownRecord = (u: unknown): u is Record<string, unknown> =>
typeof u === 'object' && u !== null
export function serialize(data: unknown): string {
if (data === null) {
return ''
}
if (isUnknownRecord(data)) {
let serializedData = ''
for (const k of Object.keys(data).sort()) {
serializedData += k
if (data[k] !== null) {
serializedData += serialize(data[k])
}
}
return serializedData
}
return String(data)
}