有一个用户表,属性为 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);