我对SQL很陌生,我需要你的帮助。
即使条件(001)在某些月份不存在,我希望在SELECT
- YM
范围内的201801
列(年)中201804
行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
有关如何编写查询以实现此目的的任何建议吗?
scrapy crawl swspider
答案 0 :(得分:1)
我想知道这是否可以在没有子查询的情况下完成。我想它可以是:
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)
)
答案 1 :(得分:0)
一种选择是使用联合来引入没有匹配code
记录的月份的记录。在我的输出中,有201712
的数据,因为您没有指定它不应出现的原因,并且它没有匹配的代码数据。如果您不想在那里使用该记录,那么在WHERE
子句中删除它就很容易了。
SELECT YM, code, hour
FROM pod11
WHERE YM BETWEEN '201801' AND '201804' AND code = '001'
GROUP BY YM, code, hour
UNION ALL
SELECT DISTINCT t1.YM, 0, 0
FROM pod11 t1
WHERE NOT EXISTS (SELECT 1 FROM pod11 t2 WHERE t1.YM = t2.YM AND t2.code = '001')
ORDER BY YM;
答案 2 :(得分:0)
<强> MSSQL:强>
SELECT
tableYM.YM,
ISNULL(pod11.code, 0) AS code,
ISNULL(SUM(pod11.hour), 0) AS hour
FROM (
SELECT DISTINCT YM FROM pod11 WHERE YM >= '201801' AND YM <= '201804'
) tableYM LEFT JOIN pod11 ON tableYM.YM = pod11.YM AND pod11.code = '001'
GROUP BY pod11.code, tableYM.YM
ORDER BY tableYM.YM
<强> MySQL的:强>
SELECT
tableYM.YM,
IFNULL(pod11.code, 0) AS code,
IFNULL(SUM(pod11.hour), 0) AS hour
FROM (
SELECT DISTINCT YM FROM pod11 WHERE YM >= '201801' AND YM <= '201804'
) tableYM LEFT JOIN pod11 ON tableYM.YM = pod11.YM AND pod11.code = '001'
GROUP BY pod11.code, tableYM.YM
ORDER BY tableYM.YM
答案 3 :(得分:0)
你可以自己加入你的桌子:
[pythondemo@panel python3.6]$ sudo yum install sqlite3 libsqlite3-dev
Loaded plugins: fastestmirror, universal-hooks
Setting up Install Process
Loading mirror speeds from cached hostfile
* EA4: 69.72.212.11
* cpanel-addons-production-feed: 69.72.212.11
* base: mirror.jaleco.com
* epel: mirror.texas3006.com
* extras: mirror.jaleco.com
* ius: ius.mirror.constant.com
* updates: mirror.jaleco.com
No package sqlite3 available.
No package libsqlite3-dev available.
答案 4 :(得分:0)
SELECT YM, COALESCE(code,0) code, COALESCE(hour,0) hour
(
SELECT YM,code,hour
FROM pod11
WHERE YM >= '201801' AND YM <= '201804' and code = '001'
GROUP by YM,code,hour
RIGHT JOIN
(SELECT 201801 as YM
UNION
SELECT 201802
UNION
SELECT 201803
UNION
SELECT 201804
) as t
ON pod11. YM = t.YM
)
ORDER BY YM
您可以将年份存储在不同的表格中并从中查询,或者如果您知道pod11表格中的所有年份,即201801到201804,那么您可以从该表格查询范围和不同