在SQL查询中多次计数

时间:2012-07-12 07:26:58

标签: sql-server tsql

我需要一个数据库的报告,我需要最终结果 男性人数,女性人数,反对城市,最后反对国家。 我开始时喜欢这样的东西。

SELECT     p.StateName,  d.CityName,
 count(api.Gender) as Gender
FROM       dbo.Application_Personal_information as api INNER JOIN
           dbo.state as p ON api.State = p.ID INNER JOIN
           dbo.City as d ON api.City= d.ID
           group by p.StateName, d.CityName

当我这样做时

   SELECT     p.StateName,  d.CityName,
     count(api.Gender = 'Male) as Male,
     count(api.Gender = 'Female) as Female,
    FROM       dbo.Application_Personal_information as api INNER JOIN
               dbo.state as p ON api.State = p.ID INNER JOIN
               dbo.City as d ON api.City= d.ID
               group by p.StateName, d.CityName

它给了我错误。 语法不正确=。 我也尝试过使用select语句

 COUNT(select api.Gender from api where api.Gender ='Male') as Male,

但它也没有用。 ... 有什么想法吗?

2 个答案:

答案 0 :(得分:4)

SELECT     
    p.StateName,  d.CityName, 
    sum(case when Gender ='Male' then 1 else 0 end ) as Male_count,
    sum(case when Gender ='Female' then 1 else 0 end ) as Female_count

FROM
    dbo.Application_Personal_information as api INNER JOIN 
    dbo.state as p ON api.State = p.ID INNER JOIN 
    dbo.City as d ON api.City= d.ID 
group by 
    p.StateName, d.CityName

答案 1 :(得分:4)

如果您使用的是SQL Server 2005或更高版本,则可以尝试PIVOT功能:

WITH CTE AS
(   SELECT  p.StateName,  
            d.CityName,
            api.Gender
    FROM    dbo.Application_Personal_information as api 
            INNER JOIN dbo.state as p 
                ON api.State = p.ID 
            INNER JOIN dbo.City as d 
                ON api.City= d.ID
)
SELECT  *
FROM    CTE
        PIVOT
        (   COUNT(Gender)
            FOR Gender IN ([Male], [Female])
        ) pvt