如何在同一行上显示一个表的多个列时连接这些表?

时间:2014-02-11 21:08:36

标签: sql sql-server join sql-server-2008-r2

我有一个价目表(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资源!

1 个答案:

答案 0 :(得分:0)

一种方法是使用JOIN表添加常规OITMGROUP BY要使用的字段,然后在HAVING后添加GROUP BY进行过滤已完成{1}}。

扩展您现有的查询,例如;

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