我试图将子查询的结果用作外部查询的派生表,然后对子查询中的信息进行计数和分组。这是我的SQL知识的一部分,尽管在线查看了多个示例,但我并没有很好地获得正确的语法。
子查询是:
SELECT rname.rn_country AS country, rname.rn_index AS id, sum(rresults.rr_sec_total) AS time
FROM rname
INNER JOIN rresults AS rresults ON rname.rn_index = rresults.rr_rn_index
WHERE rn_view = 'true'
AND rr_date = '6/6/2012'
AND (rr_slide = 'standard' OR rr_slide = 'water')
GROUP BY rn_index, rn_country
HAVING SUM (rresults.rr_sec_total) >= 18000
这个结果是:
country id time CAN 19700 57600 USA 451294 144600.9 USA 901260 39601.8 USA 934270 109800 DEN 913601 31800 USA 915011 108720.9
我需要做的是计算其中(时间> = 18000且时间< = 36000)为青铜,(时间> = 36000和< = 54000)为银的ID的数量,以及时间&gt ;超过54000是黄金,按国家分组。因此,根据上述值的结果,最终结果将是:
CAN:1金
DEN:1个铜牌
美国:3金1银
鉴于此,完整查询需要什么?提前致谢。任何帮助表示赞赏。
答案 0 :(得分:1)
为什么不在各个列中获取计数:
SELECT
a.country,
COUNT(CASE WHEN a.time > 54000 THEN 1 END) AS num_gold,
COUNT(CASE WHEN a.time BETWEEN 36000 AND 54000 THEN 1 END) AS num_silver,
COUNT(CASE WHEN a.time BETWEEN 18000 AND 36000 THEN 1 END) AS num_bronze
FROM
(
SELECT rname.rn_country AS country, rname.rn_index AS id, sum(rresults.rr_sec_total) AS time
FROM rname
INNER JOIN rresults AS rresults ON rname.rn_index = rresults.rr_rn_index
WHERE rn_view='true' AND rr_date='6/6/2012' AND (rr_slide='standard' OR rr_slide='water')
GROUP BY rn_index, rn_country having sum(rresults.rr_sec_total) >= 18000
) a
GROUP BY a.country