多列条件计数SQL

时间:2012-05-15 14:57:16

标签: asp.net sql ms-access

我试图计算连续4个单独列中的不同条目,然后计算结果总数。

例如,表头看起来与此类似:

ID       Col1    Col2    Col3    Col4

每列(保存ID)可以包含文本值W,X,Y或Z.列可以具有相同的值。

我想要做的是计算一个计算列中每个条目的方法,但每行只计算一次W,X,Y和Z.所以如果:

ID       Col1    Col2    Col3    Col4
          X        X       Y
          Y        W       X
          Z        Y       Y

结果表将是:

    Value    Count
      W        1
      X        2
      Y        3
      Z        1

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

这样的事情应该为你的例子做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


编辑:如果有很多可能的值,可以通过合并所有可能的值并动态计算它们来进一步简化:

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 :(得分:3)

也许我错过了一些东西,但这会很简单:

Select Val, Count(*)
From    (
        Select Id, Col1 As Val From Table1
        Union Select Id, Col2 From Table1
        Union Select Id, Col3 From Table1
        Union Select Id, Col4 From Table1
        ) As Z
Where Z.Val Is Not Null
Group BY Z.Val

没有理由一起使用DistinctUnion,因为Union会使结果与众不同。因此,我们需要为每一行(Id)包含唯一值。

SQL Fiddle(这使用SQL Server但在MS Access中使用相同的语法)