在两个表上进行联合后,现在它忽略了我的WHERE语句的@Badge参数。代码如下。
SELECT TOP (100) PERCENT ID_BADGE, LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2)
+ ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime, DATE_TRX, CODE_TRX
FROM omi.DCUTRX_ZERO
UNION ALL
SELECT TOP (100) PERCENT ID_BADGE, LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2)
+ ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime, DATE_TRX, CODE_TRX
FROM omi.TAHIST_ZERO
WHERE (ID_BADGE = ' ' + @Badge) AND (DATE_TRX BETWEEN @Date AND @Date2) AND (SEQ_REC IN ('0', '1000')) AND (CODE_TRX IN ('100', '101'))
任何帮助都会受到极大的赞赏!
答案 0 :(得分:3)
如果你想要将WHERE应用于两者,那么你需要包装语句并将其应用于结果集,如下所示:
SELECT *
FROM (
SELECT TOP (100) PERCENT ID_BADGE,
LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2) + ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime,
DATE_TRX,
CODE_TRX
FROM omi.DCUTRX_ZERO
UNION ALL
SELECT TOP (100) PERCENT ID_BADGE,
LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2) + ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime,
DATE_TRX,
CODE_TRX
FROM omi.TAHIST_ZERO
) q
WHERE (ID_BADGE = ' ' + @Badge) AND
(DATE_TRX BETWEEN @Date AND @Date2) AND
(SEQ_REC IN ('0', '1000')) AND
(CODE_TRX IN ('100', '101'))
答案 1 :(得分:2)
如果要将WHERE子句应用于所有结果,请尝试以下操作:
select * from (
SELECT TOP (100) PERCENT
ID_BADGE,
LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2) + ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime,
DATE_TRX,
CODE_TRX
FROM omi.DCUTRX_ZERO
UNION ALL
SELECT TOP (100) PERCENT
ID_BADGE,
LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2) + ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime,
DATE_TRX,
CODE_TRX
FROM omi.TAHIST_ZERO
) omi
WHERE (omi.ID_BADGE = ' ' + @Badge)
AND (omi.DATE_TRX BETWEEN @Date AND @Date2)
AND (omi.SEQ_REC IN ('0', '1000'))
AND (omi.CODE_TRX IN ('100', '101'))
答案 2 :(得分:1)
WHERE过滤器应用于最后一个UNION SELECT ..
更好的SQL如下:
SELECT TOP (100) PERCENT ID_BADGE, LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2)
+ ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime, DATE_TRX, CODE_TRX
FROM omi.DCUTRX_ZERO
WHERE (ID_BADGE = ' ' + @Badge) AND (DATE_TRX BETWEEN @Date AND @Date2) AND (SEQ_REC IN ('0', '1000')) AND (CODE_TRX IN ('100', '101'))
UNION ALL
SELECT TOP (100) PERCENT ID_BADGE, LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 2)
+ ':' + SUBSTRING(LEFT(RIGHT('000000' + CAST(TIME_TRX AS varchar), 6), 4), 3, 2) AS ClockTime, DATE_TRX, CODE_TRX
FROM omi.TAHIST_ZERO
WHERE (ID_BADGE = ' ' + @Badge) AND (DATE_TRX BETWEEN @Date AND @Date2) AND (SEQ_REC IN ('0', '1000')) AND (CODE_TRX IN ('100', '101'))