2014-02-11 68 views
0

我有一個價目表表(ITM1),看起來像這樣:如何在顯示同一行上的一個表的多個列的同時連接這些表?

ItemCode PriceList Price 
----------------------------- 
5740660  1   2.06 
5740660  2   3.05 
5740660  3   3.05 
5740660  4   3.05 
5740660  5   2.95 
5740660  10   2.15 
5740661  1   12.86 
5740661  2   19.48 
5740661  3   19.48 
5740661  4   24.35 
5740661  5   11.69 
5740661  10   13.79 

和信息表(OITM)是這樣的:

ItemCode Description   QryGroup11 
--------------------------------------------- 
5740660  Seal, Head Locating Y 
5740661  Screw, Head Locating N  

我發現了一個查詢這裏顯示像我的價格這樣的:

Item No. Actual Cost AMG Retail Mil Wholesale Mil Retail AMG Dealer Civ Retail 
--------------------------------------------------------------------------------------- 
5740660  2.06  3.05  3.05    3.05   1.83   2.15 
5740661  12.86  19.48  19.48   24.35   11.69   13.79 

查詢:

SELECT 
    ItemCode 
    ,MAX(price1) as 'Actual Cost' 
    ,MAX(price2) as 'AMG Retail' 
    ,MAX(price3) as 'Mil Wholesale' 
    ,MAX(price4) as 'Mil Retail' 
    ,MAX(price5) as 'AMG Dealer' 
    ,MAX(price10) as 'Civ Retail' 
FROM 
    (SELECT 
     ItemCode 
     ,CASE WHEN PriceList = 1 THEN price END AS Price1 
     ,CASE WHEN PriceList = 2 THEN price END AS Price2 
     ,CASE WHEN PriceList = 3 THEN price END AS Price3 
     ,CASE WHEN PriceList = 4 THEN price END AS Price4 
     ,CASE WHEN PriceList = 5 THEN price END AS Price5 
     ,CASE WHEN PriceList = 10 THEN price END AS Price10 
    FROM ITM1) AS ITM1 
GROUP BY 
    ItemCode 

我的問題:

我如何加入我的表顯示Description該項目,並添加一個where子句來僅QueryGroup11 = 'Y'顯示?

我瞭解內部連接,並可以從多個表中獲得很好的結果,但對於上面的查詢,我無法完全看到信息顯示沒有錯誤。

感謝您的一個偉大的SQL Server資源!

+0

http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx –

回答

0

一種方式是添加的是一個JOINOITM表,GROUP BY要使用和添加HAVING做濾波GROUP BY已經完成後的字段。

擴展您現有的查詢,類似於;

SELECT ITM1.ItemCode, Description 
    ,MAX(price1) as 'Actual Cost' 
    ,MAX(price2) as 'AMG Retail' 
    ,MAX(price3) as 'Mil Wholesale' 
    ,MAX(price4) as 'Mil Retail' 
    ,MAX(price5) as 'AMG Dealer' 
    ,MAX(price10) as 'Civ Retail' 
FROM 
(
    SELECT ItemCode 
    ,CASE WHEN PriceList = 1 THEN price END AS Price1 
    ,CASE WHEN PriceList = 2 THEN price END AS Price2 
    ,CASE WHEN PriceList = 3 THEN price END AS Price3 
    ,CASE WHEN PriceList = 4 THEN price END AS Price4 
    ,CASE WHEN PriceList = 5 THEN price END AS Price5 
    ,CASE WHEN PriceList = 10 THEN price END AS Price10 
    FROM ITM1 
) AS ITM1 
JOIN OITM ON ITM1.ItemCode = OITM.ItemCode 
GROUP BY ITM1.ItemCode, OITM.Description, OITM.QryGroup11 
HAVING QryGroup11='Y' 

An SQLfiddle to test with

+0

工作完美...我被卡在一個where語句的想法,並有我的聯接在錯誤的地方。 感謝Joachim! –

+0

有或在這裏工作相同。你也不需要內聯視圖。 [小提琴](http://sqlfiddle.com/#!3/1ba5c/11) –

相關問題