简体   繁体   English

SQL 查询返回记录数,用于两列的唯一组合

[英]SQL Query to return count of records for unique combination of two columns

I am looking to count how many routes each code has per week.我正在计算每个代码每周有多少条路线。 This would mean I want to find how many routes there are for each combination of code and year_of_week.这意味着我想找出代码和 year_of_week 的每种组合有多少条路线。 I have a set of data as follows:我有一组数据如下:

Data:
Code    Year_and_Week   Route
1       201501          A
1       201501          B
1       201523          C
1       201633          A
1       201633          A           
1       201643          A
1       201643          B
1       201643          C
1       201643          D
2       201503          A
2       201503          C
2       201520          A
2       201624          B           
2       201624          B
3       201643          A
3       201643          C
3       201643          D

I have a code snippet that works to retreive my desired result, but only when I input a "Where code= #" line in the code.我有一个代码片段可以检索我想要的结果,但只有当我在代码中输入“Where code = #”行时。 I want the results to output for each code type.我希望每种代码类型的结果为 output。

Select Year_and_Week, Count(Route)
From Deliveries
Where Code=1
Group BY Year_and_Week

Desired Output:所需的 Output:

Code    Year_and_Week   Route_Count
1       201501          2
1       201523          1
1       201633          2           
1       201643          4
2       201503          2
2       201520          1
2       201624          2
3       201643          3

I am trying to get this output so that I can then take a maximum and minimum of Route_Count for each code for analysis purposes using a CTE like...我正在尝试获取此 output 以便我可以使用像...

With Route_Number_CTE (Year_and_Week, Route_Count) As(
Select Year_And_Week, Count(Route)
From Deliveries
Where Code=1
Group BY Year_and_Week
)

select min(Route_Count),max(Route_Count)
From Route_Number_CTE;

Just add code to the select and group by clauses:只需将code添加到select并按子句group by

select code, year_and_week, count(route) no_routes
from deliveries
group by code, year_and_week

Note that count(route) counts only non- null values of route .请注意, count(route)仅计算route的非null值。 If this column is not nullable (or if you want to take in account null values), this is simpler and more efficiently written:如果此列不可为空(或者如果您想考虑null值),则更简单且更有效地编写:

select code, year_and_week, count(*) no_routes
from deliveries
group by code, year_and_week

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM