SQL查询:计数器和百分比

时间:2011-10-27 10:43:28

标签: sql ms-access

我有一张表存储所有产品订单。 我需要计算按经销商和月份分组的已结算和失败订单的数量,以及失败订单的百分比和额外信息的请求数量。

表格如下:

order id | status | dealer_id | month | area | requests
    1      Closed       1         4       N   "extra info"
    2      failed       2         4       S   "extra info"
    3      failed       2         4       S       0

样本结果集将是:

    dealer |  month  |  Total |  % Failed |  Requested info 
       1        4         1         0              0
       2        4         2        100 %           1

1 个答案:

答案 0 :(得分:0)

这个查询似乎有效,在Linux上使用SQLite:

    SELECT a.dealer_id AS dealer, a.month, COUNT(*) AS total,
            (SELECT COUNT(*)
            FROM orders b
            WHERE b.dealer_id=a.dealer_id
            AND b.month=a.month
            AND b.status!='Closed')*100/COUNT(*) AS failed
    FROM orders a
    GROUP BY a.dealer_id, a.month;

请检查这是否适合您的要求并提供反馈!