一种简单(不一定有效)的方法是获取每个组值的单独计数。请注意,列名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
标准化让生活更轻松——这是这样做的原因之一!