我想知道x次怀孕的次数.

name baby_dob1 baby_dob2 baby_dob3 Pregnant
Mary 20-01-2021 02-03-2022 True
Esther 10-01-2020 True
Helen 01-01-2020 02-02-2021 09-09-2023 False
Laura True
Queen 25-04-2020 22-04-2022 18-07-2022 False

输出应如下所示:

Category of pregnancies Number of women
3 3
2 1
1 1

Meaning:
3 women have been pregnant three times.
1 woman has had two pregnancies.
1 woman has had one pregnancy.

逻辑:

在系统中你只能怀孕三次.

baby_dob1 is the date of birth of the first baby.
baby_dob2 is the date of birth of the second baby.
baby_dob3 is the date of birth of the third and last baby.

pregnant栏意味着母亲目前正怀着另一个尚未分娩的婴儿.

例如:

Helen has had three pregnancies.
Laura is currently pregnant so she has one pregnancy.
Mary would count as three pregnancies. Two that are in the past and one that is currently ongoing since the pregnant column is true.

我如何编写postgres查询?

推荐答案

在系统中你只能怀孕三次.

如果这确实是系统应该如何工作的,那么表定义就可以了.否则,考虑将你的关系设计正常化,就像 comments 中建议的那样,以处理数量可变的婴儿(和怀孕).

num_nonnulls()NULLIF()

SELECT num_nonnulls(baby_dob1, baby_dob2, baby_dob3, NULLIF(pregnant, false)) AS "number of pregnancies"
     , count(*) AS "number of women"
FROM   tbl
GROUP  BY 1;

其他变体:

SELECT num_nonnulls(baby_dob1, baby_dob2, baby_dob3)
     + pregnant::int AS "number of pregnancies"
     , count(*) AS "number of women"
FROM   tbl
GROUP  BY 1;
SELECT (baby_dob1 IS NOT NULL)::int
     + (baby_dob2 IS NOT NULL)::int
     + (baby_dob3 IS NOT NULL)::int
     + pregnant::int AS "number of pregnancies"
     , count(*) AS "number of women"
FROM   tbl
GROUP  BY 1;

fiddle

第二个和第三个变种使用的事实是演员阵容true::int产生1.两者还假定列pregnant将被定义NOT NULL.

第一个变体不需要这些技巧/假设中的任何一个.因此,这是我的最爱.

Aside:
Always work with ISO date literals. "2021-01-20", not "20-01-2021". ISO literals are unambiguous with any datestyle setting - as opposed to other formats.

Sql相关问答推荐

Microsoft Access UNION将长文本字段限制为255个字符

为什么postgres中CURRENT_TIMESTAMP的日期与CURRENT_DATE不同?

Postgres,使用iLike运算符从json数组中搜索的工作方式与从常规表中搜索不同

将重复的值更新为下一个空闲数字

计算周时出现SQL错误结果

检索上一个星期四和上一个星期三

将结果从一列转换为两行或更多

缺少日期标识

按用户和时间列出的SQL Group考勤列表

基于开始/结束日期重叠的BigQuery突发行

SQL仅返回第一个字母在A-Z之间的值

Spark / Hive:如何获取列中正值的百分比?

如何从三个连接表中获取数据,并始终显示第一个表中的数据,以及第三个表中的空值或现有记录?

每个ID的SQL返回可能的最低级别及其值

更新表 A,然后将新值插入表 B(包含更新内容的历史日志(log))

如果 SQL 中不存在数据,如何根据某个 ID 为所有日期添加前一行

CURRENT_ROW 窗口框架上的 SQL 滞后

Lag() 获取snowflake的值变化

SQL中所有先前日期的累计总和

在 SQL 中将行显示为列