gpt4 book ai didi

SQL查询统计频率

转载 作者:行者123 更新时间:2023-12-04 14:03:22 25 4
gpt4 key购买 nike

我有一个表格,里面有类似的条目

id     keywords
1 cat, dog, man, mouse
2 man, pen, pencil, eraser
3 dog, man, friends
4 dog, leash,......

我想做一个类似的表格

id  cat  dog  man  mouse  pen  pencil  eraser  friends  leash ......
1 1 1 1 1 0 0 0 0 0
2 0 0 1 0 1 1 1 0 0
3 0 1 1 0 0 0 0 1 0

等等。

最佳答案

WITH basedata(id,keywords) AS
(
SELECT 1,'cat, dog, man, mouse' union all
SELECT 2 ,'man, pen, pencil, eraser' union all
SELECT 3,'dog, man, friends' union all
SELECT 4,'dog, leash'
),
cte(id, t, x)
AS (SELECT *,
CAST('<foo>' + REPLACE(keywords,',','</foo><foo>') + '</foo>' AS XML)
FROM basedata)
SELECT id,
LTRIM(RTRIM(w.value('.', 'nvarchar(max)'))) as keyword
INTO #Split
FROM cte
CROSS APPLY x.nodes('//foo') as word(w)


DECLARE @ColList nvarchar(max)

SELECT @ColList = ISNULL(@ColList + ',','') + keyword
FROM (
SELECT DISTINCT QUOTENAME(keyword) AS keyword
FROM #Split
) T

EXEC(N'
SELECT *
FROM #Split
PIVOT (COUNT(keyword) FOR keyword IN (' + @ColList + N')) P')

DROP TABLE #Split

给予

id          cat         dog         eraser      friends     leash       man         mouse       pen         pencil
----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
1 1 1 0 0 0 1 1 0 0
2 0 0 1 0 0 1 0 1 1
3 0 1 0 1 0 1 0 0 0
4 0 1 0 0 1 0 0 0 0

关于SQL查询统计频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5594430/

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