我有一个这样的样本表记录:
AutoID ReceiptNo Outlet_Code
--------------------------------
1 SUN12 Store X
3 SUN12 Store X
4 ART123 Store y
我想在ReceiptNo上根据Outlet_Code和Distinct选择一个带有关系的top 1,这样在这种情况下,我的结果将是:
存储X /存储Y
因为我应该将2商店X记录读为1,因为它们具有相同的收据号。
这是我的查询的一部分:
SELECT TOP 1 WITH TIES (Outlet_Code)
From [Trans] T
WHERE T.CardNo IN (Select [CardNo] From [Card]
Where [MemberID] =
(Select [ID] From [Member] Where [autoid] = @MemAutoID ))
GROUP BY Outlet_Code
ORDER BY Count(T.Outlet_Code) Desc
答案 0 :(得分:1)
SELECT DISTINCT T.Outlet_Code
FROM [Trans] T, [Card] C, [Member] M
WHERE T.CardNo = C.CardNo
AND C.MemberID = M.ID
AND M.autoid = @MemAutoID
ORDER BY Count(T.Outlet_Code) Desc
或者不那么懒惰......
SELECT DISTINCT T.Outlet_Code
FROM [Trans] AS T
JOIN [Card] AS C ON (T.CardNo = C.CardNo)
JOIN [Member] AS M ON (C.MemberID = M.ID)
WHERE M.autoid = @MemAutoID
ORDER BY Count(T.Outlet_Code) Desc
答案 1 :(得分:0)
我不知道我是否理解正确但是如何使用DISTINCT
?
SELECT DISTINCT Outlet_Code FROM tableName
答案 2 :(得分:0)
您的GROUP BY子句正确,但在ORDER BY子句中必须使用不同的列值ReceiptNo
SELECT TOP 1 WITH TIES Outlet_Code
FROM [Trans] T
WHERE T.CardNo IN (
SELECT c.[CardNo]
FROM [Card] c JOIN [Member] m ON c.[MemberID] = m.ID
WHERE m.[autoid] = @MemAutoID
)
GROUP BY T.Outlet_Code
ORDER BY COUNT(DISTINCT T.ReceiptNo) DESC
SQLFiddle上的演示