我想从同一个表的多个列中选择不同的值及其计数 例
,输出应该是这样的
答案 0 :(得分:1)
由于OP在他的评论中说他使用MYSQL这应该可行
SELECT data,COUNT(data)
FROM
(
SELECT COL1 data
FROM tableso
UNION ALL
SELECT COL2
FROM tableso
UNION ALL
SELECT COL3
FROM tableso
UNION ALL
SELECT COL4
FROM tableso
UNION ALL
SELECT COL6
FROM tableso
UNION ALL
SELECT COL7
FROM tableso
) finaltable group by data;
SQL FIDDLE:http://sqlfiddle.com/#!2/1f8cf/10
我认为接受的答案不适用于MYSQL
更新:
op已经改变了他对数据库(到MSSQL)的看法,并且接受的答案都有db版本
答案 1 :(得分:1)
由于您也在使用Sql Server
,因此会建议您这样做
使用Table valued constructor
将列转换为行,然后count
name
这将避免多个表扫描。
SELECT name,
[count]=Count(1)
FROM yourtable
CROSS apply (VALUES (col1),(COL2),(col3),(col4),(COL6),(col7)) cs (name)
GROUP BY name
注意:这在Mysql
答案 2 :(得分:-2)
获取所有列值到一行并找到计数
SQL SERVER
;WITH CTE AS
(
SELECT COL1 Name
FROM YOURTABLE
UNION ALL
SELECT COL2
FROM YOURTABLE
UNION ALL
SELECT COL3
FROM YOURTABLE
UNION ALL
SELECT COL4
FROM YOURTABLE
UNION ALL
SELECT COL6
FROM YOURTABLE
UNION ALL
SELECT COL7
FROM YOURTABLE
)
SELECT DISTINCT Name,COUNT(Name) OVER(PARTITION BY Name) [COUNT]
FROM CTE
<强> MYSQL 强>
SELECT Name,COUNT(*) [COUNT]
(
SELECT COL1 Name
FROM #TEMP
UNION ALL
SELECT COL2
FROM #TEMP
UNION ALL
SELECT COL3
FROM #TEMP
UNION ALL
SELECT COL4
FROM #TEMP
UNION ALL
SELECT COL6
FROM #TEMP
UNION ALL
SELECT COL7
FROM #TEMP
)TAB
GROUP BY Name