2014-01-06 47 views
1

我想實現下面的查詢,兩個選擇statments與工會工作不

 (SELECT 
    MAX(final_avg_total.`Provider Name`) AS `Hospital Name`, 
    final_avg_total.`DRG Definition`, 
    final_avg_total.`Provider Id`, 
    SUM(final_avg_total.avg_total_payments) AS avg_payments, 
    SUM(final_avg_total.avg_covered_charges) AS avg_covered, 
    (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments))/SUM(final_avg_total.avg_covered_charges) AS total_average, 
    1 - (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments))/SUM(final_avg_total.avg_covered_charges) AS total_percentage 
FROM final_avg_total 
GROUP BY final_avg_total.`Provider Id` 
ORDER BY total_average DESC LIMIT 0,5) 
Union 
SELECT 
    MAX(final_avg_total.`Provider Name`) AS `Hospital Name`, 
    final_avg_total.`DRG Definition`, 
    final_avg_total.`Provider Id`, 
    SUM(final_avg_total.avg_total_payments) AS avg_payments, 
    SUM(final_avg_total.avg_covered_charges) AS avg_covered, 
    (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments))/SUM(final_avg_total.avg_covered_charges) AS total_average, 
    1 - (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments))/SUM(final_avg_total.avg_covered_charges) AS total_percentage 
FROM final_avg_total 
GROUP BY final_avg_total.`total_percentage` 
ORDER BY total_average DESC LIMIT 0,5 

實際上這兩個查詢幾乎只用了GROUP BY不同一樣的,但我得到這個錯誤。

5 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION (SELECT 
    MAX(final_avg_total.`Provider Name`) AS `Hospital Name`, 
    fin' 
+0

您確定提供者名稱是適合MAX的類型嗎? –

+0

它的類型是文本,但我要求做的,我知道它不是最好的選擇,但BOSS永遠是對的 –

+0

我從查詢中刪除了最大子句,但現在我只得到5個結果我期待10條記錄 –

回答

1

如果可能,選擇較小的問題可能會有幫助。 看看你是否得到相同的結果,如果你

創建或更換視圖part_one AS ...;

CREATE OR REPLACE VIEW part_two AS ...;

然後

SELECT * FROM part_one

UNION

SELECT * FROM part_two;

讓數據庫引擎在過去的時代對片段的理解幫助我。也可以幫助代碼維護。 如果你得到咒語,UNION ALL是顫抖中另一個方便的箭頭。

1

這只是一個普通的UNION錯誤 http://www.sqlfiddle.com/#!2/ec657/7

,這是「相同」 UNION沒有錯誤 http://www.sqlfiddle.com/#!2/ec657/8

唯一的區別就是在這兩種情況下,括號,請務必將括號在UNION之後或將其刪除

... 
ORDER BY total_average DESC LIMIT 0,5) 
Union 
(SELECT --ADDED PARENTHESIS 
    MAX(final_avg_total.`Provider Name`) AS `Hospital Name`, 
... 
ORDER BY total_average DESC LIMIT 0,5) --ADDED PARENTHESIS 
+0

我按照你說的添加了括號,但我只得到5條記錄,我期待10條記錄,在查詢中沒有錯誤,現在清除 –

+0

您將收到5條結果,因爲限制'LIMIT 0,5' – jcho360