我目前正在PostgreSQL服务器上工作。给定一个包含以下内容的表:
New Jersey | Male
New Jersey | Female
New York | Male
我想返回看起来像这样的东西:
New Jersey | Male | 2
New Jersey | Female | 2
New York | Male | 1
我基本上想知道表中有多少次新泽西州或纽约出现,无论它是男性还是女性。我也不想摆脱任何行。有什么解决办法吗?谢谢!
答案 0 :(得分:2)
您需要窗口功能:
select t.*, count(city_name) over (partition by city_name)
from table t;
答案 1 :(得分:0)
这应该做
SELECT state,
gender,
COUNT(1) OVER
( PARTITION BY state) fieldYouWant
FROM Your_Table
答案 2 :(得分:0)
以为您还可以使用子查询和聚合功能
select distinct t1.*,t2.cnt as count from t t1
inner join
(
select city_name, count(*) as cnt from t
group by city_name
) as t2 on t1.city_name=t2.city_name
http://sqlfiddle.com/#!17/af578/1
city_name gender count
New York Male 1
New Jersey Female 2
New Jersey Male 2