2016-04-07 59 views
0

我有一個運行良好的查詢,我希望獲得幫助的是如何合併條件以確定給定列上顯示的值。也就是說,如果一個表的列具有價值說「授權COA的」加入應該顯示其他的日期列日期列應顯示爲空用連接表中的if條件確定列數據SQL

這裏是我的查詢到目前爲止

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' , t.date_added (//should show the value of date_added else NULL based on a condition for this column), 
    FROM request r 
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref 
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id 
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref 
    WHERE r.client_id='$cid' 
    AND r.created_at BETWEEN '$start' AND '$end' 
    AND a_s.department_id = '$dept' 
    GROUP BY r.request_id 
    ORDER BY `r`.`created_at` DESC " 
+0

無論是標記你知道的所有RDBMS或者只保留一個:) –

+0

在mysql中使用if()函數或者case表達式,在ms sql用例表達式中。 – Shadow

回答

-1

給這是一個嘗試:

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' , 
IFF(nameOfColumnToTest = 'Authorization of COA', t.date_added, null) AS DateAdded 
    FROM request r 
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref 
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id 
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref 
    WHERE r.client_id='$cid' 
    AND r.created_at BETWEEN '$start' AND '$end' 
    AND a_s.department_id = '$dept' 
    GROUP BY r.request_id 
    ORDER BY `r`.`created_at` DESC " 
0

在MySQL和MS SQL,您可以使用CASE表達式(mysql case; ms sql case)價值分配給字段條件:

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' , 
    CASE WHEN Column_To_Test = 'Authorization of COA' THEN t.date_added 
     ELSE null 
    END AS date_added 
    FROM request r 
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref 
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id 
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref 
    WHERE r.client_id='$cid' 
    AND r.created_at BETWEEN '$start' AND '$end' 
    AND a_s.department_id = '$dept' 
    GROUP BY r.request_id 
    ORDER BY `r`.`created_at` DESC " 

這樣解決方案在數據庫之間更具可移植性。 Mysql提供if()函數,ms sql iif()來實現上述功能,但這些都是產品特定的解決方案。

1

我相信在這種情況下,一個簡單的CASE語句應該足夠了。

SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, 
CONCAT(u.fname,' ',u.lname) 'analyst', 
CASE WHEN ConditionColumn = 'Authorization of COA' THEN t.date_added 
ELSE NULL END AS 'date_added' 
    FROM request r 
    LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref 
    LEFT OUTER JOIN user u ON a_s.analyst_id = u.id 
    LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref 
    WHERE r.client_id='$cid' 
0

嘗試使用Case語句。

CASE WHENCondition_1Condition_2 OR ... Condition_NTHEN(_1)ELSE(_1)END

這裏條件 _1可以是列記錄值及其組合列記錄值 和價值 _1可以是單值[例如:零或「一些字符串」]或類似嵌套的SQL語句返回值[例:(從SELECT COUNT(*)...)]