我正在尝试确定两个表之间按州和城市分组的城市人口变化,如下所示:
**TABLE 1** **TABLE 2**
NY New York 10,000 NY New York -3000
NY Syracuse 5,000 NY Syracuse 5000
PA Phila 12,000 PA Phila 1000
PA Erie 11,000 PA Erie 4000
我使用的查询如下:
SELECT Table1.State, Table1.City, SUMtable1.populationsum-Nz(SUMtable2.populationsum,0) AS Total
FROM (SELECT SUM(table1.populationchange) AS popsum, table1.State
FROM Table1
GROUP BY table1.State, table1.City) AS SUMtable1
LEFT JOIN (SELECT SUM(table2.populationchange) AS rsum, table2.State
FROM table2
GROUP BY table2.State, table2.City) AS SUMtable2
ON SUMtable1.State= SUMtable2.State;
但是,这只能给我这个:
**RESULT**
NY 7000
NY 10000
PA 13000
PA 15000
我需要它才能返回城市。此时,查询提示我输入城市的参数值。将它留空并按下输入会得到我的结果。我该如何完成此查询?
答案 0 :(得分:1)
City不是FROM查询的一部分。
SELECT State,City, sum(possum) AS Total
FROM ((
SELECT SUM(table1.populationchange) AS popsum, table1.State as state,
Table1.City as city
FROM Table1
GROUP BY table1.State, table1.City)
Union All (
SELECT SUM(table2.populationchange) AS rsum, table2.State as state ,
Table2.City as city
FROM table2
GROUP BY table2.State, table2.City) )
Group by state,city
答案 1 :(得分:0)
样本表的相同情况:
create table #temp1(c varchar(100),s varchar(100), p int);
create table #temp2(c varchar(100),s varchar(100), p int);
Insert into #temp1(c,s,p) values('ny','syc',10)
Insert into #temp1(c,s,p) values('ny','ny',10)
Insert into #temp1(c,s,p) values('Nc','ra',10)
Insert into #temp1(c,s,p) values('Ns','char',10)
Insert into #temp2(c,s,p) values('ny','syc',10)
Insert into #temp2(c,s,p) values('ny','ny',10)
Insert into #temp2(c,s,p) values('Nc','ra',10)
Insert into #temp2(c,s,p) values('Ns','char',10)
select result.s,result.c,sum(p) as total from (
select * from #temp1 union all select * from #temp2) as result group by result.c,result.s
确切查询:
select res.state,res.city,sum(res.popultationchange) as totalchange
from(
select * from Table1 union all select * from Table2
) as res group by res.state,res.city
希望这是你所需要的!