1

我有几个视图在 SQL Server 中生成以下两个输出。第一个(公寓输出)显示特定城镇中带有瓷砖和砖墙的公寓数量。第二个显示相同,但​​用于房屋。

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

我尝试过联合然后分组,但我真的很难让 Flats 和 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          |
4

3 回答 3

3

完全外部联接在这里可能会有所帮助

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]
于 2012-08-21T09:51:46.000 回答
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
于 2012-08-21T09:52:33.593 回答
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
于 2012-08-21T09:55:54.200 回答