我有一个数据库:
+--+----+---------+
|id|name|source_id|
+--+----+---------+
|11|aaaa|null
+--+----+---------+
|12|bbbb|1
+--+----+---------+
|13|cccc|1
+--+----+---------+
|14|dddd|null
+--+----+---------+
|15|eeee|2
+--+----+---------+
|16|ffff|2
+--+----+---------+
|17|gggg|2
+--+----+---------+
我想选择所有条目,但有一个例外:
- 所有条目
source_id == somevalue(not null)
都应分组 - 最后一个条目
source_id == null
应该在之后存在
这是我期望的结果:
+----+--+----+---------+
COUNT|id|name|source_id|
+----+--+----+---------+
.....|11|aaaa|null
+----+--+----+---------+
.2...|13|cccc|1
+----+--+----+---------+
.....|14|dddd|null
+----+--+----+---------+
.3...|17|ffff|2
+----+--+----+---------+
到目前为止,我已经这样做了(注意:“change_count”= COUNT):
SELECT *, (To_days(date_expires)-TO_DAYS(NOW())) as dayDiff, COUNT(id) AS change_count FROM mytable
GROUP BY source_id
HAVING dayDiff < 4
ORDER BY date_created DESC
这就是我得到的:
+----+--+----+---------+
COUNT|id|name|source_id|
+----+--+----+---------+
.2...|11|aaaa|null
+----+--+----+---------+
.2...|12|bbbb|1
+----+--+----+---------+
.3...|15|eeee|2
+----+--+----+---------+
如您所见,结果有两个问题:
- 条目按第一次
source_id
出现分组(应该是最后一个(最新)) nulls
也被分组(不应该被分组)
我上面描述的任务可以实现吗?我该怎么做?
编辑:
SELECT *, COUNT(id) AS change_count FROM
(SELECT *, (To_days(date_return_due)-TO_DAYS(NOW())) as dayDiff FROM mytable
WHERE owner_id='1'
HAVING dayDiff < 100
ORDER BY date_created DESC) AS newtable
GROUP BY (CASE WHEN source_id IS NULL THEN id ELSE source_id END)
ORDER BY (CASE WHEN source_id IS NULL THEN 1 ELSE 0 END), date_created DESC";