我有一个表cricket_overs
,它有两个列,如下所示
mid overs
1 3
2 5
3 6
4 8
5 10
我需要在0-3到4-6和>6之间的中间位置数,输出应该是
for 0-3 overs ---count of mid 1
for 4-6 overs ---count of mid 2
for >6 overs ---count of mid 2
--output
count
1
2
2
如何编写查询?
发布于 2017-10-23 10:32:18
为了回答这个问题,我做了以下工作(表+数据):
CREATE TABLE cricket_score
(
mid INTEGER NOT NULL,
overs INTEGER NOT NULL
);
INSERT INTO cricket_score VALUES
(1, 3),
(2, 5),
(3, 6),
(4, 8),
(5, 10);
运行查询:
SELECT my_count, COUNT(my_count) AS the_score
FROM
(
SELECT
mid, overs, -- <<-- this line is unnecessary - helpful for understanding!
CASE -- <<-- Just run the subquery on its own.
WHEN overs BETWEEN 1 AND 3 THEN 'mid_1'
WHEN overs BETWEEN 4 AND 6 THEN 'mid_2'
WHEN overs > 6 THEN 'mid_3'
END AS my_count
FROM cricket_score
) AS STUFF
GROUP BY my_count
ORDER BY my_count;
并得到了以下结果:
my_count the_score
mid_1 1
mid_2 2
mid_3 2
DB-小提琴这里!DB-小提琴是为PostgreSQL而设的--另一个站点,SQLFiddle.com又出了问题(再次!)而数据库-小提琴没有MS服务器,但这是相当标准的东西-应该没有问题的任何服务器!
发布于 2017-10-23 10:12:34
select count(*) from table where overs >=0 and overs <= 3
从这里开始,您应该能够扩展到一个完整的解决方案。你的问题没有显示出任何努力。
https://dba.stackexchange.com/questions/189077
复制相似问题