包括一列以对具有特定值的记录进行计数

时间:2019-05-21 16:33:35

标签: sql sql-server

我想返回表中的所有数据并添加一列,该列对子集中的记录数(例如,邻里的房屋数)进行计数。

我尝试过

CASE
    WHEN EXISTS (SELECT 1 as [parcels]
        FROM dbo.parcels p2
        WHERE p2.Neighborhood = p.Neighborhood)
    THEN COUNT([parcels]) END  -- can't count outside subquery
        as [TotalProps]

对于任何给定邻域中的每个属性记录,子查询本身返回的值为1,但是我无法在THEN语句中对子查询之外的[宗地]进行计数/求和。

输入表:

dbo.parcels
ID    Address        Neighborhood
==    =======        ============
1     123 Main St    MITO
2     124 Main St    MITO
3     200 2nd St     MITO
4     201 2nd St     MITO
5     5 Park Ave     FAIRWIND
6     1600 Baker St  GALLERY
7     1601 Baker St  GALLERY
8     1602 Baker St  GALLERY

SELECT *, <<<COUNT(neighborhood props)>>> as [TotalProps]
FROM dbo.parcels p

预期输出:

ID    Address        Neighborhood  TotalProps
==    =======        ============  ==========
1     123 Main St    MITO          4
2     124 Main St    MITO          4
3     200 2nd St     MITO          4
4     201 2nd St     MITO          4
5     5 Park Ave     FAIRWIND      1
6     1600 Baker St  GALLERY       3
7     1601 Baker St  GALLERY       3
8     1602 Baker St  GALLERY       3

3 个答案:

答案 0 :(得分:2)

您可以使用COUNT OVER PARTITION个集合:

SELECT
   p.*,
   COUNT(ID) OVER(PARTITION BY Neighborhood) AS TotalProps
FROM dbo.parcels p

答案 1 :(得分:1)

使用窗口功能:

select p.*, count(*) over (partition by neighborhood)
from dbo.parcels p;

答案 2 :(得分:0)

让事情变得简单-基本的子选择将为您提供所需的东西...

SELECT
p.*,
(
    select count(*)
    FROM dbo.parcels p2
    WHERE p2.neighborhood = p1.neighborhood ) AS hoodcount
FROM dbo.parcels p