我有一个包含5列的表:ID,Session1,Session2,Session3,Session4。我想要做的是显示每列中相同项目的数量。同一项目不能出现在多个列中。
ID Session1 Session2 Session3 Session4
-- -------- -------- -------- --------
1 Music Web Tech Future
2 Art Articles Search Introduction
3 Music Books Camera Phone
4 Music Glass Cup Future
5 Art Books Tech Future
6 Music Glass Cup Phone
我想在asp.net页面上这样显示它。
音乐:4
艺术:2
网:1
文章:1
书籍:2
玻璃:2
技术:2
搜索:1
相机:1
杯:2
未来:3
介绍:1
电话:2
我如何构建一个SQL查询并在asp.net上显示它们?
答案 0 :(得分:1)
你可以简单地使用:
SELECT
session1,
COUNT(*)
FROM
My_Table
GROUP BY
session1
UNION ALL
SELECT
session2,
COUNT(*)
FROM
My_Table
GROUP BY
session2
...
答案 1 :(得分:1)
使用SQL Server,您可以执行以下操作:
SELECT Session, COUNT(*) FROM (
SELECT Session1 AS Session FROM TableName
UNION ALL
SELECT Session2 AS Session FROM TableName
UNION ALL
SELECT Session3 AS Session FROM TableName
UNION ALL
SELECT Session4 AS Session FROM TableName) T1
GROUP BY Session
它不漂亮,但它应该有用。
答案 2 :(得分:0)
尝试:
Select z.Val, Count(*) ValueCount
From (Select Distinct session1 val From Table Union
Select Distinct session2 val From Table Union
Select Distinct session3 val From Table Union
Select Distinct session4 val From Table) Z
Join Table t on Z.Val In (t.Session1, t.Session2, t.Session3, t.Session4)
Group By z.Val