计算部分值或条件值

时间:2012-08-10 14:40:11

标签: mysql count subquery distinct

我希望有人可以在这里提供帮助和一些建议。我试图获得一个相当复杂的结果,并且不确定我是否可以将其作为一个查询来执行子查询,联合或简单的单独查询以便在事后合并到excel中。

我正在使用我的前任的遗留数据库,其中包含以下表格: 业务(使用的列:id,扇区,州) 表单(使用的列:已提交(Y / N),id,business_id) 库存(使用的列:In_stock(Y / N),id,form_id)

我正试图得到一个看起来像这样的最终结果:

| SubmittedForms | Unsubmitted Forms | Sector | State |
|-----------------------------------------------------|
|       10       |         5         |  Agr   |  UT   |
|       0        |         7         |  Chem  |  MT   |
|       2        |         1         |  Bio   |  OK   |
|       13       |         0         |  Chem  |  NM   |

我得到的主要问题是,虽然提交的表单不需要任何进一步的参数并且是一个简单的计数,但未提交的表单依赖于Inventory.in_stock ='Y'。这是我对提交表单的查询:

SELECT COUNT(Forms.id) AS Submitted, Business.sector, Business.state
FROM Forms
JOIN Business ON Forms.business_id=Business.id
WHERE Forms.submitted='Y'
GROUP BY Business.state, Business.sector

不幸的是,我似乎无法正确计算未提交的表单编号。它只返回该扇区的in_stock为Y的行总数。

如果更容易为Submitted和Unsubmitted运行单独的查询,这对于最终结果很好,但是我需要一些帮助来获取正确的未提交表单计数,其中in_stock标记为Y.此外,我尝试使用COUNT DISTINCT但是花了太长时间,10分钟后还在运行。我可以在单个查询选项中设想的另一个复杂因素是Submitted或Unsubmitted表单中0 / null值的可能性

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

一个选项:

SELECT COUNT(CASE WHEN Forms.submitted = 'Y' THEN 1 END) SubmittedForms,
       COUNT
        ( CASE WHEN Forms.submitted = 'N'
                AND EXISTS ( SELECT 1
                               FROM Inventory
                              WHERE form_id = Forms.id
                                AND in_stock = 'Y'
                           )
               THEN 1
           END
        ) UnsubmittedForms,
       Business.sector Sector,
       Business.state State
  FROM Forms
 RIGHT
 OUTER
  JOIN Business 
    ON Forms.business_id = Business.id
 GROUP
    BY Business.sector,
       Business.state
;

另一种可能表现更佳的选择:

SELECT COUNT(CASE WHEN Forms.submitted = 'Y' THEN 1 END) SubmittedForms,
       COUNT(CASE WHEN Forms.submitted = 'N' THEN 1 END) UnsubmittedForms,
       Business.sector Sector,
       Business.state State
  FROM ( SELECT *
           FROM Forms
          WHERE submitted = 'Y'
             OR id IN ( SELECT DISTINCT form_id
                          FROM Inventory
                           AND in_stock = 'Y'
                      )
       ) Forms
 RIGHT
 OUTER
  JOIN Business 
    ON Forms.business_id = Business.id
 GROUP
    BY Business.sector,
       Business.state
;