求和多个表的IF查询

时间:2014-12-02 06:41:53

标签: sql sql-server

我每个月都有一张表,我需要添加一列。我需要进行查询以在一个表中显示它。我做的第一件事就是将所有表联合起来以获得独特的国家。如何配置我开始生成我需要的输出的ms访问查询?

示例表:

表1:2014年1月

 | Country | Headcount |
 |   USA   |    100    |
 |  China  |     50    |
 |  Russia |     75    |
 |   USA   |     10    |

表2:2014年2月

 | Country | Headcount |
 |   USA   |    100    |
 |  China  |     50    |
 |  Mexico |     100   |
 |  China  |     75    |

表3:所有国家

 | Country |
 |   USA   |
 |  China  |
 |  Mexico |
 |  Russia |

期望的输出:

 | Country | January   |  February  |
 |   USA   |    110    |  100       |
 |  China  |    50     |  125       |
 |  Russia |     75    |  0         |
 |  Mexico |     0     |  100       |

到目前为止,这是我的查询,但它似乎无法正常工作..

SELECT a.[Country] As Country, 
SUM(IIF(a.[Country] = b.[Country], b.[Headcount],0)) As January 
SUM(IIF(a.[Country] = c.[Country], c.[Headcount],0)) As February
FROM [All Countries] As a, 
(SELECT [Headcount], [Country] FROM [January 2014]) As b,
(SELECT [Headcount], [Country] FROM [February 2014]) As c
GROUP BY a.[Country]

2 个答案:

答案 0 :(得分:1)

这是一种应该有效的方法 - (已编辑)

    SELECT a.[Country] As Country, 
SUM(IIF(a.[Month] = "Jan", b.[Headcount],0)) As January 
SUM(IIF(a.[Month] = "Feb", c.[Headcount],0)) As February

FROM     (
SELECT [Headcount], [Country], "Jan" AS [Month] FROM [January 2014]
 UNION ALL
SELECT [Headcount], [Country], 'Feb' AS [Month]  FROM [February 2014]
UNION ALL
...
) AS a
GROUP BY a.[Country]

答案 1 :(得分:0)

我会尝试这样的事情:

SELECT a.country,
(SELECT SUM(b.headcount) FROM table1 b WHERE b.country = a.country) as january, 
(SELECT SUM(c.headcount) FROM table2 c WHERE c.country = a.country)as february
FROM countries a

GROUP BY a.`country`