我想将我的一个表格中的数据插入到另一个表格中 这是我填写的表格:
Act (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
birth_date DATETIME,
death_date DATETIME,
place VARCHAR(20)
);
在此表中,某些值为NULL - 例如,如果它是一个出生行为,则death_date为NULL。
这是我要将数据传输到的表格:
Population_Growth (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
number_of_births INT,
number_of_deaths INT,
place VARCHAR(20),
time DATE
);
最后,我希望此表能够显示同一地点和同一天的死亡人数和出生人数。至于出生和死亡的数量,我会做这样的事情:
INSERT INTO Population_Growth (number_of_births, number_of_deaths) VALUES
((COUNT (birth_date) FROM Act WHERE birth_date IS NOT NULL)),
((COUNT (death_date) FROM Act WHERE death_date IS NOT NULL));
但我不知道如何将其与相应的时间和日期联系起来。
答案 0 :(得分:1)
获取指定结果的一种方法是这样的查询:
SELECT c.place
, c.time
, SUM(c.count_births) AS number_of_births
, SUM(c.count_deaths) AS number_of_deaths
FROM (
SELECT b.place
, DATE(b.birth_date) AS `time`
, SUM(1) AS count_births
, SUM(0) AS count_deaths
FROM Act b
WHERE b.birth_date IS NOT NULL
GROUP BY b.place, DATE(b.birth_date)
UNION ALL
SELECT d.place
, DATE(d.death_date) AS `time`
, SUM(0) AS count_births
, SUM(1) AS count_deaths
FROM Act d
WHERE d.death_date IS NOT NULL
GROUP BY d.place, DATE(d.death_date)
) c
GROUP BY c.place, c.time
要将其转换为插入,请在SELECT前面加上:
INSERT INTO Population_Growth (place, `time`, number_of_births, number_of_deaths)
<强>后续强>
上面的查询将DATETIME列转换为DATE数据类型(通过截断时间部分。)
要按年份和月份获取摘要,但仍作为有效分配到DATE
列的表单,一个选项是替换所有表达式:
DATE(b.birth_date)
DATE(d.death_date)
(在上面的查询中)包含以下表达式:
DATE_FORMAT(b.birth_date,'%Y-%m-01')
DATE_FORMAT(d.death_date,'%Y-%m-01')
新表达式将从DATETIME列中提取年份和月份,并将day组件设置为该月的第1个。
答案 1 :(得分:1)
如果我理解正确,您希望从两个日期列中获取非NULL值的计数。以下是获取摘要的一种方法:
select place, d,
(select count(*) from act where act.birth_date = pd.d and act.place = pd.place) as births,
(select count(*) from act where act.death_date = pd.d and act.place = pd.place) as deaths
from (select place, birth_date as d from act union
select place, death_date from act
) pd;
然后您可以通过执行以下操作将其放入population_growth
:
INSERT INTO Population_Growth(place, time, number_of_births, number_of_deaths)
select place, d,
(select count(*) from act where act.birth_date = pd.d and act.place = pd.place) as births,
(select count(*) from act where act.death_date = pd.d and act.place = pd.place) as deaths
from (select place, birth_date as d from act union
select place, death_date from act
) pd;