0


我有 3 张桌子

买方

buyer_id | name
50       |Joe
60       |Astor
70       |Cloe

物品

item_id | description
1       | iphone
2       | ipod
3       | imac

Item_Sold

buyer_id | item_id
50       | 1
50       | 2
60       | 1
60       | 3
70       | 1
70       | 2
70       | 3

我想找出最畅销商品的描述,在这种情况下:

Best-Selling
iphone
4

4 回答 4

2
SELECT description AS Best_Selling
FROM item
WHERE item_id = (SELECT item_id FROM( SELECT item_id ,COUNT(*) as num_items
                                      FROM Item_Sold
                                      GROUP BY item_id
                                      ORDER BY num_items DESC
                                      LIMIT 1
                                     )z
                 )

请参阅SQL FIDDLE

这个答案并不完全正确。如果两件商品的销售额相同,则它只会退回其中一件。

于 2013-06-05T03:50:26.317 回答
1

此查询将给出销售额最大的所有商品 ID 描述,即当两个或多个商品 ID 具有相等的销售额时......

;WITH CTE1(Id,Counts) as
(
SelectItem_Id,COUNT(buyer_id ) AS C  FROM T GROUP BY ID
) 

Select Item.Description from CTE1 A inner join 
(Select MAX(Counts) AS MaxCount FROM CTE1 ) b on a.Counts=b.MaxCount 
inner join
Item on Item.Item_Id=a.Item_Id

如果公用表表达式不起作用,您可以尝试这样......

Select Item.Description from (Select Item_Id,COUNT(buyer_id ) AS Counts  FROM item_sold GROUP BY Item_Id) A inner join 
(Select MAX(Counts) AS MaxCount FROM 
(
Select Item_Id,COUNT(buyer_id) AS Counts  
FROM item_sold GROUP BY Item_Id) v 
) b 
on a.Counts=b.MaxCount 
inner join
Item on Item.Item_Id=a.Item_Id

SQL Fiddle Demo Here is the Linknk of Fiddle the case im talknig about....它给出了所有销售量最大的描述...... Case Sql Fiddle Demo

于 2013-06-05T04:01:32.370 回答
0
select description as "Best-Selling" 
from (select a.item_id, b.description, count(*) count 
      from Item_Sold a,Items b
      where a.item_id = b.item_id
      group by a.item_id ) temp
where count = (select max(count) 
               from (select a.item_id, count(*) count 
                      from Item_Sold a,Items b
                      where a.item_id = b.item_id
                      group by a.item_id ) temp1)
于 2013-06-05T04:20:38.757 回答
0

pl-sql:

select description as "Best-Selling"
from item
where item_id in (
    select item_id from (
        select item_id, count(item_id) as item_count 
        from item_sold 
        group by item_id) 
    where item_count = (
        select max(item_count) from (
            select item_id, count(item_id) as item_count 
            from item_sold 
            group by item_id)
        )
)
于 2013-06-05T05:33:14.823 回答