2011-10-22 71 views
0
select column1,column2,column3 from table1 where column5=0 and column6=0 
select column1,column2,column3 from table1 where column5!=0 and column6!=0 

這些是從同一個table1讀取數據的兩條sql語句。有沒有辦法編寫一個返回相同數據的查詢?用同樣的條件寫同一個多查詢查詢條件相同的表

我想單個查詢中的(column5 = 0 AND column6 = 0)和(column5!= 0 AND column6!= 0)的單獨結果。

as example: 
select column1 as c1,column2 as c2,column3 as c3 from table1 where column5=0 and column6=0 
union 
select column1 as c1_,column2 as c2_,column3 as c3_ from table1 where column5!=0 and column6!=0 
+1

好吧,但你有什麼問題嗎? – 2011-10-22 07:07:30

+0

我想寫上述要求一個查詢 – salma 2011-10-22 07:23:14

+0

您應該提供一些示例:第一個查詢的結果,第二個查詢的結果和預期的單個查詢的結果。 – palacsint 2011-10-24 05:35:06

回答

0
select 
sum(
case when (column5=0 or column6=0) 
then 1 else 0 end 
    ) as c1 , 

sum(
case when (column5=0 or column6=0) 
then 1 else 0 end 
    ) as c2 , 
sum(
case when (column5=0 or column6=0) 
then 1 else 0 end 
) as c3 , 

sum(
case when (column5!=0 or column6!=0) 
then 1 else 0 end 
) as c1_ , 

    sum(
case when (column5!=0 or column6!=0) 
then 1 else 0 end 
) as c2_ , 
sum(
case when (column5!=0 or column6!=0) 
then 1 else 0 end 
    ) as c3_ , 

from table1 
0

如果你想獲得的所有結果從一個結果集這兩個查詢回來,你可以使用UNION像這樣:

select column1,column2,column3 from table1 where column5=0 and column6=0 
union 
select column1,column2,column3 from table1 where column5!=0 and column6!=0 
1
SELECT column1, column2, column3 
FROM table1 
WHERE (column5 = 0 AND column6 = 0) OR (column5 != 0 AND column6 != 0) 
+0

我想在單個查詢(column5 = 0和column6 = 0)和(column5!= 0和column6!= 0)個人結果。 – salma 2011-10-23 12:04:50

+0

你試過這個查詢的輸出嗎? – 2011-10-23 12:19:24

0

如上文所提到的其他人可以使用聯盟。爲了確定哪些記錄來自哪個查詢你會做這樣的:

select 'query1', column1,column2,column3 from table1 where column5=0 and column6=0 
union 
select 'query2', column1,column2,column3 from table1 where column5!=0 and column6!=0 

然後在您的記錄處理,您可以檢查的第一個值,並決定如何處理剩下的事情。

0
SELECT column1,column2,column3 from table1 where (column5=0 and column6=0) or (column5!=0 and column6!=0) 
0

如果我理解正確,你想保持結果的兩個部分分開。 爲此添加ORDER BY子句。

SELECT column1, column2, column3 
FROM table1 
WHERE (column5 = 0 AND column6 = 0) 
    OR (column5 != 0 AND column6 != 0) 
ORDER BY (column5 = 0) DESC -- it's enough to include one column in this case. 

如果你也希望能夠告訴他們分開,添加象徵着原點的另一列:

SELECT (column5 = 0) AS first_part, column1, column2, column3 
FROM table1 
WHERE (column5 = 0 AND column6 = 0) 
    OR (column5 != 0 AND column6 != 0) 
ORDER BY 1 DESC;