MySQL - 根据日期和类别提取列表

时间:2013-11-19 16:52:11

标签: mysql sql unique

这是此问题here

的附加内容

我有一张这样的表:

ID_____PostingDate_____PosterID____CategoryID
----------------------------------------------
1______05/01/2012______450_________a
2______05/30/2012______451_________a
3______06/17/2012______451_________b
4______12/10/2012______451_________c
5______06/14/2012______452_________l
6______09/15/2012______452_________l
7______05/01/2012______453_________m
8______07/04/2012______453_________n
9______04/05/2013______454_________p
10_____05/05/2012______454_________l
11_____06/12/2012______455_________x
12_____10/02/2012______455_________x
13_____02/12/2013______455_________y

我正在尝试获取所有PosterID的列表(包括潜在的重复项)&已于2012年5月或6月发布但自此之后未在同一类别中再次发布的CategoryID。

上表中的所需结果:

PosterID_______PostingDate______CategoryID
--------------------------
450____________05/01/2012_______a
451____________05/30/2012_______a
451____________06/17/2012_______b
453____________05/01/2012_______m
454____________05/05/2013_______l

以下是我的尝试:

@Filipe Silva的Curtesy

SELECT DISTINCT PosterID
FROM table1
WHERE PostingDate BETWEEN '2012-05-01' AND '2012-06-30'
AND posterID NOT IN (SELECT PosterID
  FROM table1
  WHERE PostingDate > '2012-07-01');

虽然这只删除了在任何类别中再次发布的那些PosterID,而不是类别

1 个答案:

答案 0 :(得分:1)

您必须跨越CategoryID字段上的两个选择的结果。 我认为这应该有效:

SELECT DISTINCT PosterID
FROM table1 x
WHERE PostingDate BETWEEN '2012-05-01' AND '2012-06-30'
AND posterID NOT IN (SELECT PosterID
  FROM table1 y
  WHERE PostingDate > '2012-07-01' AND x.CategoryID = y.CategoryID);