我想知道我是否可以改善此查询:
SELECT _c.*,
_o.Status,
(SELECT TOP 1 _o.PlacedOn
FROM Orders _o1
JOIN Client _c1 on _c1.Id = _o1.Client_Id
WHERE _c1.Id = 3
ORDER BY PlacedOn DESC) as LastOrderDate
FROM Client _c
JOIN Orders _o on _c.[Id] = _o.[Client_Id]
WHERE _c.Id = 3 AND _o.[Status] = 'Draft'
需要外部JOIN才能从客户那里获取信息以及有关其订单的一些信息。
内部JOIN获取该客户的最后下单。
我想知道是否可以删除内部联接以及如何移除。
Client.tbl
Id int
Gender nvarchar(255)
DateOfBirth nvarchar(255)
ContactDetails nvarchar(MAX)
FirstName nvarchar(255)
MiddleName nvarchar(255)
LastName nvarchar(255)
Order.tbl
Id int
Status nvarchar(255)
PaymentMethod nvarchar(255)
PlacedOn datetime2(7)
CancelledOn datetime2(7)
PaidOn datetime2(7)
OrderNumber nvarchar(255)
Client_Id int
客户端测试数据:
Id Gender DateOfBirth ContactDetails FirstName MiddleName LastName
1 F. 10/16/1991 NULL Mia M. Brown
订购测试数据:
Id Status PaymentMethod PlacedOn CancelledOn PaidOn OrderNumber Client_Id
1 Done Cash 11/11/1996 NULL NULL NULL 1
2 Done Cash 11/11/2007 NULL NULL NULL 1
3 Draft NULL NULL NULL NULL NULL 1
预期结果:
结果:
FirstName DraftId LastPlacedOn
Mia 3 11/11/2007
答案 0 :(得分:5)
我想您可以使用MAX() OVER ()
从结果集中找到最大值:
WITH cte AS (
SELECT _c.*,
_o.Status,
MAX(_o.PlacedOn) OVER (PARTITION BY _c.id) as LastOrderDate
FROM Client _c
JOIN Orders _o on _c.[Id] = _o.[Client_Id]
)
SELECT *
FROM cte
WHERE Id = 1 AND [Status] = 'Draft'