2011-03-19 212 views
7

例如我有这张表:GROUP BY忽略属性

itemgroup |描述|价格
A,A,10
A,B,12
A,C,14
B,克,11
B,H,16

现在我想选择具有最高的行价在一组这样的:

A,C,14
B,H,16

SQL查询(是全功能)至极得到我附近是这样的:

SELECT itemgroup, MAX(price) 
FROM table 
GROUP BY itemgroup 

A,14
B,16

通过尝试这个,我得到一个 “不是一个GROUP BY表达式” 误差:

SELECT itemgroup, description, MAX(price) 
FROM table 
GROUP BY itemgroup 

我需要的是这样的伪查询:

SELECT itemgroup, IGNORE(description), MAX(price) 
FROM table 
GROUP BY itemgroup 

我希望我能解释我的小问题。

回答

8

我通常最终会做这样的事情:

SELECT t1.itemgroup, t1.description, t1.price 
FROM table t1, 
    (SELECT itemgroup, MAX(price) as price 
    FROM table 
    GROUP BY itemgroup) t2 
WHERE t1.itemgroup = t2.itemgroup 
AND t1.price = t2.price 
+0

谢谢你,应该做的神奇:) – Pew 2011-03-19 20:32:32

+0

是的,我立即删除,谢谢你的信息! – Pew 2011-03-19 20:35:08

3

使用分析功能:

SELECT itemgroup, description, price FROM 
    (select itemgroup, description, price, RANK() 
    OVER (PARTITION BY itemgroup ORDER BY max(price) DESC) as rank 
    FROM group by itemgroup,description,price)a 
WHERE a.rank = 1 
ORDER BY itemgroup; 

有一个在解析函数很大的权力 - 学习他们可以帮助你在很多的情况。