[英]SQL Count items in each category choosing only two of the available categories
I have a table like so:我有一张这样的桌子:
Year年 | Stage阶段 | Participant参与者 |
---|---|---|
2000 2000 | 1 1 | Peter彼得 |
2000 2000 | 1 1 | John约翰 |
2000 2000 | 1 1 | Daniel丹尼尔 |
2000 2000 | 2 2 | Peter彼得 |
2000 2000 | 2 2 | John约翰 |
2000 2000 | 2 2 | Steve史蒂夫 |
2000 2000 | 3 3 | Daniel丹尼尔 |
2000 2000 | 3 3 | John约翰 |
2001 2001年 | 1 1 | Peter彼得 |
2001 2001年 | 1 1 | John约翰 |
2001 2001年 | 1 1 | Daniel丹尼尔 |
2001 2001年 | 2 2 | Peter彼得 |
2001 2001年 | 2 2 | Steve史蒂夫 |
2001 2001年 | 3 3 | Daniel丹尼尔 |
2001 2001年 | 3 3 | John约翰 |
2001 2001年 | 4 4 | Peter彼得 |
2001 2001年 | 4 4 | John约翰 |
2001 2001年 | 4 4 | Daniel丹尼尔 |
And what I need is to count the Participants in the first and last Stage and sort by year.我需要的是统计第一阶段和最后阶段的参与者,并按年份排序。
So far I got this到目前为止我得到了这个
SELECT year, stage, Count(Participant) as Participants FROM table
WHERE Stage=1 or Stage=????
GROUP BY Stage
ORDER by Year
The problem is that each year has different amount of stages so I'm having problems on how to find and set as a parameter the LAST stage of each year问题是每年都有不同数量的阶段,所以我在如何找到每年的最后阶段并将其设置为参数时遇到问题
The output should look like this:输出应如下所示:
Year年 | Stage阶段 | Participants参与者 |
---|---|---|
2000 2000 | 1 1 | 3 3 |
2000 2000 | 3 3 | 2 2 |
2001 2001年 | 1 1 | 3 3 |
2001 2001年 | 4 4 | 3 3 |
This should work for both MySQL & SQL Server:这应该适用于 MySQL 和 SQL Server:
WITH CTE AS(
SELECT Year,MIN(Stage) AS FirstStage, MAX(Stage) AS LastStage
FROM Table1
GROUP BY Year
)
SELECT T.Year,T.Stage,COUNT(Participant) AS Participants
FROM Table1 T
JOIN CTE ON T.Year = CTE.Year AND (T.Stage = CTE.FirstStage OR T.Stage = CTE.LastStage)
GROUP BY T.Year,T.Stage
Output:输出:
Year年 | Stage阶段 | Participants参与者 |
---|---|---|
2000 2000 | 1 1 | 3 3 |
2000 2000 | 3 3 | 2 2 |
2001 2001年 | 1 1 | 3 3 |
2001 2001年 | 4 4 | 3 3 |
See this db<>fiddle看到这个db<>fiddle
Using your existing query and just filling in "the blanks" you can use a correlated subquery使用您现有的查询并填写“空白”,您可以使用相关子查询
select year, stage, Count(*) as Participants
from t
where Stage = 1
or Stage = (select Max(stage) from t t2 where t2.year = t.year)
group by Stage, Year
order by year
This is likely to be the most performant but other variations are possible, such as using window functions:这可能是性能最高的,但也可以使用其他变体,例如使用窗口函数:
select distinct year, stage, Participants
from (
select Year, stage,
First_Value(stage) over(partition by year order by stage) Fstage,
First_Value(stage) over(partition by year order by stage desc) Lstage,
Count(*) over(partition by year, stage) Participants
from t
)t
where stage in (Fstage, Lstage)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.