在mysql中添加两列以区分男性和女性的计数

jtw3ybtb  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(356)

我正在尝试向查询中添加两个新列,以便能够获得男性和女性的计数

SELECT adggeth.reg01_maininfo.techname AS TechName
    ,adggeth.reg01_maininfo.techmobile AS Mobile
    ,monthname(adggeth.lng02_rpt_b_calvedets.calvdatealv) AS "Calving Month"
    ,count(adggeth.lng02_rpt_b_calvedets.sex) AS "No of Calves"
FROM adggeth.reg01_maininfo
    INNER JOIN adggeth.lng02_maininfo ON adggeth.reg01_maininfo.techmobile = adggeth.lng02_maininfo.aitechid
    INNER JOIN adggeth.lng02_rpt_b_calvedets ON adggeth.lng02_maininfo.hh_id = adggeth.lng02_rpt_b_calvedets.hh_id
        AND adggeth.lng02_maininfo.visitdate = adggeth.lng02_rpt_b_calvedets.visitdate
GROUP BY adggeth.reg01_maininfo.techname
    ,adggeth.reg01_maininfo.techmobile
    ,monthname(adggeth.lng02_rpt_b_calvedets.calvdatealv);

我要数一数我的母牛和公牛的数量 lng02_rpt_b_calvedets.sex = 1 指公牛犊 lng02_rpt_b_calvedets.sex = 2 指母牛

qfe3c7zg

qfe3c7zg1#

刚找到我的答案

SELECT 
    adggeth.reg01_maininfo.techname AS TechName,
    adggeth.reg01_maininfo.techmobile AS Mobile,
    MONTHNAME(
    adggeth.`serv00_rpt_calvdtls2`.`calvdatealv2`
    ) AS "Calving Month",
    COUNT(
    adggeth.`serv00_rpt_calvdtls2`.`sex2`
    ) AS "No of Calves",
    COUNT(
    IF (
    adggeth.serv00_rpt_calvdtls2.sex2 = 2,
    adggeth.serv00_rpt_calvdtls2.sex2,
    NULL
    )
    ) AS 'Femal Calf',
    COUNT(
    IF (
    adggeth.serv00_rpt_calvdtls2.sex2 = 1,
    adggeth.serv00_rpt_calvdtls2.sex2,
    NULL
    )
    ) AS 'Male Calf' 
    FROM
    adggeth.reg01_maininfo 
    INNER JOIN adggeth.`serv00_maininfo` 
    ON adggeth.reg01_maininfo.techmobile = adggeth.`serv00_maininfo`.`aitechid` 
    INNER JOIN adggeth.`serv00_rpt_calvdtls2` 
    ON adggeth.`serv00_maininfo`.`fid` = adggeth.`serv00_rpt_calvdtls2`.`fid` 
    AND adggeth.`serv00_maininfo`.`regdate` = adggeth.`serv00_rpt_calvdtls2`.`calvdatealv2` 
    GROUP BY adggeth.reg01_maininfo.techname,
    adggeth.reg01_maininfo.techmobile,
    MONTHNAME(
    adggeth.`serv00_rpt_calvdtls2`.`calvdatealv2`
    )
x8diyxa7

x8diyxa72#

虽然count不会对null进行计数,因此如果不是要查找的值,可以使用返回null的条件,但是使用sum要简单得多。mysql中的布尔表达式返回1或0,因此可以直接将它们的值相加。

SELECT 
  SUM(adggeth.serv00_rpt_calvdtls2.sex2 = 2) AS 'Female Calf', 
  SUM(adggeth.serv00_rpt_calvdtls2.sex2 = 1) AS 'Male Calf'
...
webghufk

webghufk3#

您还可以将计数聚合与if函数一起使用:

COUNT (IF(adggeth.lng02_rpt_b_calvedets.sex = 1, 1, NULL) ) AS Male_Calves_Count,
COUNT (IF(adggeth.lng02_rpt_b_calvedets.sex = 2, 1, NULL) ) AS Female_Calves_Count,
3bygqnnd

3bygqnnd4#

你可以使用 count 拜访某人 case 根据性别过滤小牛的表情:

COUNT (CASE adggeth.lng02_rpt_b_calvedets.sex WHEN 1 END) as "No of Male Calves",
COUNT (CASE adggeth.lng02_rpt_b_calvedets.sex WHEN 2 END) as "No of Female Calves"

相关问题