如何在这里使用self join来产生所需的输出

时间:2013-02-19 21:56:24

标签: sql sql-server-2008 tsql

我有这样的表结构:

CREATE TABLE Item
(
  ItemKey BIGINT,
  DisplayName VARCHAR(100)
)

INSERT INTO Item VALUES (136172,'Computer')
INSERT INTO Item VALUES (156737,'Car')

CREATE TABLE ItemTypeFactvw
(
   ItemKey BIGINT,
   TypeDimKey BIGINT
)

INSERT INTO ItemTypeFactvw VALUES (136172,483)
INSERT INTO ItemTypeFactvw VALUES (136172,1353)
INSERT INTO ItemTypeFactvw VALUES (156737,1000)

CREATE TABLE ItemTypeDimvw
(
  Id BIGINT,
  BaseId BIGINT,
  TypeDimKey BIGINT,
  DisplayName VARCHAR(100)

)

INSERT INTO ItemTypeDimvw VALUES (1,80,483,'IT Gadgets')
INSERT INTO ItemTypeDimvw VALUES (3,1,1353,'Electronics')
INSERT INTO ItemTypeDimvw VALUES (2,44,1000,'Vehicle')

我需要像这样产生结果(所需的输出):

| ITEMKEY | DISPLAYNAME | TYPEDIMKEY | ID | BASEID | ITEM BASE TYPE |
---------------------------------------------------------------------
|  136172 |    Computer |        483 |  1 |     80 |    Electronics |
|  156737 |         Car |       1000 |  2 |     44 |        Vehicle |

这是我的查询:

SELECT i.ItemKey, 
        i.DisplayName, 
        it.TypeDimKey,
        itd.Id,
        itd.BaseId,
        itd.DisplayName 'Item Base Type'
  FROM Item i
INNER JOIN ItemTypeFactvw it
on i.ItemKey = it.ItemKey
INNER JOIN  ItemTypeDimvw itd
ON itd.TypeDimKey = it.TypeDimKey

以上查询不会产生所需的输出,因为它还会带来ItemTypeDimvw DisplayName"IT Gadgets"的其他记录。

将此视为一个类层次结构。 IT小工具继承了电子产品。所以我需要在这种情况下显示基本类型它是IT小工具的电子产品

http://sqlfiddle.com/#!3/ef094/1

1 个答案:

答案 0 :(得分:2)

这是你想要的吗?

select  i.ItemKey, 
        i.DisplayName, 
        it.TypeDimKey,
        itd.Id,
        itd.BaseId,
        itd.DisplayName 'Item Base Type'
  from Item i
inner join ItemTypeFactvw it
on i.ItemKey = it.ItemKey
inner join ItemTypeDimvw itd
on itd.TypeDimKey = it.TypeDimKey
left outer join ItemTypeDimvw itd2
on itd2.id = itd.BaseId
where itd2.id is null