--表結構-- create table `shop` ( `id` int (10) PRIMARY KEY, `shop_name` varchar (100), `item_name` varchar (100), `price` int (10) ); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('1','小賣部','醬油','12'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('2','小賣部','醋','15'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('3','小賣部','脈動','20'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('4','小賣部','沙姜','2'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('5','超市','豬肉','24'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('6','超市','生菜','6'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('7','超市','菜心','5'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('8','連鎖店','生薑','3'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('9','超市','牛肉','30'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('10','連鎖店','蒜頭','2'); insert into `shop` (`id`, `shop_name`, `item_name`,`price`) values('11','連鎖店','黃瓜','20');
對價格price進行排序而後再根據商店類型shop_name進行分組查詢sql
select * from (select * from shop order by price desc) a GROUP BY a.shop_name數據庫
結果只是按照表數據的順序,簡單地進行了分組查詢操做,可是這時候咱們還不能下結論說這條sql就是錯誤的,咱們用另外一個數據庫版本(MySql 5.5.57)測試一下。測試
-方法一,僅適用於低於5.7版本的MySql-- select * from (select * from shop order by price desc) a GROUP BY a.shop_name; --方法二-- select * from (select * from shop order by price desc limit 999999) a GROUP BY a.shop_name; --方法三-- select * from shop a where N > (select count(*) from shop b where b.shop_name = a.shop_name and a.price < b.price) order by a.shop_name,a.price desc;
PS:方法二中使用limit,須要limit的範圍足夠大能包括全部數據,而且每種分類只會顯示一條數據,可是數據較多時運行效率要比方法三快上不少,方法三可以控制每種分類顯示多少條數據,把N換成須要顯示對應的數字便可。.net