我有一个wsm_Ref_Buildings
表,其中包含buildingid
,city
列。我想看到所有州内的所有buildingid
。例如:黑斯廷斯(city
)有18个建筑物(count
),我希望结果中包含所有18个buildingid
。
查询
select count(BuildingId), city
from wsm_Ref_Buildings
group by City
答案 0 :(得分:2)
试试这个
SELECT
City,
BuildID,
BuildCnt = COUNT(BuildingId) OVER(PARTITION BY City) from wsm_Ref_Buildings
演示
DECLARE @T TABLE
(
City VARCHAR(5),
BuildID INT
)
INSERT INTO @T
VALUES('ABC',1),('ABC',2),('ABC',3),('XYZ',1),('XYZ',4),('HIJ',6)
SELECT
City,
BuildID,
BuildCnt = COUNT(1) OVER(PARTITION BY City)
FROM @T
输出
答案 1 :(得分:1)
据我了解,您希望连接构建ID值并显示城市和建筑物数量, 请检查
select
w.city,
count(*) as cnt,
stuff(
(
select ',' + convert(varchar(10),b.buildingid)
from wsm_Ref_Buildings b
where b.city = w.city
FOR XML PATH('')
), 1, 1, ''
) as list
from wsm_Ref_Buildings w
group by w.city
对于SQL Server 2017之前的版本,这是string concatenation in SQL
如果您有SQL Server 2017,可以使用string_agg string aggregation function,如下所示
select
city,
count(*) as cnt,
string_agg( convert(varchar(10), buildingid) , ',' ) within group (order by buildingid) as list
from wsm_Ref_Buildings
group by city
两个查询都将使用我的样本数据
创建以下输出我希望它有所帮助
答案 2 :(得分:-1)
SELECT
City,BuildID,
(select COUNT(WS.BuildingId) from wsm_Ref_Buildings AS WS
WHERE WS1.City=WS.City) as BuildCnt
from wsm_Ref_Buildings AS WS1