5

我有一个数据库:

+--+----+---------+
|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";
4

3 回答 3

8

我认为以下内容可以满足您的要求:

SELECT *, (To_days(date_expires)-TO_DAYS(NOW())) as dayDiff, COUNT(id) AS change_count
FROM mytable
GROUP BY (case when source_id is null then id else source_id end)
HAVING dayDiff < 4 
ORDER BY (case when source_id is null then 1 else 0 end), date_created DESC

它是有条件group by的,因此不会对 NULL sourceid 进行分组。然后,它使用逻辑将它们放在最后order by

没看懂你说的最后一次是什么意思。现在我想我做到了:

SELECT coalesce(s.id, mytable.id) as id,
       max(case when s.maxid is not null and s.maxid = myable.id then mytable.name
                when s.maxid is null then NULL
                else mytable.name
           end) as name,
       (To_days(date_expires)-TO_DAYS(NOW())) as dayDiff, COUNT(id) AS change_count
FROM mytable left outer join
     (select source_id, MAX(id) as maxid
      from mytable
      where source_id is not null
      group by source_id
     ) s
     on mytable.id = s.maxid
GROUP BY (case when source_id is null then id else source_id end)
HAVING dayDiff < 4 
ORDER BY (case when source_id is null then 1 else 0 end), date_created DESC

这会加入来自最新记录的信息(基于最高 id)。

于 2013-02-20T19:08:49.943 回答
5

尝试将您的更改group by为:

GROUP BY coalesce(source_id, id)
于 2013-02-20T19:07:42.053 回答
0

尝试这个

SELECT *, IFNULL(source_id,UUID()) as unique_source FROM tablename WHERE (conditions) GROUP BY unique_source

于 2014-03-25T12:26:21.090 回答