我有一张包含类似数据的表,我正在寻找一种将[city]和[street]字段合并为一个字段的方法。 [street]字段是[city]字段的子字符串,可在[city]字段中找到总和 预期结果如下:
rocket_contrib
如何在mssql中做到这一点?
city/street value1 value2 value3 total
Wien 16 50 6 72
Quadenstrabe 14 46 1 61
Laberlsteg 2 4 5 11
Hamburg 7 9 5 21
Esplanade 3 7 4 14
Drehbahn 4 2 1 7
答案 0 :(得分:7)
只要您修复了数据类型并且不使用nvarchar
来存储int
,就可以了:
SELECT ISNULL(street, city) AS CityStreet,
SUM([Value1]) AS Value1,
SUM([Value2]) AS Value2,
SUM([Value3]) AS Value3,
SUM(Total) AS Total
FROM #CITY_TABLE
GROUP BY city, street WITH ROLLUP
HAVING city IS NOT NULL
ORDER BY CityStreet DESC;
答案 1 :(得分:2)
如果Value1,Value2,Value3和Total的数据类型为int,那么您的生活会容易得多。但是,有了您拥有的东西:
SELECT
CITY [City/Street],
SUM(convert(int,VALUE1)) [Value1],
SUM(convert(int,VALUE2)) [Value2],
SUM(convert(int,VALUE3)) [Value3],
SUM(convert(int,TOTAL)) [Value1] from
[dbo].#CITY_TABLE GROUP BY CITY
UNION
SELECT
STREET,
convert(int,value1),
convert(int,value2),
convert(int,value3),
convert(int,total)
from [dbo].#CITY_TABLE
答案 2 :(得分:1)
我想我会这样做:
select v.city_street, sum(t.value1) as value1, sum(t.value2) as value2, sum(t.value3) as value3
from #CityTable ct cross apply
(values (city), (street)
) v(city_street)
group by city_street;
这假定数字实际上是存储为数字而不是字符串。