我需要获取某个日期过去 3 个预约和接下来 3 个预约。每个查询都会给出预期的结果。我的问题是我需要一起得到结果。我无法使用 UNION,因为我需要在两个查询中使用 ORDER BY。我怎样才能做到这一点?
--This is for the future appointments
SELECT TOP 3
e.Events, e.EventDate
FROM
events e
JOIN
EventMatters em ON em.Events = e.Events
WHERE
Matters = '000122FD-47B6-47B6-47B6-1FCAB474CE53'
AND EventKind = 'D'
AND CONVERT(DATE, e.eventdate) > '2022/05/03'
ORDER BY
e.EventDate
--This is for the past appointments
SELECT TOP 3
e.Events, e.EventDate
FROM
events e
JOIN
EventMatters em ON em.Events = e.Events
WHERE
Matters = '000122FD-47B6-47B6-47B6-1FCAB474CE53'
AND e.EventKind = 'D'
AND CONVERT(DATE, e.eventdate) < '2022/05/03'
ORDER BY
EventDate DESC
你可以做两个
CTE
和UNION ALL
他们
--This is for the future appointments
WITH CTE_AFTER AS(SELECT TOP 3
e.Events, e.EventDate
FROM
events e
JOIN
EventMatters em ON em.Events = e.Events
WHERE
Matters = '000122FD-47B6-47B6-47B6-1FCAB474CE53'
AND EventKind = 'D'
AND CONVERT(DATE, e.eventdate) > '2022/05/03'
ORDER BY
e.EventDate),
CTE_BEFORE AS(
SELECT TOP 3
e.Events, e.EventDate
FROM
events e
JOIN
EventMatters em ON em.Events = e.Events
WHERE
Matters = '000122FD-47B6-47B6-47B6-1FCAB474CE53'
AND e.EventKind = 'D'
AND CONVERT(DATE, e.eventdate) < '2022/05/03'
ORDER BY
EventDate DESC)
SELECT Events, EventDate FROM CTE_AFTER
UNION ALL
SELECT Events, EventDate FROM CTE_BEFORE
如果您不关心最终订单:
SELECT * FROM
(
SELECT TOP (3) ... FROM ... WHERE ... ORDER BY EventDate
) x
UNION ALL
SELECT * FROM
(
SELECT TOP (3) ... FROM ... WHERE ... ORDER BY EventDate DESC
) AS x;
如果您希望按日期排序,最早的在前:
) AS x ORDER BY EventDate;
如果您希望最旧的 3 个按最旧的在前排序,而最新的 3 个按最新的在前排序,则情况会变得有点复杂,但仍然可行。