我如何制作一个表格来显示不同表sqlite3中男性和女性按十年的比例

问题描述 投票:0回答:1

我想显示按十年划分的性别比例,将表 1 和表 2 添加到一起

它应该看起来像这样:

年份 男性总和 女性总和
2000 ### ####
2010 ##### ###
sql = ("Select "
           "sum(case when SEX LIKE 'Male%' then 1 else 0 end),sum(case when SEX LIKE 'Female%' then 1 else 0 end), YEAR/10*10"
           "from table 1"
           "UNION ALL"
           "sum(case when SEX LIKE 'Male%' then 1 else 0 end), sum(case when SEX LIKE 'Female%' then 1 else 0 end),Year/10*10 "
           "from table2"
           " where table1.YEAR AND table2.Year != ' ' "
           "group by table1.YEAR/10 ")

这是我的代码,我能创建的最好的结果是两张表,分别按几十年列出了男性和女性,但我无法在一张汇总表中按男性或女性总结每个十年的值,以产生比率

sql sqlite join union
1个回答
0
投票

我相信以下内容证明了:-

a) 如何只需要一个表,以及 b)

CASE
构造也不是必需的。

DROP TABLE IF EXISTS table1;
CREATE TABLE IF NOT EXISTS table1 (year INTEGER, sex TEXT);
/* LOAD DATA */
INSERT INTO table1 VALUES
    (2000,'male'),(2000,'male'),(2001,'male'),(2002,'male'),(2003,'male'),
    (2004,'male'),(2010,'male'),(2011,'male'),(2012,'male'),(2013,'male'),
    (2000,'female'),(2000,'male'),(2001,'female'),(2002,'male'),(2003,'female'),
    (2004,'male'),(2010,'female'),(2011,'male'),(2012,'female'),(2013,'male'),
    (2005,'whatever'),
    (2023,'niether')
;

/* DEMO */
SELECT 
    (year / 10) * 10 AS decadestart,
    ((year / 10) * 10) + 9  AS decadeend, 
    count(sex) AS total, 
    sum(sex = 'male') AS m, 
    sum(sex = 'female') AS f, 
    sum(sex <> 'male' AND sex <> 'female') AS o,
    /* percentages*/
    round((CAST((sum(sex = 'male')) AS REAL) / count(sex)) * 100,3) AS mp,
    round((CAST((sum(sex = 'female')) AS REAL) / count(sex)) * 100,3) AS fp,
    round((CAST((sum(sex <> 'male' AND sex <> 'female')) AS REAL) / count(sex)) * 100,3) AS op
    FROM table1 
    GROUP BY year/10
;
/* CLEANUP */
DROP TABLE IF EXISTS table1;

结果:-

© www.soinside.com 2019 - 2024. All rights reserved.