我有3张桌子
我正在尝试获取一个查询来返回这样的值:
------------------------------------------------------------
| Date | Username | Badge timestamp |
------------------------------------------------------------
| 01-jan-2018 | Steve | null |
| 01-jan-2018 | Peter | 01-01-2018T08:25:21 |
| 01-jan-2018 | Sasha | null |
| 02-jan-2018 | Steve | null |
| 02-jan-2018 | Peter | null |
| 02-jan-2018 | Sasha | null |
| 03-jan-2018 | Steve | 03-01-2018T12:01:20 |
| 03-jan-2018 | Peter | 03-01-2018T06:39:01 |
| 03-jan-2018 | Sasha | 03-01-2018T09:11:15 |
------------------------------------------------------------
查询应该显示表Kalender
中的每个值以及表GeoPers
中的每个人的结果,然后显示他们的徽章时间戳,如果没有则为NULL
我到目前为止:
select
k.datum, isnull(gp.name,null), isnull(gt.DateTimeLocal,null)
from
Kalender k
left outer join
GeoTikkingen gt on CAST(k.datum as DATE) = CAST(gt.DateTimeLocal as DATE)
left outer join
GeoPers gp on gp.name = gt.UserName
order by
k.datum asc, gp.name asc
但是当用户在特定日期没有标记时,它不会返回NULL
我应该能够获得Kalender中所有值的列表以及GeoPers中的所有值,如果没有NULL,那么它们是否标记为时间戳
请帮助: - )
答案 0 :(得分:1)
我认为,你应该申请full outer join
;
select k.datum, gp.name, gt.DateTimeLocal
from Kalender k
full outer join GeoTikkingen gt on CAST(k.datum as DATE) = CAST(gt.DateTimeLocal as DATE)
full outer join GeoPers gp on gp.name = gt.UserName
order by k.datum asc, gp.name asc
并删除isnull(gt.DateTimeLocal,null)
语句,这完全是错误的用法。
答案 1 :(得分:0)
我认为cross join
是要走的路。以下是我确认自己的观点。您可以将它用于数据库对象:
with a as (select 1 record
union select 2 record)
, b as (select 'a' text
union select 'b' text)
,c as (select 1 r
union select 4 r)
select record, text, r
from a cross join b
left join c on record = r
答案 2 :(得分:0)
试试这个:
SELECT k.datum,
gp.name,
gt.DateTimeLocal
FROM Kalender k,
GeoPers gp
LEFT OUTER JOIN GeoTikkingen gt
ON Cast(k.datum AS DATE) = Cast(gt.DateTimeLocal AS DATE)
AND gp.name = gt.UserName
ORDER BY k.datum ASC,
gp.name ASC