2012-11-09 157 views
0

我正在使用SQL Server 2005查詢Web Developer 2010,並且min函數似乎返回多個值(對於返回的每個ID,請參見下文)。理想情況下,我希望它只爲每個ID返回一個。SQL MIN()返回多個值?

SELECT  Production.WorksOrderOperations.WorksOrderNumber, 
      MIN(Production.WorksOrderOperations.OperationNumber) AS Expr1, 
      Production.Resources.ResourceCode, 
      Production.Resources.ResourceDescription, 
      Production.WorksOrderExcel_ExcelExport_View.PartNumber, 
      Production.WorksOrderOperations.PlannedQuantity, 
      Production.WorksOrderOperations.PlannedSetTime, 
      Production.WorksOrderOperations.PlannedRunTime 
FROM  Production.WorksOrderOperations 
INNER JOIN Production.Resources 
      ON Production.WorksOrderOperations.ResourceID = Production.Resources.ResourceID 
INNER JOIN Production.WorksOrderExcel_ExcelExport_View 
      ON Production.WorksOrderOperations.WorksOrderNumber = Production.WorksOrderExcel_ExcelExport_View.WorksOrderNumber 
WHERE  Production.WorksOrderOperations.WorksOrderNumber IN 
      (SELECT WorksOrderNumber 
       FROM  Production.WorksOrderExcel_ExcelExport_View AS WorksOrderExcel_ExcelExport_View_1 
       WHERE (WorksOrderSuffixStatus = 'Proposed')) 
      AND Production.Resources.ResourceCode IN ('1303', '1604') 
GROUP BY Production.WorksOrderOperations.WorksOrderNumber, 
      Production.Resources.ResourceCode, 
      Production.Resources.ResourceDescription, 
      Production.WorksOrderExcel_ExcelExport_View.PartNumber, 
      Production.WorksOrderOperations.PlannedQuantity, 
      Production.WorksOrderOperations.PlannedSetTime, 
      Production.WorksOrderOperations.PlannedRunTime 

如果你能得到它周圍你的頭,我從多個表,其中WorksOrderNumber也包含一個子查詢中,和許多其他條件選擇某些列。

結果集看起來有點像這樣,模糊了不相關的數據。

http://i.stack.imgur.com/5UFIp.png(不讓我嵌入圖像)。

突出顯示的行不應該在那裏,我不能明確地將它們過濾掉,因爲此結果集將每天更新,並且可能會發生在不同的記錄中。

我已經嘗試鑄造並將OperationNumber轉換爲衆多其他數據類型,varchar類型返回'100'而不是'30'。還嘗試搜索搜索引擎,沒有人似乎有同樣的問題。

我沒有構造表(它們被嚴重規範化),並且不可能重構它們。

任何想法讚賞,非常感謝。

+0

是有辦法的IN()函數之前,必須在WHERE子句中多列?像這樣:WHERE(WorksOrderNumber,OperationNumber)IN(SELECT WorksOrderNumber,OperationNumber FROM table) – Charlie

+0

請注意,標籤是獨立的。也就是說,結合'sql'和'server'並不意味着你在談論MS SQL Server。請務必小心選擇標籤。 – Charles

回答

0

MIN函數返回組中的最小值。 如果你想要每個ID的最小值,你需要在ID上獲得組。 我假設你通過「ID」引用Production.WorksOrderOperations.WorksOrderNumber。

您可以在SQL添加爲「表」:

(SELECT Production.WorksOrderOperations.WorksOrderNumber, 
     MIN(Production.WorksOrderOperations.OperationNumber) 
    FROM Production.WorksOrderOperations 
GROUP BY Production.WorksOrderOperations.WorksOrderNumber) 
+0

將聲明作爲一個臨時表,謝謝,有沒有辦法在SQL中執行以下操作? WHERE Field1 + Field2 IN(SELECT Field1,Field2 FROM)etc ... – Charlie

+0

Bodge的位,但我最終宣佈了兩個單獨的表,然後使用select子句來查詢第二個表是否包含第一個值,實現了預期結果集,它將來如何證明是另一回事。謝謝你指導我在正確的方向。 – Charlie

+0

回覆第一條評論:如果您有其他問題,您應該將其作爲新問題發佈(前提是您無法通過搜索網絡找到答案)。 –