2012-06-08 62 views
1

我有一個名爲users的表。使用日期條件將多個MySql查詢組合成單個查詢

id name date  cdate   c a b 
1  rz 42121221 42121221   0 1 0 
2  an 12122111 42121221   0 0 1 
3  cb 22121221 42121221   1 1 1 
4  ss 3321221 42121221   1 0 0 

我必須選擇兩個日期之間的值,然後我必須使用此語句找到計數。

SELECT COALESCE(SUM(IF(c=1 AND a=0 AND b=1 , 1, 0)),0) AS ACTIVE 
    WHERE DATE BETWEEN 'DATE 1' AND 'DATE 2', 
COALESCE(SUM(IF(c=0 AND a=0 AND b=1 , 1, 0)),0) AS INC 
    WHERE cdate BETWEEN 'DATE 1' AND 'DATE 2' 
FROM users where dealer id='2' 

此查詢不起作用。

+1

爲什麼不是查詢工作? –

+1

#1064 - 您的SQL語法錯誤;檢查對應於你的MySQL服務器版本的手冊,在'WHERE'DATE'BETWEEN'DATE 1'和'DATE 2', – coolboy

回答

0

這是您的查詢,格式正確。每個SELECT語句只能有一個WHERE子句,並且FROM子句在SELECT子句之後和WHERE子句之前。

SELECT SUM(IF(c=1 AND a=0 AND b=1 AND DATE BETWEEN 'DATE 1' AND 'DATE 2', 1, 0)) AS ACTIVE, 
    SUM(IF(c=0 AND a=0 AND b=1 AND cdate BETWEEN 'DATE 1' AND 'DATE 2', 1, 0)) AS INC 
FROM users 
WHERE DATE BETWEEN 'DATE 1' AND 'DATE 2' 
    OR cdate BETWEEN 'DATE 1' AND 'DATE 2' 

我複製你的日期比較成IF語句。

此外,我刪除了COALESCE子句,因爲它在這種情況下是冗餘的。 SUM總是返回一個值。

我把這些列放在一起,用逗號隔開,在SELECT子句後面。

現在您可能希望刪除WHERE子句,具體取決於您要做什麼。我也懷疑cdate BETWEEN 'DATE 1' AND 'DATE 2'。如果cdate是DATETIME列,則需要在常量中輸入格式正確的日期。如果日期1和日期2列名,那麼你就需要回蜱,而不是單引號,像這樣:

cdate BETWEEN `DATE 1` AND `DATE 2` 

您應該考慮讀書的SELECT syntax的文檔。

+0

附近使用正確的語法,所以我有兩個使用兩個select staemet? – coolboy

+0

@coolboy,不,看看我上面的查詢。您可以使用一個SELECT語句並用逗號分隔列。在[documentation](http://dev.mysql.com/doc/refman/5.0/en/select.html)中有很多很好的例子。 –

+0

活動的日期條件呢? – coolboy

0

我會做這樣的事情來實現你在一個查詢的需要:

試試看:

SELECT COALESCE(SUM(IF(u1.c=1 AND u1.a=0 AND u1.b=1, 1, 0)),0) AS ACTIVE, 
COALESCE(SUM(IF(u2.c=0 AND u2.a=0 AND u2.b=1, 1, 0)),0) AS INC 
from user u1 
left outer join user u2 on u1.row_id = u2.row_id 
where u1.DATE BETWEEN 'DATE 1' AND 'DATE 2' and 
u2.cdate BETWEEN 'DATE 1' AND 'DATE 2'