基于不同日期范围的类似数据的计数

时间:2014-10-14 08:43:18

标签: sql sql-server sql-server-2008

表名 - sql server 2008中的航班

   date       name
2003/04/29  air_France
2003/04/05  Dale_avia 
2003/04/08  Dale_avia 
2003/04/08  Dale_avia 
2003/04/02  Dale_avia 
2003/04/05  Aeroflot  
2003/04/25  Aeroflot  
2003/04/01  Don_avia  
2003/04/01  Don_avia  
2003/04/01  Don_avia  
2003/04/13  Don_avia  
2003/04/13  Don_avia  
2003/04/13  Don_avia  
2003/04/14  Don_avia  
2003/04/14  Don_avia  
2003/04/01  Don_avia  
2005/11/04  British_AW
2005/11/07  British_AW
2005/11/07  British_AW
2005/11/09  British_AW

现在我尝试根据日期列过滤特定日期范围内的名称,我的意思是2003年第4个月的3集,日期在1到10之间,11到20日,21到30日......但我很难框架正确的查询

我想尝试下面的

name       | 1-10  | 11-20  | 21-30
---------------------------------- 
Don_avia   |   4   |   5    |  0 
Aeroflot   |   1   |   0    |  1 

我无法以正确的方式进行正确的查询......

请帮助我..提前谢谢!!!!!!

2 个答案:

答案 0 :(得分:1)

SELECT
  name,  
  SUM(CASE WHEN DAY(date) BETWEEN 1 AND 10 THEN 1 ELSE 0 END) as "1-10",
  SUM(CASE WHEN DAY(date) BETWEEN 11 AND 20 THEN 1 ELSE 0 END) as "11-20",
  SUM(CASE WHEN DAY(date) BETWEEN 21 AND 30 THEN 1 ELSE 0 END) as "21-30"
FROM flights
GROUP BY name

SQL Fiddle

上测试

答案 1 :(得分:0)

SELECT DISTINCT   名,
  (SELECT COUNT(name)FROM flights AS F1 WHERE F.name = F1.name AND DAY(Date)BETWEEN 1和10)AS“1-10”,   (SELECT COUNT(name)FROM FROM AS F2 WHERE F.name = F2.name AND DAY(Date)BETWEEN 11 AND 20)AS“11-20”,   (SELECT COUNT(name)FROM Flights AS F3 WHERE F.name = F3.name AND DAY(Date)BETWEEN 21和30)AS“21-30” 来自航班AS F