好的,我有一張表,其中包括:名稱,c_id,日期。SQL Group按日期排序
該表中的某些條目符合某些標準,我可以使用WHERE有效選擇,所以這不是問題。
我想什麼,然後,是一種分組的,除了名稱和C_ID列,三個日期的組:日期 - 1,日期,日期+ 1。換句話說,我希望輸出的每一行代表具有相同名稱和c_id作爲某個相關條目的所有條目,並且該條目發生在該條目之前的一天之前(包括其自身)。
我該怎麼做呢?
--edit:
(EDIT2:起源表應該是Table 1和表2的INNER JOIN ON Table1.id = Table2.id)
樣本數據:
Table1:
id | c_id | date | other stuff
-----------------------------------------------------
01 | abc | 2015/12/09 | whatever
02 | abc | 2015/12/09 | whatever
03 | abc | 2015/12/10 | relevant criterion
04 | abc | 2015/12/11 | whatever
05 | def | 2015/11/15 | whatever
06 | def | 2015/11/16 | relevant criterion
07 | abc | 2015/11/17 | whatever
08 | mnc | 2016/01/02 | whatever
09 | mnc | 2016/01/02 | whatever
10 | mnc | 2016/01/03 | whatever
11 | mnc | 2016/01/03 | whatever
12 | mnc | 2016/01/03 | whatever
13 | mnc | 2016/01/04 | relevant criterion
14 | mnc | 2016/01/05 | whatever
15 | mnc | 2016/01/05 | whatever
16 | mnc | 2016/01/06 | whatever
Table2:
id | Name | other stuff
--------------------------------------
01 | John | whatever
02 | John | whatever
03 | John | whatever
04 | John | whatever
05 | Mary | whatever
06 | Mary | whatever
07 | Mary | whatever
08 | Alice | whatever
09 | Alice | whatever
10 | Alice | whatever
11 | Alice | whatever
12 | Alice | whatever
13 | Alice | whatever
14 | Alice | whatever
15 | Alice | whatever
16 | Alice | whatever
樣品所需的輸出:
Name | c_id | pivot_date | count
------------------------------------------
John | abc | 2015/12/10 | 4
Mary | def | 2015/11/16 | 2
Alice | mnc | 2016/01/04 | 6
(該pivot_date部分沒有特別的必要的一個與相關的標準,所涉及的日期中的任何一個都好)
你可以發佈你到目前爲止嘗試過的SQL嗎? – Haymaker
沒有聚合的'GROUP BY'幾乎沒用。你確定要'GROUP BY'嗎? - 無論如何,您都可以使用自加入來匹配您想要的記錄。 – JimmyB
我不確定我想分組!我很確定我想要的結果,但我並不特別喜歡得到它們的任何方式。我不確定自連接如何找到匹配的記錄?我正在查找的條目通常會在前幾天和第二天之間有幾十條記錄。 (和@Haymaker:我還沒有嘗試過任何東西,我甚至不知道如何開始!) –