2014-09-01 282 views
-3

我有一臺包含命名爲日2場,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」的計數。 任何人都可以找到解決方案。任何幫助將不勝感激。

+2

要快速解決,您應該快速編輯並格式化您的問題。 btw是什麼問題? – deterministicFail 2014-09-01 07:24:03

+0

如何在輸出表中確定MIN和MAX? – ydoow 2014-09-01 07:27:47

+0

@ydoow我編輯了我的問題 – aparna 2014-09-01 07:33:19

回答

0

您可以執行下面的查詢:

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

其中的minDate的maxDate是你varables。

結果會以這種方式閱讀:值 「VAL」 的minDate和的maxDate

之間的衝擊片雷管 「occurence」 時間
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 @[email protected] 
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

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 | 
+------------+------------+------+------+