我该如何解决这个问题呢?

时间:2014-09-01 07:20:58

标签: sql

我有一个表包含2个名为date,val的字段 数据是

date        val
2014-08-01   A
2014-08-02   B
2014-08-03   A
2014-08-04   A
2014-08-05   B
2014-08-06   B
2014-08-07   A
2014-08-08   A
2014-08-09   B
2014-08-10   A
2014-08-11   A

我想要一个像这样的输出表

MIN        MAX        A B
2014-08-01  2014-08-05 3 2
2014-08-06  2014-08-11 4 2

结果将根据天数计算,例如5天。在这个问题中,我选择了5天的间隔。从这张表中我想找到所选间隔中值“A”的计数和值“B”的计数。 任何人都可以找到解决方案。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

我认为这会对你有所帮助:

    DECLARE @MinDate DATETIME
DECLARE @MaxDate DATETIME
DECLARE @StartDate DATETIME
DECLARE @DayCount INT
DECLARE @A_Count INT
DECLARE @B_Count INT

SET @DayCount = 5
SELECT  TOP 1 @MinDate=[date] FROM table_1 ORDER BY date
SELECT  TOP 1 @MaxDate=[date] FROM table_1 ORDER BY date DESC


CREATE TABLE #temp_table ( 
    _Min DATETIME,
    _Max DATETIME,
    _A INT,
    _B INT
)

SET @StartDate=@MinDate
WHILE @StartDate < @MaxDate
BEGIN
    SELECT @A_Count = COUNT(*) FROM table_1 WHERE date BETWEEN @StartDate AND DATEADD(dd,@DayCount-1,@StartDate) AND val = 'A'
    SELECT @B_Count = COUNT(*) FROM table_1 WHERE date BETWEEN @StartDate AND DATEADD(dd,@DayCount-1,@StartDate) AND val = 'B'
    INSERT INTO #temp_table VALUES (@StartDate,DATEADD(dd,@DayCount-1,@StartDate),@A_Count,@B_Count)
    SET @StartDate = DATEADD(dd,@DayCount,@StartDate)
END
SELECT * FROM #temp_table
DROP TABLE #temp_table

和SqlFiddle演示:click here

答案 1 :(得分:0)

您可以执行以下查询:

SELECT MAX(date), MIN(date), val, COUNT(val) AS occurence
FROM table 
WHERE date>minDate AND date<maxDate
GROUP BY val

minDate maxDate 是您的可变数据。

结果将以这种方式阅读:价值&#34; val&#34; apper&#34;出现&#34; minDate和maxDate之间的时间

答案 2 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(date        DATE NOT NULL
,val CHAR(1) NOT NULL
,PRIMARY KEY (date)
);

INSERT INTO my_table VALUES
('2014-08-01','A'),
('2014-08-02','B'),
('2014-08-03','A'),
('2014-08-04','A'),
('2014-08-05','B'),
('2014-08-06','B'),
('2014-08-07','A'),
('2014-08-08','A'),
('2014-08-09','B'),
('2014-08-10','A'),
('2014-08-11','A');

SELECT MIN(date) min_date
     , MAX(date) max_date
     , SUM(val = 'A') A
     , SUM(val = 'B') B
  FROM my_table 
 GROUP 
    BY CEILING(TO_DAYS(date)/5)*5;

+------------+------------+------+------+
| min_date   | max_date   | A    | B    |
+------------+------------+------+------+
| 2014-08-01 | 2014-08-05 |    3 |    2 |
| 2014-08-06 | 2014-08-10 |    3 |    2 |
| 2014-08-11 | 2014-08-11 |    1 |    0 |
+------------+------------+------+------+