MySQL计算多列中值的存在

时间:2013-10-04 17:54:20

标签: mysql sql

我有一个名为Customers的表,其中包含CustID列和另外三个名为Prod1,Prod2,Prod3的列。 Prod列的每个客户的值为“0”或“1”,表示客户是否拥有该特定产品(1 =他们拥有该产品,0 =他们没有),即:

      CustID   Prod1   Prod2   Prod3
     -------------------------------
      001     1       1        0
      002     0       0        1
      003     1       1        1
      004     1       0        1

我想得到每个产品有多少客户,即我的输出需要:

      Prod   Count   
     --------------
      Prod1   3  
      Prod2   2     
      Prod3   3    

谢谢!

1 个答案:

答案 0 :(得分:0)

SELECT "Prod1" AS Prod, Sum(Prod1) As [Count] FROM Customers
UNION
SELECT "Prod2" AS Prod, Sum(Prod2) As [Count] FROM Customers
UNION
SELECT "Prod3" AS Prod, Sum(Prod3) As [Count] FROM Customers