T-SQL如何根据组中的最大值构建聚合表?

时间:2013-05-15 15:34:20

标签: sql sql-server tsql

我正在尝试根据汇总表格构建客户购买量最大的产品的高级摘要。

该表采用以下格式

account_code    product_id   num_purchases
abc123          1            10
abc123          2            5
xyz789          1            5

我想返回下面的

account_code    product_id   
abc123          1           
xyz789          1           

因此,对于每个帐户,都会返回该帐户中购买次数最多的产品的产品ID。

到目前为止,我一直在努力解决这个问题,但我觉得必须有一个相当基本的解决方案,非常感谢任何帮助! :)

2 个答案:

答案 0 :(得分:5)

SELECT  account_code, product_id
FROM    (
            SELECT  account_code, product_id, num_purchases,
                    DENSE_RANK() OVER (PARTITION BY account_code 
                                        ORDER BY num_purchases DESC) RowID
            FROM    TableName
        )records
WHERE   RowID = 1

输出

╔══════════════╦════════════╗
║ ACCOUNT_CODE ║ PRODUCT_ID ║
╠══════════════╬════════════╣
║ abc123       ║          1 ║
║ xyz789       ║          1 ║
╚══════════════╩════════════╝

答案 1 :(得分:0)

SELECT tableName.account_code, tableName.product_ID
FROM tableName INNER JOIN  (
SELECT account_code, max(num_purchases) AS maxPurchases
FROM tableName
GROUP BY account_code) AS aggregated
ON tableName.account_code  = aggregated.account_code
AND tableName.num_purchases = aggregated.maxpurchases

使用JW的小提琴 - > http://www.sqlfiddle.com/#!3/44c9f/13