我需要在下表中获得最多的项目?

时间:2016-10-26 19:28:35

标签: sql-server-2008

我编写了以下T-SQL查询来选择特定表的计数值。

SELECT 
    COUNT(Item1) AS ITEM_COUNT, Item1 AS ITEM
FROM 
    [cloths_DB].[dbo].[Suggetion_DB]
WHERE 
     [Type] = 'Dockers' and [Age] = '25'
GROUP BY 
     Item1

UNION ALL

SELECT 
    COUNT(Item2) AS ITEM_COUNT, Item2 AS ITEM
FROM 
    [cloths_DB].[dbo].[Suggetion_DB]
WHERE 
    [Type] = 'Dockers' and [Age] = '25'
GROUP BY  
    Item2
ORDER BY 
    ITEM_COUNT DESC

我得到以下结果:

ITEM_COUNT  ITEM
-------------------------
7           Tommy
5           Denim shorts
4           Boxers
3           Diesel_D
3           Emerald
3           Jockey
2           Polo_D
2           Polo_D
2           Tommy
2           Gucci

我需要在上面的结果表中获得最多的项目记录。例如,有#7; Tommy"在第一行和2号"汤米"第9排。所以总共有9个" Tommy"这是上述结果中最高的。

如何更改上述查询以获得此结果?

2 个答案:

答案 0 :(得分:0)

Select top 1 * from ( select sum(item_count) as total, item from (
SELECT 
COUNT(Item1) AS ITEM_COUNT, Item1 AS ITEM
FROM 
[cloths_DB].[dbo].[Suggetion_DB]
WHERE 
 [Type] = 'Dockers' and [Age] = '25'
GROUP BY 
 Item1

UNION ALL

SELECT 
COUNT(Item2) AS ITEM_COUNT, Item2 AS ITEM
FROM 
[cloths_DB].[dbo].[Suggetion_DB]
WHERE 
[Type] = 'Dockers' and [Age] = '25'
GROUP BY  
Item2
ORDER BY 
ITEM_COUNT DESC

) group by item order by total desc)

答案 1 :(得分:0)

如果我理解正确,对于每个ITEM,您只想看到一行(具有最大计数),但如果您可以向我们提供样本数据,我们可以更好地理解。但假设我的理解是正确的,以下代码应该适合你

with c as (
SELECT 
    COUNT(Item1) AS ITEM_COUNT, Item1 AS ITEM
FROM 
    [cloths_DB].[dbo].[Suggetion_DB]
WHERE 
     [Type] = 'Dockers' and [Age] = '25'
GROUP BY 
     Item1

UNION ALL

SELECT 
    COUNT(Item2) AS ITEM_COUNT, Item2 AS ITEM
FROM 
    [cloths_DB].[dbo].[Suggetion_DB]
WHERE 
    [Type] = 'Dockers' and [Age] = '25'
GROUP BY  
    Item2
)
, c2 as (
          select item_count, item
         , rnk=row_number() over (partition by Item order by item_count desc)
         from c
        )
select item_count, item from c2 
where rnk = 1;