首页 > 解决方案 > 即使条件不存在也如何显示行

问题描述

我对 SQL 很陌生,我需要你的帮助。

我希望SELECTYM(年月)中的所有行都在范围内201801-201804即使条件(001)在几个月内不存在。

pod11

YM  code    hour   
------------------------------------
201712  005 32
201712  002 16
201712  003 24
201712  007 112
201801  001 112
201801  003 12
201801  005 24
201801  007 64
201802  001 64
201802  002 128
201803  005 32
201803  002 16
201804  003 24
201804  007 112
201804  008 86 

我用这个:

SELECT YM,code,hour
FROM pod11
WHERE  YM >= '201801' AND YM <= '201804' and code = '001'
GROUP by YM,code,hour
ORDER BY YM

我懂了:

YM  code    hour   
------------------------------------
201801  001 112
201802  001 64

关于如何编写查询来实现这一点的任何建议?

YM  code    hour   
------------------------------------
201801  001 112
201802  001 64
201803  0   0
201804  0   0

标签: sqlsql-server-2014

解决方案


我想知道这是否可以在没有子查询的情况下完成。我认为可以是:

select top (1) with ties YM,
       (case when code = '001' then hour else 0 end) as code,
       (case when code = '001' then code else 0 end) as hour
from pod11
where YM between '201801' and '201804' 
order by rank() over (partition by ym
                      order by (case when code = '001' then 1 else 2 end),
                               (case when code <> '001' then hour end)
                     )

推荐阅读