计算SQL中多个列的不同组合的数量

时间:2016-12-15 17:05:11

标签: sql-server count concat

有人问过这个问题的多种风格,但我无法找到我想要做的事情。这是我的原始表(sqlServer):

State  City           Job
CA     LOS ANGELES    DEVELOPER
CA     SAN FRANCISCO  DESIGNER
CA     LOS ANGELES    DESIGNER
NY     NEW YORK       DEVELOPER

我想计算State和City的不同组合,并将其作为表中的新列返回。所以最终产品看起来像:

State  City           Job         # of Unique
CA     LOS ANGELES    DEVELOPER   3
CA     SAN FRANCISCO  DESIGNER    3
CA     LOS ANGELES    DESIGNER    3
NY     NEW YORK       DEVELOPER   3

我尝试使用同一个表并使用计数进行内部联接,但这并没有返回正确的结果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

尝试此查询;

测试数据

CREATE TABLE #TestData (State nvarchar(2), City nvarchar(20), Job nvarchar(20))
INSERT INTO #TestData
VALUES
 ('CA','LOS ANGELES','DEVELOPER')
,('CA','SAN FRANCISCO','DESIGNER')
,('CA','LOS ANGELES','DESIGNER')
,('NY','NEW YORK','DEVELOPER')

查询

SELECT
     a.State
    ,a.City
    ,a.Job
    ,b.CountField
FROM #TestData a
CROSS JOIN (SELECT 
            COUNT(DISTINCT State + City) CountField
            FROM #TestData
            ) b

输出(无序,因为没有按语句排序)

State   City            Job         CountField
CA      LOS ANGELES     DEVELOPER   3
CA      LOS ANGELES     DESIGNER    3
CA      SAN FRANCISCO   DESIGNER    3
NY      NEW YORK        DEVELOPER   3

根据评论中的问题,您可以执行此操作以仅过滤计数中的CA;

SELECT
     a.State
    ,a.City
    ,a.Job
    ,b.CountField
FROM #TestData a
CROSS JOIN (SELECT 
            COUNT(DISTINCT State + City) CountField
            FROM #TestData
            WHERE State = 'CA'
            ) b

哪个应输出

State   City            Job         CountField
CA      LOS ANGELES     DEVELOPER   2
CA      LOS ANGELES     DESIGNER    2
CA      SAN FRANCISCO   DESIGNER    2
NY      NEW YORK        DEVELOPER   2