我有这两个表:
人
Name Gender RegionID
Bob Male 1
Mary Female 2
Jane Female 3
Chris Male 1
Paul Male 2
Matt Male 2
Jenny Female 1
区域
ID Region
1 North
2 South
3 Central
我想最终得到一张这样的表:
Region Male Female
North 2 1
South 2 1
Central 0 1
我首先尝试使用区域ID来生成结果表,因此不需要连接:
select RegionID, Gender, count(Name) from Person group by RegionID
但性别领域尚未定义。并且真的不知道从那里去哪里。
标记后,我正在使用alasql
JavaScript库。
答案 0 :(得分:1)
试着看看这个:
'$${CLICK_URL_ENC}$'.replace(/\$\${CLICK_URL_ENC}\$/g, '$$$$${CLICK_URL_ENC}$$$');
答案 1 :(得分:1)
您可以使用此
select region
,sum(case when b.Gender='Male' then 1 else 0 end) Male
,sum(case when b.Gender='Female' then 1 else 0 end) Female
from Region a
inner join Person b on a.[Id]=b.RegionID
group by a.[Id],a.Region
order by [id]
在tsql中你可以转动,如果你有几个以上的值可以转动,这可能会更容易:
Select * from
( select Region ,Gender
from Region a
inner join Person b on a.[Id]=b.RegionID ) p
pivot
( count(Gender)
for Gender
IN ([Male],[Female])
) pivottable
如果你添加第三个性别,像这样的非二元
insert into Person values ('Kim','Nonbinary',3)
您可以轻松地将查询扩展到帐户:
Select * from
( select Region ,Gender
from Region a
inner join Person b on a.[Id]=b.RegionID ) p
pivot
( count(Gender)
for Gender
IN ([Male],[Female],[Nonbinary])
) pivottable
order by a.[id]
答案 2 :(得分:1)
对于那些在alasql
寻找最终解决方案的人来说,这是我在此页面的帮助下提出的:
var res = alasql("SELECT regionData.Title \
, SUM(CASE WHEN peopleData.Gender = 'Male' THEN 1 ELSE 0 END) AS Male \
, SUM(CASE WHEN peopleData.Gender = 'Female' THEN 1 ELSE 0 END) AS Female \
FROM ? regionData LEFT JOIN ? peopleData \
ON regionData.ID = peopleData.RegionID\
GROUP BY regionData.Title", [regionData, bensData]);