2014-05-03 300 views
0

誰能告訴我以下sql查詢有什麼問題?嵌套的Sql select語句

Select *, 
(SELECT [DiseaseID], COUNT(*) AS [Rank] FROM [DiseaseSymptom] WHERE 
    ([SymptomID] IN(1, 5)) GROUP BY [DiseaseID] ORDER BY [Rank] DESC) 
FROM Disease WHERE GenderID in (1, 3) 

我有2代表一個含有疾病和性別它與

疾病

+-----------+-------------------+----------+ 
| DiseaseID | DiseaseName | GenderID | 
+-----------+-------------------+----------+ 
|   1 | Fever    |  3 | 
|   2 | Flu    |  3 | 
|   3 | Lady Disease  |  2 | 
|   4 | Gentlemen Disease |  1 | 
+-----------+-------------------+----------+ 

性別1 =男,2 =女性,3 =普通

相關聯

和這樣的症狀疾病矩陣

DiseaseSymptom

+-----------+-----------+----------+ 
| DiseaseID | SymptomID | DissymID | 
+-----------+-----------+----------+ 
|   1 |   1 |  1 | 
|   1 |   2 |  3 | 
|   1 |   4 |  4 | 
|   2 |   1 |  5 | 
|   2 |   3 |  9 | 
|   2 |   4 |  6 | 
|   2 |   5 |  7 | 
+-----------+-----------+----------+ 

我從用戶的症狀,並在DiseaseSymptom表相匹配,並根據匹配的症狀的數目(內SQL語句)

在外聲明我只是想獲得它排在內部陳述的結果並評估它是否屬於特定性別。我收到的時候我嘗試運行上述查詢的錯誤是

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified. 
+2

你想達到什麼目的? – Mureinik

+1

你有什麼錯誤? – underscore

+0

現在,我明白查詢要做什麼,我不是100%確定它是按照你的意圖做的。您應該提供樣本數據,期望的結果和(通常)說出現問題時會出現什麼問題。 –

回答

0

您正在使用子查詢與group by。你的意圖是有一個相關的子查詢。問題是子查詢返回多行。我認爲這是你想要什麼:

Select d.*, 
     (SELECT COUNT(*) AS [Rank] 
     FROM [DiseaseSymptom] ds 
     WHERE [SymptomID] IN (1, 5)) AND ds.DiseaseId = d.DiseaseId 
    ) 
FROM Disease d 
WHERE GenderID in (1, 3); 
+0

...鑑於外部'SELECT'從主表中獲取更多列,我嚴重懷疑只是這樣做就足夠了。 –

+0

@ Clockwork-Muse。 。 。我完全誤讀了這個問題。謝謝。 –

+0

我試過了你的查詢,我得到了「Column'DiseaseSymptom.DiseaseID'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中」錯誤。 –

0

子查詢在SELECT子句只能產生一個標值,而不是多列或行結果集。如果你想既然後將子查詢在FROM子句(正常相關),並指兩個不同vqlues SELECT子句中

Select d.*, z.DeseaseId, z.Rank 
FROM Disease d 
    join (SELECT DiseaseID, COUNT(*) Rank 
      FROM DiseaseSymptom 
      WHERE SymptomID IN(1, 5) 
      GROUP BY DiseaseID) Z 
     On z.DeseaseId = d.DeseaseId 
WHERE GenderID in (1, 3) 
Order By z.Rank 
0

您應該使用公用表表達式(CTE)是這樣的:

with cte as (SELECT [DiseaseID], GenderID, COUNT(*) AS [Rank] FROM [DiseaseSymptom] WHERE 
    ([SymptomID] IN(1, 5)) GROUP BY [DiseaseID],GenderID ORDER BY [Rank] DESC) 
    select * FROM cte WHERE GenderID in (1, 3) 

希望這有助於;)

+0

目前尚不清楚OP究竟在嘗試什麼,你認爲這會解決什麼問題?你也完全忽略了原始文章中的一個表格,所以你不太可能返回OP需要的所有數據。 –

0

實在是沒有必要有一個嵌套查詢,剛剛加入和過濾

SELECT d.DiseaseID, d.DiseaseName, d.GenderID 
    , Symptoms = Count(ds.SymptomID) 
FROM Disease d 
     INNER JOIN DiseaseSymptom ds ON d.DiseaseID = ds.DiseaseID 
WHERE ds.SymptomID IN (1, 5) 
    AND d.GenderID IN (1, 3) 
GROUP BY d.DiseaseID, d.DiseaseName, d.GenderID 
ORDER BY Count(SymptomID) Desc 

SQLFiddle演示