有我的问题:
enter code here
我有一个名为test的表,看起来像这样
id| service | sub service | Qt | date
1 | service_1 | sub_service_11 | 3 | 2011-12-03
2 | service_1 | sub_service_12 | 6 | 2011-12-03
3 | service_1 | sub_service_13 | 4 | 2011-12-03
后来我有一个名为datedim的表,看起来像这样
id| date
1 | 2011-12-01
2 | 2011-12-02
3 | 2011-12-03
4 | 2011-12-04
5 | 2011-12-05
我想要做的是,即使没有匹配,每个sub_service也会从datedim返回所有日期。
所以基本上看起来像这样的东西
sub_service_11 | 2011-12-01 | NULL
sub_service_11 | 2011-12-02 | NULL
sub_service_11 | 2011-12-03 | 3
sub_service_11 | 2011-12-04 | NULL
sub_service_11 | 2011-12-05 | NULL
sub_service_12 | 2011-12-01 | NULL
sub_service_12 | 2011-12-02 | NULL
sub_service_12 | 2011-12-03 | 6
sub_service_12 | 2011-12-04 | NULL
sub_service_12 | 2011-12-05 | NULL
sub_service_13 | 2011-12-01 | NULL
sub_service_13 | 2011-12-02 | NULL
sub_service_13 | 2011-12-03 | 4
sub_service_13 | 2011-12-04 | NULL
sub_service_13 | 2011-12-05 | NULL
我确实尝试过RIGHT JOIN,UNIONS和其他东西,但我无法弄明白。
有谁知道我怎么能做到这一点?
谢谢,
答案 0 :(得分:1)
这就是你需要的:
select
ss.sub_service,
dd.date,
ts.qt
from
(datedim dd, (select distinct sub_service from test) ss)
left join test ts on (dd.date = ts.date and ts.sub_service = ss.sub_service)
order by ss.sub_service, dd.date
答案 1 :(得分:0)
由于您有一个包含每个sub_service的表(让我们称之为sub_service_list),您应该能够执行以下操作:
SELECT
s.sub_service, d.date, t.Qt
FROM (sub_service_list s,datedim d)
LEFT JOIN test t ON s.sub_service=t.sub_service AND d.date=t.date
答案 2 :(得分:0)
你可以这样做:
select t.id, sub_service, case when d.date = t.date then qt else null end as qt
from test t cross join datedim d
order by sub_service, d.date