我試圖合併兩個查詢。目標是獲得一個記錄集,其中包含唯一的客戶電子郵件以及他們的名稱和基於MAX(ID)的最新列表的標題。MS SQL使用DISTINCT選擇基於MAX(ID)的多個列
使用DISTINCT我可以得到電子郵件和ID,但顯然添加標題打破了這一點。
這是我到目前爲止有:
SELECT DISTINCT MAX(EV_ID) As EV_ID, EV_ContactEmail, EV_CusName
FROM tblEvents ev
INNER JOIN tblCustomers cus ON cus.CUS_ID = ev.EV_CustomerID
WHERE (
CUS_IsAdmin = 'y'
AND CUS_Live = 'y'
AND EV_Live = 'y'
AND EV_EndDate >= '2012/7/5 12:00:00 AM'
AND EV_ContactEmail <> ''
)
GROUP BY EV_ContactEmail
,我發現這裏的部分訊息,說表明我需要做一個自我加入,但我不能讓它返回的記錄相同的量,但與標題,它返回更多。
SELECT DISTINCT MAX(EV_ID) As EV_ID, ev.EV_Title, EV_ContactEmail, EV_CusName
FROM tblEvents ev
INNER JOIN tblCustomers cus ON cus.CUS_ID = ev.EV_CustomerID
INNER JOIN (
SELECT EV_Title, MAX(EV_ID) AS MaxID
FROM tblEvents
GROUP BY EV_Title
) groupedev ON ev.EV_Title = groupedev.EV_Title AND ev.EV_ID = groupedev.MaxID
WHERE (
CUS_IsAdmin = 'y'
AND CUS_Live = 'y'
AND EV_Live = 'y'
AND EV_EndDate >= '2012/7/5 12:00:00 AM'
AND EV_ContactEmail <> ''
)
GROUP BY EV_ContactEmail, ev.EV_Title
任何人都可以告訴它有什麼問題嗎?
可你也提供你的數據庫結構 – Kshitij 2012-07-06 10:41:48