2012-03-15 44 views
0

嗨程序员! 我得比较联合查询的选择查询在Union中比较查询在sql

我的代码是这样的:

  select emp_id,type from 
      (
       select emp_id,'leave' as type 
       from tbl_emp_info 
       where emp_id like'5_2' or emp_id like '602' 
      ) as t1 
      union 
      select emp_id,type from 
      (
       select emp_id,'weekend'as type 
       from tbl_emp_off_info 
       where emp_id like'6_2' 
      ) t2 t1.emp_id!=t2.emp_id 

我需要比较这两种选择查询

 As i need the result like 

      EMP_ID  TYPE 

      512  leave 
      612  weekend    

但不喜欢

  EMP_ID  TYPE 


      512  leave 
      612  leave 
      612  weekend    

请帮我一下

回答

1

也许这会适合你(SQL Server 2005及更高版本)。

;WITH t1 AS 
(
    SELECT emp_id, 'leave' AS [type] 
    FROM tbl_emp_info 
    WHERE emp_id LIKE '5_2' OR emp_id LIKE '602' 
) 
, t2 AS 
(
    SELECT emp_id, 'weekend' AS [type] 
    FROM tbl_emp_info 
    WHERE emp_id LIKE '6_2' 
) 
SELECT emp_id, [type] 
FROM t1 
WHERE emp_id NOT IN (SELECT emp_id FROM t2) 
UNION 
SELECT emp_id, [type] 
FROM t2 

对于SQL Server 2000,你需要复制的WHERE子句中的一种:

SELECT emp_id, 'leave' AS [type] 
FROM tbl_emp_info 
WHERE (emp_id LIKE '5_2' OR emp_id LIKE '602') 
AND NOT (emp_id LIKE '6_2') 
UNION 
SELECT emp_id, 'weekend' AS [type] 
FROM tbl_emp_info 
WHERE (emp_id LIKE '6_2') 
+0

感谢您的解决方案,但它给错误,如:第1行:附近有语法错误“;”。其实我使用SQL Server 2000,它是否发生,因为它的版本。 – 2012-03-16 04:44:14

+0

我检查了这个代码在SQL Server 2005中,它的工作原理,但不是在SQL Server 2000中,有无论如何要在SQL Server 2000中执行此操作? – 2012-03-16 04:51:52

+0

我已经为SQL Server 2000添加了一个解决方案 – 2012-03-16 09:57:30