2017-08-29 52 views
0

我有一個查詢返回用戶所在的ID,最高值和最高級別的項目。如何在SQL中分組多個聚合結果

我的查詢如下:

SELECT id, 
MAX(item) AS highest_item, 
MAX(level) AS highest_level 
FROM data 
GROUP BY 1 
ORDER BY 1; 

我如何可以查詢數據庫,這樣我收到的唯一用戶的總數,誰是在同一水平最高,並且具有相同價值最高的項目嗎?

回答

0

您可以根據您需要的值獲得計數(distcint id)。例如。對於這兩個值:

select count(distinct id), highest_item, highest_level 

    from ( 
    SELECT id, 
    MAX(item) AS highest_item, 
    MAX(level) AS highest_item 
    FROM data 
    GROUP BY 1 
) t 
group by highest_item, highest_level 
order by count(distinct id) desc 

或highest_item

select count(distinct id), highest_item 

    from ( 
    SELECT id 
    MAX(item) AS highest_item, 
    MAX(level) AS highest_level 
    FROM data 
    GROUP BY 1 
) t 
group by highest_item 
order by count(distinct id) desc 

爲HIGHEST_LEVEL

select count(distinct id), highest_level 

    from ( 
    SELECT id, 
    MAX(item) AS highest_item, 
    MAX(level) AS highest_level 
    FROM data 
    GROUP BY 1 
) t 
group by highest_level 
order by count(distinct id) desc 
+0

利用你的第一個建議,組我得到一個簡單計數的結果表,其中不是我所需要的,我需要一個包含關卡#,項目ID和有多少不同用戶與同一項目處於同一級別的表。你能否在你的查詢中解釋「t」字符的用途? – nyvokub

+0

添加了關卡...... t是()t ..子查詢的表名,但是用戶與問題的關係如何(我假設你是meadn是這個id的數目)。我在查詢中沒有看到任何用戶列。 – scaisEdge

0

你可以試試這個也

Select id,count(Id) from data group by level,item having level=max(level) and item=max(item)