为没有关系的2个表生成查询输出

时间:2018-04-06 13:35:55

标签: sql

我有2张桌子: 列为StartDate,UserID的会话 和 具有列FullName,UPN,ID

的用户

两个表中还有许多其他列,但它们中的任何一个都有相互关系。

你能帮我写一个查询:

从会话中选择StartDate,其中startdate大于1个月且低于当前日期,FullName,来自用户的UPN。

我正在尝试使用此查询,但没有成功:

SELECT StartDate  
FROM Session  
WHERE ((startdate >= '20180306') AND (startdate <= '20180406')) 
UNION 
SELECT FullName, Upn 
FROM User

有什么方法可以做到吗?我应该使用不同表格中的密钥吗?

3 个答案:

答案 0 :(得分:1)

编辑以反映评论中的信息

select 
    a.startdate,
    b.fullname,
    b.upn
from
    sessions a
    inner user b on a.UserId = b.id
where
    startdate between dateadd(month,-1,getdate()) and getdate()

答案 1 :(得分:0)

如果两个表的User和Fullname相同,则可以使用这些表将表连接在一起。您可以在今天使用getdate(),在1个月前使用dateadd,这样您就不必在日期范围内更改查询。

select 
    startdate,
    fullname,
    upn
from
    sessions
    join user 
    on sessions.userid=user.id
where
    startdate between dateadd(month,-1,getdate()) and getdate()

答案 2 :(得分:0)

Union运算符仅在表和列中的列数和数据类型相同时才起作用。您可以使用完全连接或交叉连接来组合来自两个表的数据