像這樣的東西應該爲你的榜樣4箱子做到這一點:
select 'W' as [Value], count(*) as Count from Table1
where Col1='W' or Col2='W' or Col3='W' or Col4='W' union
select 'X' as [Value], count(*) as Count from Table1
where Col1='X' or Col2='X' or Col3='X' or Col4='X' union
select 'Y' as [Value], count(*) as Count from Table1
where Col1='Y' or Col2='Y' or Col3='Y' or Col4='Y' union
select 'Z' as [Value], count(*) as Count from Table1
where Col1='Z' or Col2='Z' or Col3='Z' or Col4='Z'
演示:http://www.sqlfiddle.com/#!3/68aa3/11
編輯:如果有很多可能的值,這可以進一步簡化通過unioning所有可能的值,並將其動態計數:
select V.Value as [Value],
count(IIF(col1=[Value] or col2=[Value]
or col3=[Value] or col4=[Value],1,NULL)) as [Count]
from Table1, (
select distinct col1 as [Value] from table1 union
select distinct col2 from table1 union
select distinct col3 from table1 union
select distinct col4 from table1) V
where V.value is not null
group by V.value
+1非常聰明的工作對我罰款。你是對的,就是這麼簡單:) – mellamokb
感謝您的幫助!這很好。 – dooms13