SQL计算多个标准中的记录

时间:2014-02-19 16:32:39

标签: sql sqlite

使用案例陈述

考虑下面的查询
  SELECT (CASE  
              WHEN [C1].[Date]>='2012-02-19' 
                   AND [C1].[Date]<='2012-07-29' 
                       THEN 'HY1''12'
              WHEN [C1].[Date]>='2012-08-05' 
                   AND [C1].[Date]<='2013-01-27' 
                       THEN 'HY2''12' 
              WHEN [C1].[Date]>='2013-01-06' 
                   AND [C1].[Date]<='2013-06-30' 
                       THEN 'HY1''13' 
          END) AS [Timeperiod],
         MIN([C1].[Date]),
         MAX([C1].[Date]),
         COUNT([C1].[Date])


    FROM [TABLE_1] AS [C1]
GROUP BY [Timeperiod] 

考虑一个日期2013-01-06,这满足多个标准,即HY2&#39; 12和HY1&#13; 13。此日期仅使用上述案例陈述在HY2&#12; 12中计算。我想要一个查询,其中这个日期在HY2&#12; 12和HY1&#13;中计算,结果在一个列中,即在上面查询一个名为Timeperiod的列。

我在下面的表之后,

Time Period|Start Date|End Date  |Count

HY2'12     |05-08-2012|27-01-2013|901

HY1'13     |03-02-2013|30-06-2013|900

HY2'13     |07-07-2013|29-12-2013|902

           |19-02-2012|29-07-2012|905

2 个答案:

答案 0 :(得分:1)

我认为最好的方法是将它分成三个不同的查询:

SELECT 'HY1''12', MIN([C1].[Date]), MAX([C1].[Date]), COUNT(*)
FROM [TABLE_1] AS [C1]
WHERE [C1].[Date]>='2012-02-19' AND [C1].[Date]<='2012-07-29'
UNION ALL
SELECT 'HY2''12', MIN([C1].[Date]), MAX([C1].[Date]), COUNT(*)
FROM [TABLE_1] AS [C1]
WHERE [C1].[Date]>='2012-08-05' AND [C1].[Date]<='2013-01-27'
UNION ALL
SELECT 'HY1''13', MIN([C1].[Date]), MAX([C1].[Date]), COUNT(*)
FROM [TABLE_1] AS [C1]
WHERE [C1].[Date]>='2013-01-06' AND [C1].[Date]<='2013-06-30'

我觉得这个更干净,我相信它会带来更好的表现。

答案 1 :(得分:1)

显然,我正在努力。我想提出一个不同的方法。如果您打算更改将来生成的“报告”,这种方法会更好。

创建“报告”表:

CREATE TABLE reports (name TEXT, start_date TEXT, end_date TEXT);

并将输入范围添加到其中:

INSERT INTO reports VALUES ('HY1''12', '2012-02-19', '2012-07-29'), ('HY2''12', '2012-08-05', '2013-01-27'), ('HY1''13', '2013-01-06', '2013-06-30');

然后以下查询将解决这个问题:

SELECT [reports].[name], [reports].[start_date], [reports].[end_date], COUNT(*)
FROM [TABLE1] AS [C1], [reports]
WHERE [C1].[Date]>=[reports].[start_date] AND [C1].[Date]<=[reports].[end_date]
GROUP BY [reports].[name], [reports].[start_date], [reports].[end_date];