【问题标题】:Smart counting of id in join mysql智能计算加入mysql中的id
【发布时间】:2012-11-07 21:00:54
【问题描述】:

运行此查询时,COUNT 函数不会按“check_if_new_customer”标志进行过滤。我在这篇文章中读到:http://dev.mysql.com/tech-resources/articles/wizard/page4.html 在某些情况下可以使用 SUM 而不是 COUNT 以获得更准确的结果,但是当我尝试这样做时,我得到了一些非常不同的东西,它似乎显示出大量的数字翻倍。我认为这可能是因为我正在对 id 字段中的 UUID 求和,而不是在该点进行计数。关于我可以放什么来计算所有现有客户和新客户的任何建议?

SELECT
  YEAR(so.date_entered),
  so.technical_address_country,
  so.technical_address_state,
  COUNT(so.id) as all_sales,
  COUNT(mf.id) as all_jobs,
  SUM(so.total_value) as all_value,
    COUNT(IF(so.check_if_new_customer=1,so.id,0)) as sales_order_new,
  SUM(IF(so.check_if_new_customer = 1,so.total_value,0)) as total_value_new,
    COUNT(IF(so.check_if_new_customer=1,mf.id,0)) as jobs_new,
    COUNT(IF(so.check_if_new_customer=0,so.id,0)) as sales_order_existing,
  SUM(IF(so.check_if_new_customer = 0,so.total_value,0)) as total_value_existing,
    COUNT(IF(so.check_if_new_customer=0,mf.id,0)) as jobs_existing,
    SUM(IF(so.check_if_new_customer=0,mf.id,0)) as jobs_existing_t
FROM 
  sugarcrm2.so_order so 
LEFT JOIN 
  sugarcrm2.mf_job mf on so.id = mf.sales_order_id 
WHERE 
  so.date_entered > "2011-10-30" AND 
    so.technical_address_country IS NOT NULL AND  
  so.technical_address_state IS NOT NULL AND 
  so.deleted = 0 AND 
  so.has_been_promoted = 1 
GROUP BY 
    YEAR(so.date_entered),
  so.technical_address_country, 
  so.technical_address_state
ORDER BY 
  so.technical_address_country, so.technical_address_state 

【问题讨论】:

    标签: mysql if-statement count sum case


    【解决方案1】:

    如果您想像COUNT() 一样使用SUM(),您需要将1 或0 传递给它,这样所有1 的总和都会达到您想要的计数。所以在你的例子中,如果你想要所有新工作的总和,你会这样做:

    SUM(IF(so.check_if_new_customer=1,1,0)) as jobs_new

    或者如果是这样。check_if_new_customer 总是返回 1 或 0,您也可以这样做:

    SUM(so.check_if_new_customer) as jobs_new

    【讨论】:

      【解决方案2】:

      COUNT() 返回其参数(如果指定)不为NULL 的记录数。由于在这种情况下它的参数是 IF() 表达式的结果(如果为真,则计算为某个列的值,如果为假,则计算为 0),因此几乎每条记录都将被计算在内,而与测试条件无关。

      SUM(),顾名思义,将其参数的值相加。在这种情况下,只要测试条件为真,它就会对引用列的值求和。

      显然你所追求的也不是,尽管你的问题对于你到底想要什么是相当模棱两可的。猜测一下,你可能想要这样的东西:

      SUM(so.check_if_new_customer)
      

      【讨论】:

        【解决方案3】:

        每次连接表的 id 字段不为空时,我想求和 +1。

        SUM(IF(so.check_if_new_customer=0 AND mf.id IS NOT NULL,1,0)) as jobs_existing

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-03
          • 1970-01-01
          • 2019-07-28
          • 1970-01-01
          相关资源
          最近更新 更多