1

我正在写一个投票比赛,人们可以投票选出他们最喜欢的第一、第二、第三和第四个乐队。我最终得到一个这样的表:

   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

更新:我的数据显然没有标准化。假设有一个包含乐队名称列表的表格。那么我们怎样才能得到上面的结果呢?

4

2 回答 2

2

鉴于这种情况,这是一种 hacky 方法(假设固定firstsecond,thirdfourth列号(example):

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

从那里您可以从乐队表中进行选择,并带入投票表中的计数。

于 2013-08-21T15:08:11.390 回答
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
于 2013-08-21T15:19:59.283 回答