我想弄清楚如何爲Trans.TranSID的每個組返回前10條記錄。t-SQL查找每個組的前10條記錄
SELECT a.ABID, a.ABName, t.TranSID, SUM(IIF(TranTypeID = 'CO', td.Qty * CAST(td.Price AS money) * - 1,
td.Qty * CAST(td.Price AS money))) AS TotalSales
FROM Trans t INNER JOIN
TransDetail td ON t.TranID = td.TranID INNER JOIN
ABook a ON t.TranABID = a.ABID
WHERE (t.TranDate BETWEEN CONVERT(DATETIME, '2012-01-01 00:00:00', 102) AND CONVERT(DATETIME, '2013-01-01 00:00:00', 102)) AND
t.TranTypeID in ('SO','CA','CO') AND (t.TranStatus <> 'V')
GROUP BY a.ABID, a.ABName, t.TranSID
HAVING (NOT (a.ABName LIKE '%cash%'))
ORDER BY t.TranSID, TotalSales Desc
我可以在select語句中添加「TOP 10」,但是不管組別如何,我都可以獲得前10名。有25組Trans.TranSID,我試圖讓每組只有前10名。
包括一個基本的表結構和預期的輸出將幫助你得到答案。 – jTC 2013-04-30 15:40:17
基本上有一個客戶賬戶表(Abook)和交易(Trans)以及交易詳情(TransDetail)表。非常簡單的結構。只需要爲每個客戶總結銷售額,然後將TranSID(這是交易發生的地點)的前10名結果分組。 – 2013-04-30 15:42:56