2014-02-11 47 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) –

相关问题