第六章 SELECT进阶
一.循环操作:Case
UPDATE movie_table
SET category =
CASE
WHEN drama = 'T' THEN 'drama'
WHEN comedy = 'T' THEN 'comedy'
WHEN action = 'T' THEN 'action'
WHEN gore = 'T' THEN 'horror'
WHEN scifi = 'T' THEN 'scifi'
WHEN for_kids = 'T' THEN 'family'
WHEN cartoon = 'T' AND rating = 'G' THEN 'family'
ELSE 'misc'
END;
说明:a.基本语法
UPDATE tablename
SET columnname =
CASE
WHEN columnname1 = value1 THEN newvalue1
WHEN columnname2 = value2 THEN newvalue2
WHEN columnname3 = value3 THEN newvalue3
ELSE newvalue4
END;
b.ELSE是不符合其他几种case的默认值,若所有条件都写的很全面了,可以省略此处ELSE.
c.case还可以与SELECT ,INSERT ,DELETE搭配,不要忘了UPDATE.
二.排序ORDER BY
SELECT title,category FROM movie_table ORDER BY title;
说明:a.句尾使用ORDER BY+列名,使用列中的值进行排序。
b.也可以使用多列排序,在ORDER BY后面跟多个列名,以列的次序分优先级。
c.反序排列:在ORDER BY+列名+DESC;此处DESC是单词descending(降)的简写。解析表的语句DESC tablename中,DESC是description(描述)的简写。
三.分组查询/*分组*/
SELECT * FROM cookie_sales GROUP BY first_name;
分组之后,查询出来的结果不会再出现重复的了。
/*求单人销售综合*/
SELECT first_name ,SUM(sales) FROM cookie_sales GROUP BY first_name ORDER BY SUM(sales) DESC;
/*求平均销售量*/
SELECT first_name ,AVG(sales) FROM cookie_sales GROUP BY first_name;
/*求销售天数*/
SELECT first_name ,COUNT(sale_date) FROM cookie_sales GROUP BY first_name;
/*求最大最小值*/
SELECT first_name ,MIN(sales) FROM cookie_sales GROUP BY first_name;
SELECT first_name ,MAX(sales) FROM cookie_sales GROUP BY first_name;
/*LIMIT查询,限制返回数量*/
SELECT first_name ,SUM(sales) FROM cookie_sales GROUP BY first_name ORDER BY SUM(sales) DESC LIMIT 2;
SELECT first_name ,SUM(sales) FROM cookie_sales GROUP BY first_name ORDER BY SUM(sales) DESC LIMIT 1 ,1;
说明:LIMIT后面跟两个参数a,b,代表从第a条记录开始,返回b条记录。SQL是从0开始计数的。LIMIT 1,1代表从第2条记录返回一条记录,也就是第二条记录。
本文出自 “墨痕” 博客,转载请与作者联系!