0

我正在尝试基于聚合表构建客户最常购买的产品的高级摘要。

该表采用以下格式

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

我想返回以下

account_code    product_id   
abc123          1           
xyz789          1           

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

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

4

2 回答 2

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 ║
╚══════════════╩════════════╝
于 2013-05-15T15:36:28.810 回答
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

于 2013-05-15T15:44:53.607 回答