0

这可能是初学者的问题,但我不知道转换的术语是什么,所以到目前为止我无法获得有用的搜索结果。

输入表如下:

ID, FromCity, ToCity, ViaCity
1, New York, Chicago, NULL
2, New York, Los Angeles, Chicago
3, Chicago, Boston, NULL

所需的输出是

City, FromCount, ToCount, ViaCount
New York, 2, 0, 0
Chicago, 1, 1, 1
Los Angeles, 0, 1, 0
Boston, 0, 1, 0
NULL, 0, 0, 2

城市名称列表应该从第一个表中生成,即它没有现有的表。

我更喜欢构建一个索引视图,但如果查询太复杂而 SSIS 可以使它变得容易,我也可以使用 SSIS。

4

1 回答 1

1

这是一个独立于数据库的方法:

select city, sum(fromcity) as fromcity, sum(tocity) as tocity, sum(via) as via
from ((select fromcity as city, 1 as fromcity, 0 as tocity, 0 a via
       from t
      ) union all
      (select tocity, 0, 1, 0
       from t
      ) union all
      (select via, 0, 0, 1
       from t
      )
     ) t
group by city
于 2013-06-21T02:13:25.193 回答