如何对多列进行小计

时间:2013-08-21 14:28:14

标签: mysql sql

我正在写一个投票比赛,人们可以为他们的第一,第二,第三和第四喜欢的乐队投票。我最终得到了这样一张桌子:

   first      second      third     fourth
   band1      band2       band3     band4
   band1      band2       band4     band3
   band4      band3       band2     band1

我想要检索的是一个视图,显示每个乐队的小计投票如下:

           first     second    third   fourth
  band1      2          0        0        1
  band2      0          2        1        0
  band3      0          1        1        1
  band4      1          0        1        1

我尝试使用GROUP BY和ROLLUP,但我没有得到我需要的东西。有不同数量的乐队。

我怎样才能做到这一点? TIA

更新:我的数据显然没有正常化。我们假设有一个包含波段名称列表的表。那我们怎么能得到上面的结果呢?

2 个答案:

答案 0 :(得分:2)

鉴于这种情况,这里采用了一种愚蠢的方法(假设有一个固定的firstsecondthirdfourth列号({{3 }}):

SELECT band,
       (SELECT COUNT(*) FROM votes WHERE first = band) AS first,
       (SELECT COUNT(*) FROM votes WHERE second = band) AS second,
       (SELECT COUNT(*) FROM votes WHERE third = band) AS third,
       (SELECT COUNT(*) FROM votes WHERE fourth = band) AS fourth
FROM (
  SELECT DISTINCT band
  FROM (
    SELECT first AS band FROM votes
    UNION ALL
    SELECT second AS band FROM votes
    UNION ALL
    SELECT third AS band FROM votes
    UNION ALL
    SELECT fourth AS band FROM votes
  ) x
) y
-- optionally:
ORDER BY band

但是,我建议将数据标准化,以便乐队在他们自己的表中:

-- First create a table to store the values
CREATE TABLE bands
(
  name        VARCHAR(255), -- or whatever `first`,`second`,`third`&`fourth` are
  PRIMARY KEY (name),
  UNIQUE KEY  (name)
);

-- then populate it with unique entries
INSERT INTO bands (name)
SELECT DISTINCT band
FROM (
  SELECT first AS band FROM votes
  UNION ALL
  SELECT second AS band FROM votes
  UNION ALL
  SELECT third AS band FROM votes
  UNION ALL
  SELECT fourth AS band FROM votes
) t

从那里你可以从乐队表中选择并引入在投票表中找到的计数。

答案 1 :(得分:0)

没有正常化总是一种痛苦。如果这只是一个包含所有数据的表,则可以单独使用这样的内容:

select   first as "band",
         distinct count(first) as "first"
from     table
group by first

这将产生

band  first
band1 2
band2 0
band3 0
band4 1