SQL Server:最常见的值

时间:2017-01-14 11:38:38

标签: sql sql-server

我有一个名为Accessoires_OrderDetails的表格,其结构如下:

ID int IDENTITY(1,1)
accessoireID int,
QteSelled int,
Price Varchar(50)

我正在使用此查询显示表格中已售出的商品:

SELECT TOP 12 
    AccessoireID, COUNT(AccessoireID) AS Amount 
FROM 
    Accessoires_OrderDetails
GROUP BY 
    AccessoireID
ORDER BY 
    Amount DESC

但我不知道如何展示卖出的Qte

该查询的输出是:

1   3
4   2
2   1

我希望展示项目ID = 1已售出3次。

示例:

AccessoireID = 1, Sold = 3 times, first time (Qte = 2), second time (Qte = 3), third time (Qte = 5) 

输出应为

1   3  10 
4   2
2   1

所以10是所有销售的Qte销售数量。

1 个答案:

答案 0 :(得分:1)

简单SUM将执行:

select TOP 12 
    AccessoireID,
    count(AccessoireID) as Amount,
    SUM(QTE) as total_qte           -- Added this
from Accessoires_OrderDetails
GROUP BY AccessoireID
ORDER BY Amount
DESC