笔试实例
以MySQL为例,制作一个简单的表profit如下:
T1
分别求1991年以及1992年第一季度的金额总和,效果如下:
sql语句实现:
SELECT
year,
SUM(amount) amount
FROM
profit
GROUP BY
profit.year
其中用到了聚集函数SUM()以及GROUP BY子句,表示按照年份分组后求和展示。
T2
将一维表转变成二维表,效果如下:
sql语句实现:
SELECT
year,
( SELECT amount FROM profit a WHERE a.year = b.year AND a.MONTH = 1 ) AS m1,
( SELECT amount FROM profit a WHERE a.year = b.year AND a.MONTH = 2 ) AS m2,
( SELECT amount FROM profit a WHERE a.year = b.year AND a.MONTH = 3 ) AS m3
FROM
profit b
GROUP BY
b.year
T3
按月分别求金额总和并按金额降序显示,效果如下:
sql语句实现:
SELECT
month,
SUM(amount) amount
FROM
profit
GROUP BY
profit.month
ORDER BY
profit.amount DESC
ORDER BY子句默认按升序按指定字段排序结果,加DESC表示降序排列。
注意:ORDER BY与GROUP BY同时使用时,ORDER BY必须用在GROUP BY后面。