SQL Server 2016 中使用 JSON 的两列字符串聚合
String aggregation with two columns using JSON in SQL Server 2016
我的结果包含如下数据:
CustomerId | Rating (Star) | RatingCount
1 | 1 | 20
1 | 2 | 15
1 | 3 | 4
1 | 4 | 30
1 | 5 | 36
2 | 1 | 5
2 | 2 | 4
2 | 5 | 10
但我想将结果转换为:
CustomerId | CustomerRatings
1 | { "1": 20, "2": 15, "3": 4 , "4": 30, "5": 36 }
2 | { "1": 5, "2": 4, "5": 10 }
我使用 FOR JSON 路径函数将数据转换为
@JSONString = {"_":"1","__":20},{"_":"2","__":15},{"_":"3","__":4},{"_":"4","__":30},{"_":"5","__":36}
然后使用replace方法得到实际结果。
SELECT REPLACE(REPLACE(REPLACE(@JSONString,'"_":',''),',"__":',':'),'},{',',')
{"1":20,"2":15,"3":4,"4":30,"5":36}
有没有更好的方法来实现?我最近几天开始使用 SQL server 2016。
假设评分总是在 1 到 5 之间:
SELECT CustomerId, (
SELECT MIN(CASE WHEN Rating = 1 THEN RatingCount END) AS [1]
, MIN(CASE WHEN Rating = 2 THEN RatingCount END) AS [2]
, MIN(CASE WHEN Rating = 3 THEN RatingCount END) AS [3]
, MIN(CASE WHEN Rating = 4 THEN RatingCount END) AS [4]
, MIN(CASE WHEN Rating = 5 THEN RatingCount END) AS [5]
FROM t AS x
WHERE x.CustomerId = t.CustomerId
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER
)
FROM t
GROUP BY CustomerId
使用 INCLUDE_NULL_VALUES
选项来包含空值,或 COALESCE(..., 0)
将空值转换为零。
我的结果包含如下数据:
CustomerId | Rating (Star) | RatingCount
1 | 1 | 20
1 | 2 | 15
1 | 3 | 4
1 | 4 | 30
1 | 5 | 36
2 | 1 | 5
2 | 2 | 4
2 | 5 | 10
但我想将结果转换为:
CustomerId | CustomerRatings
1 | { "1": 20, "2": 15, "3": 4 , "4": 30, "5": 36 }
2 | { "1": 5, "2": 4, "5": 10 }
我使用 FOR JSON 路径函数将数据转换为
@JSONString = {"_":"1","__":20},{"_":"2","__":15},{"_":"3","__":4},{"_":"4","__":30},{"_":"5","__":36}
然后使用replace方法得到实际结果。
SELECT REPLACE(REPLACE(REPLACE(@JSONString,'"_":',''),',"__":',':'),'},{',',')
{"1":20,"2":15,"3":4,"4":30,"5":36}
有没有更好的方法来实现?我最近几天开始使用 SQL server 2016。
假设评分总是在 1 到 5 之间:
SELECT CustomerId, (
SELECT MIN(CASE WHEN Rating = 1 THEN RatingCount END) AS [1]
, MIN(CASE WHEN Rating = 2 THEN RatingCount END) AS [2]
, MIN(CASE WHEN Rating = 3 THEN RatingCount END) AS [3]
, MIN(CASE WHEN Rating = 4 THEN RatingCount END) AS [4]
, MIN(CASE WHEN Rating = 5 THEN RatingCount END) AS [5]
FROM t AS x
WHERE x.CustomerId = t.CustomerId
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER
)
FROM t
GROUP BY CustomerId
使用 INCLUDE_NULL_VALUES
选项来包含空值,或 COALESCE(..., 0)
将空值转换为零。