按表单某一列进行分组,并按另一列进行组内排序。
首先SQLite并不支持关键字 PARTITION BY,所以所谓的组内排序其实是通过两次排序来实现。
话不多说,先来建立一个表单
CREATE TABLE IF NOT EXISTS CUSTOMER (ID integer PRIMARY KEY AUTOINCREMENT,Name text,Vip_num integer,Commodity text,C_num integer,Price integer); /*插入数据*/ INSERT INTO CUSTOMER VALUES (1,'赵童鞋',1001,'A类产品',1101,99); INSERT INTO CUSTOMER VALUES (2,'钱童鞋',1002,'B类产品',1102,50); INSERT INTO CUSTOMER VALUES (3,'孙童鞋',1003,'C类产品',1003,77); INSERT INTO CUSTOMER VALUES (4,'赵童鞋',1001,'A类产品',1001,101); INSERT INTO CUSTOMER VALUES (5,'赵童鞋',1001,'B类产品',1002,99); INSERT INTO CUSTOMER VALUES (6,'李童鞋',1004,'B类产品',1002,200); INSERT INTO CUSTOMER VALUES (7,'钱童鞋',1002,'A类产品',1001,70); INSERT INTO CUSTOMER VALUES (8,'赵童鞋',1001,'A类产品',1001,100); INSERT INTO CUSTOMER VALUES (9,'赵童鞋',1001,'B类产品',1001,40);
所建表单如下
首先按照产品(条件1)分组,然后按照价格(条件2)组内排序
(按照先条件2排序,再按条件1排序即可完成需求)
SELECT * FROM (SELECT * FROM CUSTOMER ORDER BY Price DESC) ORDER BY Commodity
结果如下图
另附GROUP BY
开始以为组内排序可以通过GROUP BY来解决,但怎么都无法得到正确结果,仔细查看API 发现GROUP BY属于合计函数。即按照给定条件计算出数据的某个结果(如sum(),avg()等)
-
根据Vip_num计算每位顾客的总计消费情况
SELECT Name,Vip_num,sum(Price) FROM CUSTOMER GROUP BY Vip_num
查询结果如下:
查询结果一般根据GROUP BY的条件,每种情况对应只有一条结果(本例中每个Vip_num只对应一行数据) -
计算顾客总计消费并按结果降序排序
SELECT Name,Vip_num,sum(Price) FROM CUSTOMER GROUP BY Vip_num ORDER BY sum(Price) desc
查询结果如下