我的下面有一个示例代码,其中包含ID,日期,值以及编号的行,该行由ID持有者分区并按其会议日期排序:
import logging
from logging.config import dictConfig
import logging_config # defined above so import accordingly
dictConfig(logging_config)
logger = logging.getLogger() # you have a logger ready. Use it to log something
logger.debug("Its a log")
运行此类查询的结果示例将带来:
SELECT
c.ID
,m.CONTACT_DATE
,d.TEST
,row_number() over(partition by c.ID
order by m.CONTACT_DATE desc
) [rn]
FROM COMMUNITY C
INNER JOIN MEETING m
ON c.ID = m.CONTACT_ID
LEFT JOIN DISCUSSION d
ON m.DISCUSSION_TEST = d.TEST
我想要做的是将每个ID分组以获取最新的ID CONTACT_DATE TEST rn
01 2017-05-01 NULL 1
01 2017-04-01 1 2
01 2017-03-01 NULL 3
02 2017-08-01 NULL 1
02 2017-09-01 NULL 2
02 2017-10-01 1 3
03 2017-02-01 NULL 1
03 2017-01-01 NULL 2
(即放置在子查询中CONTACT_DATE
,然后T
)
但是,如果WHERE T.rn = 1 GROUP BY T.ID
下有一个值,那么我想要查看具有值的最新TEST
,如下所示:
CONTACT_DATE
我该怎么做才能过滤最新ID CONTACT_DATE TEST rn
01 2017-04-01 1 2
02 2017-10-01 1 3
03 2017-02-01 NULL 1
CONTACT_DATE
的{{1}},如果该ID的所有值都为TEST
,我仍可获取最新的CONTACT_DATE
}?
答案 0 :(得分:4)
您可以更改row_number排序:
row_number() over(partition by c.ID
order by CASE WHEN d.TEST IS NOT NULL THEN 1 ELSE 2 END
, m.CONTACT_DATE desc
)