mysql - 获取未下订单产品的男性用户总数和女性用户总数

标签 mysql sql

如何获得未下订单产品的女性用户总数、男性用户总数以及(男性和女性用户的总和)。结果应如下所示:

total male     | total female     | total
---------------------------------------
 31            |      24          |  55
---------------------------------------

fiddle 帮助http://sqlfiddle.com/#!9/3a0e30/36

之前的代码:

select p.*,
   (select count(*)
    from users u 
    where u.uid not in (select o.uid from       orders o where o.productid = p.productid) and 
          u.gender = 'Male'
   ) as NumMales,
   (select count(*)
    from users u 
    where u.uid not in (select o.uid from orders o where o.productid = p.productid) and 
          u.gender = 'Female'
   ) as NumFemales     

来自产品p;

最佳答案

抱歉,我一开始没理解你的问题,我以为你是在尝试计算用户数量,结果发现你是在尝试计算每个尚未下单的人可能购买的产品订单。

SELECT SUM(CASE WHEN gender = 'Male' THEN 1
           ELSE 0
           END) as Male,
       SUM(CASE WHEN gender = 'Female' THEN 1
           ELSE 0
           END) as Female,
       COUNT(1) as Total
FROM Users U INNER JOIN Products P
LEFT JOIN Orders O ON O.uid = U.uid AND P.productid = O.productid
WHERE O.uid IS NULL

sqlfiddle 此查询返回与之前的查询相同的结果,但不使用 IN 子句,因此可能会更快。

SELECT P.productid,P.productname,P.productdescription,
       SUM(CASE WHEN gender = 'Male' THEN 1
           ELSE 0
           END) as Male,
       SUM(CASE WHEN gender = 'Female' THEN 1
           ELSE 0
           END) as Female,
       COUNT(1) as Total
FROM Users U INNER JOIN Products P
LEFT JOIN Orders O ON O.uid = U.uid AND P.productid = O.productid
WHERE O.uid IS NULL
GROUP BY P.productid,P.productname,P.productdescription

关于mysql - 获取未下订单产品的男性用户总数和女性用户总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36524728/

相关文章:

php - 在MySql中存储每小时更新的数据

MySQL 基于日期列按周分组?

c# - SQLDataReader 如何处理非常大的查询?

SQL IN 和 AND 子句输出

sql - 使用 SQL Server 聚合 bool 表

mysql - 获取每位老师成绩最低的学生

mysql - 如何对 MySQL 查询的输出进行分组,我想按 ID 求和EquipCost 输出。即我希望 accountCost 由他们的帐户求和

mysql 查询返回两个结果而不是一个

sql - 选择今天的日期作为默认日期

sql - 如何获取每个月的第一行数据(postgres)