比方说,你有一个这样的表:
-------------------------------
Date Name Type
2017-01-01 John 1
2017-01-02 John 1
2017-01-03 Mike 2
2017-01-04 John 1
-------------------------------
我希望能够按类型分组以获得如下结果
-------------------------
Name Type
John 1
Mike 2
John 1
-------------------------
正如你所看到的那样,前两行是分组的,因为它们之间没有不同的类型,就像你在手机通话记录中看到的那样。
如何在SQLite中实现这一目标?
答案 0 :(得分:3)
以下查询通过NOT EXISTS
对前一行(如果有)的相同Name
和Type
值实现此目的。通过查找严格小于当前行日期的最大日期来找到上一行。
SELECT *
FROM tbl t1
WHERE NOT EXISTS (
SELECT *
FROM tbl t2
WHERE t2.Name = t1.Name
AND t2.Type = t1.Type
AND t2.`Date` = (SELECT MAX(`Date`)
FROM tbl t3
WHERE t3.`Date` < t1.`Date`)
);
SQL小提琴演示: http://sqlfiddle.com/#!5/0700cb/3
答案 1 :(得分:1)
您可以使用有序的临时表和一些rowid比较来执行此操作:
sqlite> create table t (date, name, type);
sqlite> insert into t (date, name, type) values ( '2017-01-01', 'John', 1);
sqlite> insert into t (date, name, type) values ( '2017-01-02', 'John', 1);
sqlite> insert into t (date, name, type) values ( '2017-01-03', 'Mike', 2);
sqlite> insert into t (date, name, type) values ( '2017-01-04', 'John', 1);
sqlite> create temp table tp as select date, name, type from t order by date;
sqlite> delete from tp
where tp.name = (select name from t where t.rowid = tp.rowid - 1)
and tp.type = (select type from t where t.rowid = tp.rowid - 1);
sqlite> select * from tp;
2017-01-01|John|1
2017-01-03|Mike|2
2017-01-04|John|1
sqlite>