1

我有一个包含和Customer_Invoice列的表。我想以降序显示特定商品和已售商品数量的前 5 件商品,即如果商品 A 的数量为 5,商品 B 的数量为 3,则商品 A 应位于顶部,商品 B 将排在第二位。item_nameQuantity

|  ITEMCODE | QUANTITY |
------------------------
|     kb434 |        1 |
| A4tech123 |        4 |
|   HDD40GB |        4 |
|    Cell12 |        4 |
|    Icd123 |        2 |
| A4tech123 |        6 |

在上图中,我希望A4tech123在第 1 个没有HDD40GB第 2 个没有,Cell12在第 3 个没有,依此类推。

4

5 回答 5

11
select top 5 Item_code, sum(Quantity)
from customer_invoice
group by Item_code
Order by sum(Quantity) desc
于 2012-11-28T07:41:35.883 回答
4
select top 5 item_name , sum(Quantity) as Quantity from Customer_Invoice 
group by item_name 
ORDER BY sum(Quantity) DESC
于 2012-11-28T07:41:58.440 回答
0

如果您使用 postgres 作为数据库,请使用以下查询:

select Item_code, Quantity from customer_invoice order by Quantity desc limit 5

或者

如果您使用任何其他数据库,请使用此查询:

select top 5 Item_code, Quantity from customer_invoice order by Quantity desc

我没有检查第二个,因为我使用的是 Postgres DB,所以在使用之前确认该查询

于 2012-11-28T07:52:44.580 回答
0
CREATE TABLE invoice
    (ITEMCODE varchar(9), QUANTITY int)
;

INSERT INTO invoice
VALUES
    ('kb434', 1),
    ('A4tech123', 4),
    ('HDD40GB', 4),
    ('Cell12', 4),
    ('Icd123', 2),`
    ('A4tech123', 6)
;


SELECT ITEMCODE,
       SUM(QUANTITY) as total_quantity,
       ROW_NUMBER() OVER (order by sum(QUANTITY) desc) as rank_n
FROM invoice
GROUP BY ITEMCODE

http://sqlfiddle.com/#!18/da13e/6

于 2018-08-29T01:35:25.807 回答
-3
SELECT TOP 5 * FROM Customer_Invoice ORDER BY QUANTITY
于 2012-11-28T07:43:27.567 回答