sql - 选择生肖的 SQL 查询
问题描述
请告诉我 sql 查询按出生日期选择星座。
这是表结构。
CREATE TABLE constellation
constellation_name VARCHAR(5) PRIMARY KEY,
start_date INTEGER,
end_date INTEGER
);
INSERT INTO constellation
VALUES ('Aries', 321,419), ('Taurus',420 ,520),
('Gemini', 521,621), ('Cancer',622 ,722),
('Leo', 723,822), ('Virgo',823 ,922)
('Libra', 923,1023), ('Scorpio',1024 ,1122),
('Sagittarius',1123 ,1221), ('Capricorn', 1222,119),
('Aquarius', 120,218), ('Pisces', 219,320);
解决方案
请注意,varchar(5)
对于大多数星座来说,这不会让你走得太远。
您可以使用join
. 大多数数据库都有 和 之类的功能month()
,day()
尽管它们的名称可能略有不同。
这个想法是:
select t.*, c.constellation_name
from t join
constellation c
on month(dob) * 100 + day(dob) between start_mmdd and end_mmdd
编辑:
对付摩羯座:
select t.*, c.constellation_name
from t join
constellation c
on (start_mmdd < end_mmdd and
month(dob) * 100 + day(dob) between start_mmdd and end_mmdd
) or
(start_mmdd > end_mmdd and
(month(dob) * 100 + day(dob) >= start_mmdd or
month(dob) * 100 + day(dob) <= end_mmdd
) ;
推荐阅读
- sql-server - 从命令行运行 SSIS 例程的问题
- python - 当 arg 已经包含 " " 和 ' ' 引号时,如何将字符串 arg 提交给 subprocess.run(arg, shell=True)?
- excel - 单击时如何制作用“组”字填充单元格以用于下一个空行的按钮宏
- php - else 条件有效,即使为真
- python - nn.Linear 如何在 shape(batch_size, seq_length, hidden_size) 中工作?
- html - 在 Firestore 中为新的 Firebase 身份验证帐户创建用户数据
- kubernetes - 通过 k8s 代理访问 Grafana API
- cron - crontab 不执行脚本,但可以手动执行
- azure-pipelines - 根据存储库名称使用不同的池/无法访问作业条件中的“Build.Repository.Name”变量
- typescript - 为什么打字稿编译器不警告用变量覆盖getter?