部分文章内容为公开资料查询整理,原文出处可能未标注,如有侵权,请联系我,谢谢。邮箱地址:gnivor@163.com ►►►需要气球么?请点击我吧!

MySQL笔记--查询语句实践

有一个用户表,属性为 id,age,buytime

创建表以及插入数据的语句

CREATE TABLE USER(
id INT,
age INT,
buytime INT
)

INSERT INTO USER VALUES(1000,10,1);
INSERT INTO USER VALUES(1000,10,2);
INSERT INTO USER VALUES(1000,10,3);
INSERT INTO USER VALUES(1001,11,1);
INSERT INTO USER VALUES(1001,11,2);
INSERT INTO USER VALUES(1001,11,4);
INSERT INTO USER VALUES(1002,13,2);
INSERT INTO USER VALUES(1002,13,5);
INSERT INTO USER VALUES(1004,10,2);
INSERT INTO USER VALUES(1004,10,4);
INSERT INTO USER VALUES(1004,10,5);

 

查询:

1. buytime(购买时间)在1和3之间(包含1和3)的用户年龄分布情况

方法:先查询出购买时间在1和3之间的用户的年龄,然后对结果根据年龄分组,计算每个分组的数量

SELECT age,COUNT(*) 
FROM(
SELECT age
FROM USER
WHERE buytime >0 AND buytime < 4
) 
AS agenum
GROUP BY age

 注意:上面的AS agenum是不可缺少的,作为表的别名(虽然在这里没有使用到)

 

2.每一个用户购买时间在1到3的id 年龄 购买数量

SELECT id,age, COUNT(*) num
FROM USER
WHERE buytime >0 AND buytime < 4
GROUP BY id

 

创建表以及插入数据的语句

CREATE TABLE USER(
id INT,
age INT,
buytime INT
)

SELECT * FROM USER

INSERT INTO USER VALUES(1000,10,1);
INSERT INTO USER VALUES(1000,10,2);
INSERT INTO USER VALUES(1000,10,3);
INSERT INTO USER VALUES(1001,11,1);
INSERT INTO USER VALUES(1001,11,2);
INSERT INTO USER VALUES(1001,11,4);
INSERT INTO USER VALUES(1002,13,2);
INSERT INTO USER VALUES(1002,13,5);
INSERT INTO USER VALUES(1004,10,2);
INSERT INTO USER VALUES(1004,10,4);
INSERT INTO USER VALUES(1004,10,5);

 

posted @ 2016-04-14 16:40  流了个火  阅读(267)  评论(0编辑  收藏  举报
►►►需要气球么?请点击我吧!►►►
View My Stats