这可能是初学者的问题,但我不知道转换的术语是什么,所以到目前为止我无法获得有用的搜索结果。
输入表如下:
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。
答案 0 :(得分: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