sql - 即使条件不存在也如何显示行
问题描述
我对 SQL 很陌生,我需要你的帮助。
我希望SELECT
列YM
(年月)中的所有行都在范围内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
解决方案
我想知道这是否可以在没有子查询的情况下完成。我认为可以是:
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)
)
推荐阅读
- android - 我无法使用 Mockito 测试 SharedPreference
- java - gradle 测试任务在扩展 TestCase 但没有测试方法的 Test Util 类上失败
- grails - 无法在空对象上获取属性“id”
- python - 使用几何方法在屏幕上设置 Tkinter 标签位置
- vbscript - 如何通过 VBScript 在文本文件中保存非拉丁字符?
- excel - 试图忽略 Excel 列中的零值
- python - 使用坐标(基因)文件的脚本
- android - Android 语音转文本查询
- java - JavaFx 如何使用二维数组向 GridPane 添加按钮?
- angular - '可观察的
>' 不可分配给类型 'Observable