在SQL Server中选择Group中的计数记录?

问题描述 投票:1回答:3

我有一张wsm_Ref_Buildings表,里面有buildingidcity列。我希望所有的州都能看到所有的buildingid。例如:黑斯廷斯(city)有18座建筑物(count),我想在结果中拥有所有18个buildingid

询问

select count(BuildingId), city 
from wsm_Ref_Buildings 
group by City

enter image description here

sql-server select group-by
3个回答
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

两个查询都将使用我的示例数据创建以下输出

enter image description here

我希望它有所帮助


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

产量

enter image description here


-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
© www.soinside.com 2019 - 2024. All rights reserved.