0
下面是一些SQL以拉取客戶端列表。正如你所看到的,我添加了由「 - ADDED」註釋的行 - 一個新字段,一個連接和一個order by。我試圖在結果集中顯示每行一個客戶端,但對於每個客戶端,我想顯示最近的訂單。什麼是最好的方法來做到這一點?我應該在我的JOIN中放置一個位置還是使用TOP 1?我想有幾種方法,但我想盡可能提高效率。SQL - 拉客戶端(結果集中每行有1個客戶端)以及這些客戶端的最近訂單日期
SELECT
CONVERT(NVARCHAR(255),client.identifyingnumber) As [Client ID],
CONVERT(VARCHAR,client.name) As [Client Name],
client.clientid As [Id],
CONVERT(CHAR(10),[ecom_order].[order_date],101) -- ADDED
FROM
client
JOIN clientstatus ON client.clientstatusid = clientstatus.clientstatusid
JOIN clienttype ON clienttype.clienttypeid = client.clienttypeid
-- keep left outer join since some clients won't have any orders, thus no last order
LEFT OUTER JOIN [ecom_order] ON client.clientid = [ecom_order].clientid -- ADDED
WHERE
client.name LIKE '%_%'
AND
client.name <= (
SELECT MAX(maxsubquery.ordercolumn) FROM (
SELECT
TOP 10 client.name AS ordercolumn
FROM
client
JOIN clientstatus ON client.clientstatusid = clientstatus.clientstatusid
JOIN clienttype ON clienttype.clienttypeid = client.clienttypeid
WHERE
client.name LIKE '%_%'
ORDER BY client.name
)
AS maxsubquery)
ORDER BY
client.name,
[ecom_order].order_date DESC -- ADDED
測試數據結果集示例:
只是爲了以後提醒我自己..你修改域公式,打消了我額外的ORDER BY行,並添加了該組。似乎工作!感謝您及時的回覆!我會接受它,當它允許我。 – MacGyver