ID GROUP NAME
1 1,2, Supreeth
2 1,2,5, Aishu
3 3, Arvi
4 4,5, Gani
5 4,3,2, Jyo
6 3,2,1, Upi
7 2,3,4,1,5, Savi
我有这样的表,我正试图得到小组的数量
DECODE Count
1 A 4
2 B 5
3 C 4
4 D 3
5 E 3
我想将group的值解码为DECODE值,例如1到A,2到B,3到C,4到D,5到E ..
我试着这样但是得到错误
select count(*) from s_c where age like '%1%' and '%2%' and '%3%';
答案 0 :(得分:3)
一种简单的(不一定有效的)方法是获得每个组值的单独计数。请注意,列名Group
正在使用保留字,因此您必须使用适当的分隔标识符表示法。当您使用便携式(SQL标准)双引号时,您必须得到标识符正确的情况;我假设小写 - YMMV。
SELECT 1 AS GroupID, 'A' AS Decode, COUNT(*) AS GroupCount
FROM AnonymousTable
WHERE "group" LIKE '%1%'
GROUP BY GroupID, Decode
UNION
SELECT 2 AS GroupID, 'B' AS Decode, COUNT(*) AS GroupCount
FROM AnonymousTable
WHERE "group" LIKE '%1%'
GROUP BY GroupID, Decode
UNION
SELECT 3 AS GroupID, 'C' AS Decode, COUNT(*) AS GroupCount
FROM AnonymousTable
WHERE "group" LIKE '%1%'
GROUP BY GroupID, Decode
UNION
SELECT 4 AS GroupID, 'D' AS Decode, COUNT(*) AS GroupCount
FROM AnonymousTable
WHERE "group" LIKE '%1%'
GROUP BY GroupID, Decode
UNION
SELECT 5 AS GroupID, 'E' AS Decode, COUNT(*) AS GroupCount
FROM AnonymousTable
WHERE "group" LIKE '%1%'
GROUP BY GroupID, Decode
但这不能很好地扩展;添加另外5组,这是非常不愉快的;加500,这是无法管理的。您最好将数据存储在正确规范化的表中,然后可以使用更简单的SQL进行分析。
Users UserGroups Groups
ID Name UserID GroupID ID Decode
1 Supreeth 1 1 1 A
2 Aishu 1 2 2 B
3 Arvi 2 1 3 C
4 Gani 2 2 4 D
5 Jyo 2 5 5 E
6 Savi 3 3
4 4
4 5
...
以下是简化查询,它可能比原始查询执行得更好,并且可以扩展到任意数量的组(如果需要,可以扩展到数百万):
SELECT u.GroupID, g.Decode, COUNT(*) AS Count
FROM UserGroups AS u
JOIN Groups AS g ON u.GroupID = g.ID
GROUP BY u.GroupID, g.Decode
标准化使生活更轻松 - 这是做这件事的一个原因!
答案 1 :(得分:1)
此解决方案可能不太好或不灵活,因为它取决于硬编码值,但它可以实现所需的输出,如问题中所述:
SELECT 1 AS [Num], 'A' AS Decode, COUNT(*) AS [Count] FROM my_table WHERE [Group] LIKE '%1%'
UNION
SELECT 2 AS [Num], 'B' AS Decode, COUNT(*) AS [Count] FROM my_table WHERE [Group] LIKE '%2%'
UNION
SELECT 3 AS [Num], 'C' AS Decode, COUNT(*) AS [Count] FROM my_table WHERE [Group] LIKE '%3%'
UNION
SELECT 4 AS [Num], 'D' AS Decode, COUNT(*) AS [Count] FROM my_table WHERE [Group] LIKE '%4%'
UNION
SELECT 5 AS [Num], 'E' AS Decode, COUNT(*) AS [Count] FROM my_table WHERE [Group] LIKE '%5%'
答案 2 :(得分:0)
我知道这已经得到了解答,但我想分享我的观点。
我所做的实际上是将逗号分隔列拆分为行然后我只应用计数。至于解码,我只需将数字添加到64并应用将返回ASCII表的大写字母的CHAR函数,而不是手动执行作业...
SELECT Decode,
COUNT(*)
FROM
(
SELECT ID,
CHAR(64+CONVERT(INT,String)) AS Decode,
string
FROM
(
SELECT A.[id],
Split.a.value('.', 'VARCHAR(100)') AS String
FROM
(
SELECT id,
CAST ('<M>' + REPLACE(SUBSTRING([GROUP],0,LEN([GROUP])), ',', '</M><M>') + '</M>' AS XML) AS String
FROM Table1
) AS A CROSS APPLY String.nodes ('/M') AS Split(a)
) T1
) T2
GROUP BY Decode
ORDER BY Decode
只是为了让你知道我到了Column To Rows。
我还创建了一个小提琴here
我昨天会给出答案,但我全神贯注......对不起
Giannis