我有以下SQL语句:
select top 1 scrr.name, sess.end_time
from tbl_session sess
inner join tbl_scripts scrr on sess.script_id = scrr.script_id
where end_time >= '5-May-2015 14:58:00'
and end_time < '06-May-2015 14:58:00'
and scrr.script_type in (1,3,4)
and sess.operator_id = 95
UNION
select top 1 scr.name, oh.end_time
from tbl_outbound_history oh
inner join tbl_outbound o on oh.outbound_id = o.outbound_id
inner join tbl_session ses on o.session_id = ses.id
inner join tbl_scripts scr on ses.script_id = scr.script_id
where oh.end_time >= '5-May-2015 14:58:00'
and oh.end_time < '06-May-2015 14:58:00'
and oh.start_time <> oh.end_time
and oh.user_id = 95
order by end_time
数据没有变化,但结果每次都不同。就好像忽略了顺序。
第二个选择在这种情况下不返回任何内容,我尝试简化SQL以最小化问题,但无法重现它。
如果我放弃第二个选择,我每次都得到相同的结果,所以关于联合到零和前1的一些事情或许我可以通过更简单的选择来做到这一点。
之前有人遇到过这样的错误,如果是这样的话,是否有适合它的工作。
任何指向正确方向的人都会受到赞赏。
我正在使用:
Microsoft SQL Server 2012 (SP1) - 11.0.3000.0 (X64)
Oct 19 2012 13:38:57
Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)
答案 0 :(得分:4)
您需要订购&amp;在外部查询中使用top 1
select top 1 from (
select scrr.name, sess.end_time
from tbl_session sess
inner join tbl_scripts scrr on sess.script_id = scrr.script_id
where end_time >= '5-May-2015 14:58:00'
and end_time < '06-May-2015 14:58:00'
and scrr.script_type in (1,3,4)
and sess.operator_id = 95
UNION
select scr.name, oh.end_time
from tbl_outbound_history oh
inner join tbl_outbound o on oh.outbound_id = o.outbound_id
inner join tbl_session ses on o.session_id = ses.id
inner join tbl_scripts scr on ses.script_id = scr.script_id
where oh.end_time >= '5-May-2015 14:58:00'
and oh.end_time < '06-May-2015 14:58:00'
and oh.start_time <> oh.end_time
and oh.user_id = 95
) a
order by a.end_time
我相信,施放日期时间会很棒
CAST('06-May-2015 14:58:00' as datetime)