查询中的列总和

时间:2017-02-06 09:23:55

标签: mysql sql

我有这个查询

`SELECT order_customFields.order_customFields_delivery_method,

    sum(case `order`.order_status when 'paid' then 1 else 0 end) paid,
    sum(case `order`.order_status when 'later' then 1 else 0 end) later
FROM order_customFields 
  INNER JOIN `order` ON order_customFields.order_id = `order`.order_id

where `order`.order_createdAt >= date_sub(date_sub(curdate(), interval day(curdate()) - 1 day), interval 1 month) 
and `order`.order_createdAt < date_sub(curdate(), interval day(curdate()) - 1 day)
AND order_customFields.order_customFields_delivery_method in('a','b','c','d','e')
GROUP BY    
   order_customFields.order_customFields_delivery_method`

如何在此查询中获得列paidlater的总和?像这样example

4 个答案:

答案 0 :(得分:3)

如果要查找两列的总和,请使用IN

sum(case when `order`.order_status in ('paid', 'later') then 1 end)

答案 1 :(得分:1)

你可以放+,你将得到总数

sum(case `order`.order_status when 'paid' then 1 else 0 end)+
    sum(case `order`.order_status when 'later' then 1 else 0 end) total

答案 2 :(得分:1)

您可以使用加法运算符进行加法 - &#34; +&#34;

SELECT order_customFields.order_customFields_delivery_method,

    sum(sum(case `order`.order_status when 'paid' then 1 else 0 end) +
    sum(case `order`.order_status when 'later' then 1 else 0 end)) total
FROM order_customFields 
  INNER JOIN `order` ON order_customFields.order_id = `order`.order_id

where `order`.order_createdAt >= date_sub(date_sub(curdate(), interval day(curdate()) - 1 day), interval 1 month) 
and `order`.order_createdAt < date_sub(curdate(), interval day(curdate()) - 1 day)
AND order_customFields.order_customFields_delivery_method in('a','b','c','d','e')
GROUP BY    
   order_customFields.order_customFields_delivery_method

请参阅MYSQL文档以获取更多详细信息 - Arithmetic Operations - MYSQL

答案 3 :(得分:1)

试试这个

SELECT order_customFields.order_customFields_delivery_method,
sum(case `order`.order_status when 'paid' then 1 else 0 end)+
sum(case `order`.order_status when 'later' then 1 else 0 end)
FROM order_customFields 
INNER JOIN `order` ON order_customFields.order_id = `order`.order_id
where `order`.order_createdAt >= date_sub(date_sub(curdate(), interval 
day(curdate()) - 1 day), interval 1 month) 
and `order`.order_createdAt < date_sub(curdate(), interval day(curdate()) - 1 day)
AND order_customFields.order_customFields_delivery_method in('a','b','c','d','e')
GROUP BY    
order_customFields.order_customFields_delivery_method`