工做中不免會寫sql從數據庫中到導出報表,自己sql是很是簡單。只不過一個報表囊括的業務含義比較複雜時,須要咱們使用大量的鏈接查詢(子查詢均可以用鏈接查詢來實現)、大量的where條件來實現,那是就顯得很費腦力了,但其卻並無什麼技術含量。java
這裏介紹兩個sql場景,根據本人的經驗,這兩個場景的sql做爲總體sql的部分查詢時,每每增大了閱讀難度。sql
一、一維數據庫
含義:統計不一樣國家的人的數量,並排序code
select tem.country,tem.number from (select country,count(pupulation) as number from table group by country ) tem order by number
二、二維排序
含義:統計不一樣國家的男、女人數數量,按男性數量排序io
select tem.country,tem.male_number,tem.female_number from ( select country, sum( case when sex = '1' then population ELSE 0 END) as male_number, sum( case when sex = '2' then population ELSE 0 END) as famale_number from table group by country ) tem order by male_number