我已经制作了一个视图(加入四个表格),如下所示:
ID | BookID | date | points |
1 | 11 | 2014-11-01 | 15 |
1 | 11 | 2015-01-01 | 16 |
1 | 11 | 2014-12-01 | 17 |
1 | 12 | 2014-02-11 | 18 |
1 | 12 | 2014-03-11 | 19 |
1 | 12 | 2014-04-11 | 15 |
1 | 13 | 2014-12-23 | 121 |
1 | 14 | 2014-01-15 | 113 |
1 | 14 | 2014-02-08 | 112 |
我希望此视图的结果如下
ID | BookID | Date | points |
1 | 11 | 2015-01-01 | 16 |
1 | 12 | 2014-04-11 | 15 |
1 | 13 | 2014-12-23 | 121 |
1 | 14 | 2014-02-08 | 112 |
它应该像Distincit Book ID一样具有最大日期并显示为分隔点。 到目前为止,我已经通过加入和分组与日期一起尝试了该组。但它有点过了,因为我无法找到解决方案。
我的查询是:
SELECT m1.* FROM viewPoints m1 LEFT JOIN viewPoints m2
ON (m1.BookID = m2.BookID AND m1.Date < m2.Date)
WHERE m1.ID= 1 and m2.Date IS NULL
ORDER BY m1.BookID
任何帮助!在此先感谢。
答案 0 :(得分:1)
也许这就是你想要的?
select v.*
from viewPoints v
join (
select
BookID,
max(date) max_date
from viewPoints
where points is not null
group by BookID
) v2 on v.BookID = v2.BookID and v.date = v2.max_date
where v.points is not null
order by v.BookID
示例输出:
| ID | BOOKID | DATE | POINTS |
|----|--------|---------------------------------|--------|
| 1 | 11 | January, 01 2015 00:00:00+0000 | 16 |
| 1 | 12 | April, 11 2014 00:00:00+0000 | 15 |
| 1 | 13 | December, 23 2014 00:00:00+0000 | 121 |
| 1 | 14 | February, 08 2014 00:00:00+0000 | 112 |
答案 1 :(得分:0)
CREATE VIEW [BOOKLIST] AS
SELECT m1.* FROM viewPoints m1 LEFT JOIN viewPoints m2
ON (m1.BookID = m2.BookID AND m1.Date < m2.Date)
WHERE m1.ID= 1 and m2.Date IS NULL
ORDER BY m1.BookID
SELECT ID, DISTINCT BookID, Date, points FROM BOOKLIST
WHERE Date BETWEEN "start date" AND "end date"
答案 2 :(得分:0)
SELECT *
FROM tablename
WHERE DATE
IN (
SELECT MAX( DATE )
FROM tablename
GROUP BY bookid
ORDER BY DATE DESC
)
ORDER BY DATE DESC