将两个视图合并为一个带变换的结果集?

时间:2012-08-21 09:46:19

标签: sql sql-server views

我有几个视图在SQL Server中生成以下两个输出。 第一个(Flats输出)显示了Tileroofs和Brickwalls特定城镇的单位数量。第二个显示相同,但​​对于房屋。

我要做的是创建一个看起来像第三个例子的决赛桌,其中平面和房屋数量与相应的Tileroof和Brickwall组合相结合。

我已尝试过联合然后进行分组,但我真的很难将Flats and Houses计数列并排。有人能帮忙吗?

由于

--View one
| Town | Flats | TileRoofs | Brick Wall |
-----------------------------------------
| A    | 3     | Y         | N          |
| A    | 4     | N         | Y          |
| A    | 8     | N         | N          |


--View two
| Town | Houses | TileRoofs | Brick Wall |
------------------------------------------
| A    | 1      | Y         | Y          |
| A    | 2      | Y         | N          |
| A    | 5      | N         | Y          |
| A    | 2      | N         | N          |


--Prefered output, by combining the two--

| Town | Flats | Houses | TileRoofs | Brick Wall |
--------------------------------------------------
| A    | 0     |  1     | Y         | Y          |
| A    | 3     |  2     | Y         | N          |
| A    | 4     |  5     | N         | Y          |
| A    | 8     |  2     | N         | N          |

3 个答案:

答案 0 :(得分:3)

Full outer join might help here

select isnull(a.Town, b.Town) Town,
       isnull(a.TileRoofs, b.TileRoofs) TileRoofs,
       isnull(a.[Brick wall], b.[Brick wall]) [Brick wall],
       isnull(a.Flats, 0) Flats,
       isnull(b.Houses, 0) Houses
  from ViewOne a
  full outer join ViewTwo b
    on a.Town = b.Town
   and a.TileRoofs = b.TileRoofs
   and a.[Brick wall] = b.[Brick wall]

答案 1 :(得分:0)

select
    v2.Town ,coalesce(v1.flat,0) as flat,v2.houses,v2.TileRoofs, v2.Brick, v2.Wall 
from
    view2 as v2 left join view1 as v1
on v1.town=v2.town

答案 2 :(得分:0)

您可能正在进行完整的外部联接

select 
    houses.town,
    flats.flats, 
    houses.houses,
    houses.BrickWall,
    houses.TileRoofs
from flats
full outer join houses
    on houses.town=flats.town
    and houses.TileRoofs = flats.TileRoofs
    and houses.BrickWall = flats.BrickWall