2017-01-06 60 views
0

我需要幀MySQL查詢,其中有接列的要求,僅當它具有值(爲NOT NULL)從4列的給定的,first_accuracysecond_accuracythird_accuracyfourth_accuracyMySQL的 - 選擇列,只有當他們具有值

假設我有隻爲first_accuracysecond_accuracy值,所以查詢應該是

SELECT first_accuracy,second_accuracy FROM compliance_employees CE;

UPDATE:

查詢我申請:

SELECT first_accuracy, second_accuracy, third_accuracy, fourth_accuracy FROM compliance_employees CE; 

結果:

enter image description here

您可以看到,對於「第三精度」,沒有任何行的值,所以我根本不想選擇該列。那可能嗎?

任何解決方案?

+1

我想'山坳不null'? – GurV

+0

... WHERE CE.first_accuracy不爲NULL且CE.second_accuracy不爲NULL且CE.third_accuracy IS NULL和CE.fourth_accuracy IS NULL# – spencer7593

+1

如果不使用動態SQL,則無法執行此操作。但你爲什麼要這樣做?只需使用'COALESCE()'來處理每列中的NULL值。 –

回答

2

如果你只是想確保兩列first_accuracysecond_accuracyNULL然後使用此:

SELECT first_accuracy, 
     second_accuracy 
FROM compliance_employees CE 
WHERE first_accuracy IS NOT NULL AND 
     second_accuracy IS NOT NULL 

如果你想確保所有四列不NULL然後使用這個:

SELECT first_accuracy, 
     second_accuracy 
FROM compliance_employees CE 
WHERE first_accuracy IS NOT NULL AND 
     second_accuracy IS NOT NULL AND 
     third_accuracy IS NOT NULL AND 
     fourth_accuracy IS NOT NULL 
+0

我想我沒有把我的問題框架得很好,它不僅僅是'NOT NULL'..不過感謝你的幫助.. –

+0

@RajeshOmanakuttan這回答你的問題,因爲你有它的措辭。如果你的意思是別的,那麼更新並向我們展示樣本數據。 –

+0

當然,我正在做它.. –

0
SELECT 
    first_accuracy, 
    second_accuracy 
FROM 
    compliance_employees CE 
WHERE 
    first_accuracy IS NOT NULL 
    AND second_accuracy IS NOT NULL 
0

您的意思是問如何選擇在v四個領域中的一個?如果是的話,我建議使用GREATEST

SELECT 
    GREATEST(first_accuracy, second_accuracy) as accuracy 
FROM 
    compliance_employees CE; 
2

使用「聯盟」,GROUP_CONCAT()和「不爲空」,我們發現其中有值列數。 然後傳遞列給準備好的陳述,它給你你想要的結果。

 select coalesce (GROUP_CONCAT(col_name),'No_Result') into @ColumnNames 
     from (
     select 'first_accuracy' as col_name, count(distinct first_accuracy) as count from compliance_employees 
     where first_accuracy is not null 
     union 
     select 'second_accuracy' as col_name, count(distinct second_accuracy) from compliance_employees 
     where second_accuracy is not null 
     union 
     select 'third_accuracy' as col_name, count(distinct third_accuracy) from compliance_employees 
     where third_accuracy is not null 
     union 
     select 'fourth_accuracy' as col_name, count(distinct fourth_accuracy) from compliance_employees 
     where fourth_accuracy is not null 
     )a where count >0\\ 
     -- select @ColumnNames\\ 


    SET @sql := CONCAT('SELECT ', @ColumnNames, ' FROM compliance_employees'); 
    set @sql := REPLACE(@sql,'No_Result','"No Column have values" as No_Result')\\ 

    PREPARE stmt FROM @sql; 
    EXECUTE stmt;   

檢查現場演示Here

輸出:

enter image description here

+0

如果所有字段都爲空,則查詢會引發錯誤。否則,這是一個很好的答案。 –

+0

@PrabirGhosh third_accuracy COLUMN有所有字段空值..你想說什麼? –

+0

只要嘗試所有列的所有字段的罕見情況爲空。但根據我的觀點,你的答案是最好的。 –

相關問題