0

我想在查询中做数学运算,想知道用 PHP 还是 MYSQL 更好。另外,如果我选择 MYSQL,任何人都可以帮助我进行查询。

到目前为止我有

  SELECT COUNT(*) as total, booker, appdate,
  SUM(CASE WHEN status='DNS' THEN 1 ELSE 0 END) book,
  SUM(CASE WHEN status!='DNS' THEN 1 ELSE 0 END) tot
  FROM appts WHERE WEEK(app_date)= WEEK(CURDATE()) GROUP BY booker

我想从此查询中获得更多统计信息。我想做book / (book+tot) 但显然只有当book!=0or tot!=0,因为显然我不想将任何东西除以零。

有没有办法在 MYSQL 查询中做到这一点?

我希望我的输出是......

       book  | 14
       tot   | 25
       hold  | 35%

我还想按从最高到最低的持有百分比排序。这可能吗????

4

2 回答 2

3

您可以使用子查询来实现您的要求,如下所示:

SELECT *, IF(book + tot, 100*book/(book + tot), NULL) AS hold
FROM (
  SELECT COUNT(*) as total, booker, appdate,
  SUM(status='DNS') book, SUM(status!='DNS') tot
  FROM appts WHERE WEEK(app_date)= WEEK(CURDATE()) GROUP BY booker
) AS subquery
ORDER BY hold DESC

请注意,在几个地方我使用了 MySQL 使用数字作为逻辑值的事实。所以你可以总结没有 的条件,你可以写一个没有检查CASE的公式。IF<> 0

于 2013-10-17T21:31:52.963 回答
1

天真的方法:

SELECT
    COUNT(*) as total,
    SUM(CASE WHEN status='DNS' THEN 1 ELSE 0 END) book,
    SUM(CASE WHEN status!='DNS' THEN 1 ELSE 0 END) tot,

    IF(  ( SUM(CASE WHEN status!='DNS' THEN 1 ELSE 0 END) +
           SUM(CASE WHEN status='DNS' THEN 1 ELSE 0 END) ) = 0,
          0,
          SUM(CASE WHEN status='DNS' THEN 1 ELSE 0 END) /
           ( SUM(CASE WHEN status!='DNS' THEN 1 ELSE 0 END) +
             SUM(CASE WHEN status='DNS' THEN 1 ELSE 0 END) )
    ) AS hold
FROM appts
WHERE WEEK(app_date) = WEEK(CURDATE()) GROUP BY booker
ORDER BY hold;

或者为了不重复您的别名,请使用子查询:

SELECT *, IF (book + tot = 0, 0, book / (book + tot) * 100)
FROM (
    SELECT
        COUNT(*) as total,
        SUM(CASE WHEN status='DNS' THEN 1 ELSE 0 END) book,
        SUM(CASE WHEN status!='DNS' THEN 1 ELSE 0 END) tot,
    FROM appts
    WHERE WEEK(app_date) = WEEK(CURDATE()) GROUP BY booker
) AS subq
ORDER BY hold;

或者,更聪明:) ( book+ tot= total)

SELECT *, IF (total = 0, 0, book / total * 100)
FROM (
    SELECT
        COUNT(*) as total,
        SUM(CASE WHEN status='DNS' THEN 1 ELSE 0 END) book,
        SUM(CASE WHEN status!='DNS' THEN 1 ELSE 0 END) tot,
    FROM appts
    WHERE WEEK(app_date) = WEEK(CURDATE()) GROUP BY booker
) AS subq
ORDER BY hold;

而且,只是为了好玩,最紧凑的形式:

SELECT *, COALESCE(book / total * 100, 0) AS hold -- a division by 0 returns NULL
FROM (
    SELECT
        COUNT(*) total,
        SUM(status='DNS') book, -- boolean "true" is internally integer "1"
        SUM(status!='DNS') tot,
    FROM appts
    WHERE WEEK(app_date) = WEEK(CURDATE()) GROUP BY booker
) AS subq
ORDER BY hold;
于 2013-10-17T21:39:04.157 回答