【发布时间】:2019-01-15 09:40:05
【问题描述】:
我在 SQL 存储过程中有一个 CTE,它是来自两个数据库的 UNIONing 值 - 这些值是客户编号和该客户的最后订购日期。
这里是原始 SQL -
;WITH CTE_last_order_date AS
(
SELECT c1.customer ,MAX(s2.dt_created) AS last_order_date
FROM customers c1 WITH (NOLOCK)
LEFT JOIN archive_orders s2 WITH (NOLOCK)
ON c1.customer = s2.customer
GROUP BY c1.customer
UNION ALL
SELECT c1.customer ,MAX(s1.dt_created) AS last_order_date
FROM customers c1 WITH (NOLOCK)
LEFT JOIN orders s1 WITH (NOLOCK)
ON c1.customer = s1.customer
GROUP BY c1.customer
)
示例结果:
customer, last_order_date
CF122595, 2011-11-15 15:30:22.000
CF122595, 2016-08-15 10:01:51.230
(2 row(s) affected)
这显然不适用于UNION distinct records 规则,因为日期值不匹配,这意味着 SQL 从 两个 表中返回了最大值(即最终记录集不是不同的)
为了解决这个问题,我尝试了从 this question 借来的另一种方法并实现了分组:
;WITH CTE_last_order_date AS
(
SELECT max(last_order_date) as 'last_order_date', customer
FROM (
SELECT distinct cust.customer, max(s2.dt_created) AS last_order_date, '2' AS 'group'
FROM customers c1 WITH (NOLOCK)
LEFT JOIN archive_orders s2 WITH (NOLOCK)
ON c1.customer = s2.customer
GROUP BY c1.customer
UNION
SELECT distinct c1.customer, max(sord.dt_created) AS last_order_date, '1' AS 'group'
FROM customers c1 WITH (NOLOCK)
LEFT JOIN orders s1 WITH (NOLOCK)
ON cust.customer = sord.customer
GROUP BY
c1.customer
) AS t
GROUP BY customer
ORDER BY MIN('group'), customer
)
示例结果:
customer, last_order_date
CF122595, 2016-08-15 10:01:51.230
(1 row(s) affected)
这有一个工作正常的区别(哈哈),直到进入阻止ORDER BY 在公用表表达式中的规则,这是选择最低组所必需的(这意味着实时订单(第 1 组) ,其日期需要优先于存档(第 2 组))。
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
感谢所有帮助或想法。
【问题讨论】:
-
您必须在 CTE 之外订购,除非您使用的是 SELECT TOP ,否则需要订购。您可以在 CTE 之外订购。那么你需要什么订单?你想在这里返回什么?你能给出示例数据和结果吗?你是说你想要两张桌子的最大值吗?如果是合并子查询中的两个表,则取子查询的最大值。
-
添加了更多细节,包括结果。
标签: sql-server sql-server-2008-r2 common-table-expression