按非空值分组

时间:2013-02-20 18:58:32

标签: mysql sql

我有一个数据库:

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

3 个答案:

答案 0 :(得分:5)

我认为以下是您想要的:

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源代码进行分组。然后它使用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)。

答案 1 :(得分:4)

尝试将group by更改为:

GROUP BY coalesce(source_id, id)

答案 2 :(得分:0)

试试这个

SELECT *,IFNULL(source_id,UUID())作为unique_source FROM tablename 在哪里(条件) GROUP BY unique_source