从表中查找另一个表中的描述来选择最大值

时间:2013-06-05 03:32:37

标签: sql sqlite count nested max


我有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 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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 这里是小提琴的Liknk,我在谈论的情况....它给出了所有描述谁有最大销售.... Case Sql Fiddle Demo

答案 2 :(得分: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)

答案 3 :(得分: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)
        )
)