SQL如何按2个不同的日期列对数据进行分组?
我得到一个像这样的表:
Id Date1 Date2 Status
----------------------------------------------
1 01/01/2010 null A
2 04/04/2010 05/14/10 X
3 01/01/2010 null A
4 01/11/2010 01/01/2010 X
5 01/02/2010 null A
和其他几条记录,日期 1 不为空,但仅当状态为 A 时,它才在分组依据中相关,对于日期 2 不为空的记录,无论分组依据的状态如何到此日期2。
所需的结果集如下:
Date Number of A Status Number of Date 2 not null statuses
------------------------------------------------------------------------------
01//01/2010 2 1
01/02/2010 1 0
05/14/2010 0 1
基本上分组依据必须按日期分组,问题是在某些情况下它针对 Date1 列,而在其他情况下针对 Date2 列。如何才能做到这一点?
I got a table like this:
Id Date1 Date2 Status
----------------------------------------------
1 01/01/2010 null A
2 04/04/2010 05/14/10 X
3 01/01/2010 null A
4 01/11/2010 01/01/2010 X
5 01/02/2010 null A
And several other records, Date 1 is not null but it is only relevant in the group by if the Status is A, for the records where Date2 is not null, regardless of the status the group by should be by this Date2.
The desired result set is as follows:
Date Number of A Status Number of Date 2 not null statuses
------------------------------------------------------------------------------
01//01/2010 2 1
01/02/2010 1 0
05/14/2010 0 1
Basically the group by must group by date, the problem is that in some cases it is for the Date1 column and in the other case is for the Date2 columns. How can this be accomplished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以按解码或大小写表达式进行分组。只在 Oracle 中尝试过,所以不确定这是否可移植。有了这些数据:
您可以执行
以下操作:
You can group by a decode, or case, expression. Only tried in Oracle so not sure if this is portable. With this data:
You can do:
Which gives:
这是一个典型的 PIVOT 查询:
但是您需要根据您的数据派生一个包含两列日期的表,以便首先进行联接。
It's a typical PIVOT query:
But you need to derive a table containing the dates from both columns, based on your data, to join against first.
也许是这样的:
Maybe something like this: