0
SELECT  COUNT(ID) AS RANK1 FROM `db_ranking` WHERE `sid`=2 AND `rank`=1
UNION
SELECT  COUNT(ID) AS RANK2  FROM `db_ranking` WHERE `sid`=2 AND `rank`=2
UNION
SELECT  COUNT(ID) AS RANK3  FROM `db_ranking` WHERE `sid`=2 AND `rank`=3
UNION
SELECT   COUNT(ID)  AS RANK4  FROM `db_ranking` WHERE `sid`=2 AND `rank`=4
UNION
SELECT COUNT(ID) AS RANK5 FROM `db_ranking` WHERE `sid`=2 AND `rank`=5

我想在列中显示每个 SELECT 结果。

所以我想要 5 列,每列都有一个 ID 计数..

所以应该是这样的

RANK1 RANK2 RANK3 RANK4 RANK5
  0     3     5     6     7

我现在不明白..我不知道为什么

4

2 回答 2

1

以下工作正常..

  select
    (SELECT  COUNT(ID) AS RANK1 FROM `db_ranking` WHERE `sid`=2 AND `rank`=1) as Rank1,
    (SELECT  COUNT(ID) AS RANK2  FROM `db_ranking` WHERE `sid`=2 AND `rank`=2) as rank2,
    (SELECT  COUNT(ID) AS RANK3  FROM `db_ranking` WHERE `sid`=2 AND `rank`=3) as rank3,
    (SELECT   COUNT(ID)  AS RANK4  FROM `db_ranking` WHERE `sid`=2 AND `rank`=4) as rank4,
    (SELECT COUNT(ID) AS RANK5 FROM `db_ranking` WHERE `sid`=2 AND `rank`=5) as rank5
    from dual
于 2012-08-02T10:08:31.267 回答
0

最有效的方法是

SELECT
    SUM(CASE WHEN `rank`=1 THEN 1 ELSE 0 END) as Rank1,
    SUM(CASE WHEN `rank`=2 THEN 1 ELSE 0 END) as Rank2,
    SUM(CASE WHEN `rank`=3 THEN 1 ELSE 0 END) as Rank3,
    SUM(CASE WHEN `rank`=4 THEN 1 ELSE 0 END) as Rank4,
    SUM(CASE WHEN `rank`=5 THEN 1 ELSE 0 END) as Rank5
FROM
    `db_ranking`
WHERE
    `sid`=2
于 2012-08-02T10:46:59.847 回答