2

我需要来自数据库的报告,我需要最终结果,例如男性人数,女性人数,显示针对城市,最后针对州。我从类似的东西开始。

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,

但它也不起作用。... 任何想法?

4

2 回答 2

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
于 2012-07-12T07:51:50.790 回答
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
于 2012-07-12T07:38:59.930 回答