也计算双重身份的人

时间:2018-10-15 10:48:52

标签: sql sql-server tsql

我试图计算来自sql server中不同国家/地区的人数。但是有些人也有双重公民身份。 如何编写同时考虑双重国籍的查询并计算两国的人数。

示例:

ID  CITIZENSHIP DUAL CITIZENSHIP
00000S123   US  ITALY
00000BH01   UK  
00000VA03   US  
00000SR01   UK  US

理想情况下,只有两名学生拥有美国公民身份,但应为3名,因为一名学生也拥有美国双重国籍。 请注意,我不想在where子句

中进行硬编码
WHERE  DUAL_CITIZENSHIP='US'

谢谢, 信德省

4 个答案:

答案 0 :(得分:2)

实际上,我相信您希望出于计数的目的,第一排名义上变成第二排,而双重公民船则向下旋转第二排。当然,您可以查询citizenship ='US'或dual_citizenship ='US',但希望避免谓词被双重包含。

类似的东西(未提供表名):

SELECT count(*)
FROM
(
    SELECT id, citizenship
    FROM yourTable
    UNION ALL
    SELECT id, dual_citizenship as citizenship
    FROM yourTable
    WHERE dual_citizenship is not null
) a
WHERE citizenship = 'US'

如果您想要所有国家/地区:

SELECT citizenship, count(*)
FROM
(
    SELECT id, citizenship
    FROM yourTable
    UNION ALL
    SELECT id, dual_citizenship as citizenship
    FROM yourTable
    WHERE dual_citizenship is not null
) a
GROUP BY citizenship

答案 1 :(得分:0)

您可以使用联合来合并CITIZENSHIP

    select  ID,  CITIZENSHIP
    from my_table 
    where  CITIZENSHIP ='US'
    union  
    select  ID,  DUAL_CITIZENSHIP
    from my_table 
    where  CITIZENSHIP ='US'


select count(*) 
from (

    select  ID,  CITIZENSHIP
    from my_table 
    where  CITIZENSHIP ='US'
    union  
    select  ID,  DUAL_CITIZENSHIP
    from my_table 
    where  CITIZENSHIP ='US'

)

答案 2 :(得分:0)

您可以使用UNPIVOT

Select T.Country, count(*)
from (
Select id,Country
from TABLENAME t
     unpivot (
     Country for c in (CITIZENSHIP ,DUALCITIZENSHIP)
     ) Unpvt
     ) T
WHERE len(Country)>0
Group by T.Country

如果您要按特定国家/地区进行过滤,则可以选择关闭的地方

答案 3 :(得分:0)

WITH cte (Citizenship, NumberOfStudents) as (
    SELECT Citizenship, COUNT(*)
    FROM Students
    GROUP BY Citizenship
    UNION ALL
    SELECT DualCitizenship, COUNT(*)
    FROM Students WHERE DualCitizenship IS NOT NULL
    GROUP BY DualCitizenship
)
SELECT Citizenship, SUM(NumberOfStudents) as NumberOfStudents
FROM cte
GROUP BY Citizenship;

结果是:

enter image description here