SELECT *
FROM tasks
LEFT JOIN plans
ON plans.task_id = tasks.id
WHERE plan.week IS NULL OR (plan.week < DATEPART(week, GetDate()) AND plan.Year = YEAR(GETDATE())
您不应该使用SELECT *
, 明确写出您需要的每一列。您没有提到是否也有年份列,您必须处理周数和年份。如果您只处理一周#,您将获得多年的结果。
听起来你可以只使用任务描述???如果可以使用任务描述,为什么要基于周列?
SELECT *
FROM tasks
LEFT JOIN plans
ON plans.task_id = tasks.id
WHERE tasks.description = 'Past' OR tasks.description = 'Not planned'
啊哈,我现在了解您的数据,您可以有多个任务,但周数不同。这很简单,只需使用查询找到 MAX(Week#) GROUP BY 任务然后执行查询,我会写下来给我一分钟...
CREATE TABLE #MyTest
(
TaskID int,
TaskYear int,
TaskWeek int
)
INSERT INTO #MyTest(TaskID,TaskYear,TaskWeek)
VALUES (1, 2012, 4)
INSERT INTO #MyTest(TaskID,TaskYear,TaskWeek)
VALUES (2, 2012, 5)
INSERT INTO #MyTest(TaskID,TaskYear,TaskWeek)
VALUES (2, 2012, 36)
INSERT INTO #MyTest(TaskID,TaskYear,TaskWeek)
VALUES (3, 2012, 36)
INSERT INTO #MyTest(TaskID,TaskYear,TaskWeek)
VALUES (4, 2012, NULL)
INSERT INTO #MyTest(TaskID,TaskYear,TaskWeek)
VALUES (6, 2011, 5)
INSERT INTO #MyTest(TaskID,TaskYear,TaskWeek)
VALUES (6, 2010, 36)
SELECT
TaskID,
MAX(TaskWeek) AS WeekNumber,
TaskYear
FROM
#MyTest
GROUP BY
TaskID,
TaskWeek,
TaskYear
HAVING MAX(TaskWeek) < DatePart(week, GetDate()) OR MIN(TaskWeek) IS NULL
DROP TABLE #MyTest
现在,这将为您提供每个task.id
具有最大周数的唯一行。
最后结果
根据您的最终评论:
将此复制并粘贴到 sql management studio 中,我已为您评论:
CREATE TABLE #MyTest
(
TaskID int,
TaskDate datetime
)
--test for only in the past NOTHING in the future
INSERT INTO #MyTest(TaskID, TaskDate)
VALUES (1, '1998-01-01')
--test for planned in the future NOTHING in the past
INSERT INTO #MyTest(TaskID,TaskDate)
VALUES (3, '2012-12-24')
--test for no plan as all (IS NULL)
INSERT INTO #MyTest(TaskID,TaskDate)
VALUES (4, null)
--test for planned in the past but has an upcoming event in the future
INSERT INTO #MyTest(TaskID,TaskDate)
VALUES (6, '2011-12-23')
INSERT INTO #MyTest(TaskID,TaskDate)
VALUES (6, '2012-12-23')
INSERT INTO #MyTest(TaskID,TaskDate)
--test for planned in the past, NO upcoming event in the future
VALUES (8, '2012-1-23')
INSERT INTO #MyTest(TaskID,TaskDate)
VALUES (8, '2012-6-23')
--result should show:
-- task id = 1 (because of: performed in past but nothing in the future)
-- task id = 4 (because of: no plan at all)
-- task id = 8 (because of: only past)
SELECT
TaskID,
YEAR(TaskDate) AS TheYear,
DatePart(week, TaskDate) AS WeekNumber
FROM
#MyTest
WHERE
--handle no planning of a task...
((TaskDate IS NULL)
--eliminate any task id that is out in the future
OR TaskID NOT IN (SELECT TaskID FROM #MyTest WHERE TaskDate > GetDate()))
GROUP BY
TaskID,
Year(TaskDate),
DatePart(week, TaskDate)
DROP TABLE #MyTest