好的,我有一张表,其中包括:名称,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:我还没有尝试过任何东西,我甚至不知道如何开始!) –