这是我的简化代码:

SELECT
   a.user_id as User_ID,
   min(b.a_day) as Date_from,
   max(b.a_day) as Date_to,
   c.code as ID
FROM a, b, c
WHERE
   a_day > (day, -15, getdate())
GROUP BY
   a.user_id,
   c.code

查询给出以下输出:
User ID date_from   date_to     id
1234567 2016-06-13  2016-06-13  B
1234567 2016-06-17  2016-06-17  A
12345672016-06-18  2016-06-18   A
1234567 2016-06-19  2016-06-19  A
1234567 2016-06-20  2016-06-20  A
1234567 2016-06-21  2016-06-21  C
1234567 2016-06-22  2016-06-22  C
1234567 2016-06-23  2016-06-23  D

我需要这样的东西:
User ID date_from   date_to     id
1234567 2016-06-13  2016-06-13  B
1234567 2016-06-17  2016-06-20  A
1234567 2016-06-21  2016-06-22  C
1234567 2016-06-23  2016-06-23  D

当我将min()和max()函数与group by一起使用时,它对所有记录的聚合效果都很好,但是我只需要日复一日地汇总具有相同ID的日期。

有任何想法吗?

提前致谢。

最佳答案

您可以通过在CASE EXPRESSION子句中使用GROUP BY进行条件分组:

SELECT
   a.user_id as User_ID,
   min(b.a_day) as Date_from,
   max(b.a_day) as Date_to,
   c.code as ID
FROM a, b, c
WHERE
   a_day > (day, -15, getdate())
GROUP BY
   a.user_id,
   c.code,
   CASE WHEN c.code in ('B','D') THEN b.a_day ELSE 1 END

它将生成为GROUP BY子句:
c.code = 'B' -> a.user_id,c.code,b.a_day
c.code <> 'B' -> a.user_id,c.code,1

关于sql - 如何使用GROUP BY异常(exception)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39484658/

10-16 22:32