2012-03-15 92 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