0

狡猾的标题,我知道。

我知道我可以很容易地在 PHP 中做到这一点,但想知道是否可以使用我的 SQL 查询。

我正在制作一个条形图,显示我网站的新成员。

JAN  |  FEB  |  MAR  |  APR
-----|-------|-------|-------------
101  |  163  |  282  |  233

这是我到目前为止所做的:

SELECT DATE_FORMAT(created, '%Y') as 'year',
DATE_FORMAT(created, '%b') as 'month',
IFNULL(COUNT(user_id),0) as 'total'
FROM users
WHERE DATE_FORMAT(created, %Y) = 2013
GROUP BY DATE_FORMAT(created, '%Y%m')

但是要制作条形图,我需要知道最高计数是多少。在上面的示例中,我想返回282作为最高计数,这样我就可以计算条形的百分比。

这可能吗?如何?我在想也许我需要一个子查询,但不太确定最佳性能方法。

这是我想返回的:

JAN  |  FEB  |  MAR  |  APR  | Highest_Count
-----|-------|-------|-------|--------------
101  |  163  |  282  |  233  | 282
4

2 回答 2

1

SQL小提琴

MySQL 5.5.32 架构设置

CREATE TABLE users
    (`user_id` int, `created` date)
;

INSERT INTO users
    (`user_id`, `created`)
VALUES
    (1, '2013-01-01'),
    (2, '2013-01-03'),
    (3, '2013-01-07'),
    (4, '2013-02-01'),
    (5, '2013-02-04'),
    (6, '2013-03-04')
;

查询 1

SELECT DATE_FORMAT(u.created, '%Y') as 'year',
       DATE_FORMAT(u.created, '%b') as 'month',
       IFNULL(COUNT(u.user_id),0) as 'total',
       r2.Highest_Count,
       IFNULL(COUNT(u.user_id),0) / r2.Highest_Count as 'percentage'
FROM users u
INNER JOIN (
    SELECT r1.year, max(r1.Total) as Highest_Count
    FROM (  
        SELECT DATE_FORMAT(created, '%Y') as 'year',
        DATE_FORMAT(created, '%b') as 'month',
        IFNULL(COUNT(user_id),0) as 'total'
        FROM users
        WHERE DATE_FORMAT(created, '%Y') = 2013
        GROUP BY DATE_FORMAT(created, '%Y%m')) AS r1
    GROUP BY r1.year) AS r2 ON r2.year = DATE_FORMAT(u.created, '%Y')
WHERE DATE_FORMAT(u.created, '%Y') = 2013
GROUP BY DATE_FORMAT(u.created, '%Y%m')

结果

| YEAR | MONTH | TOTAL | HIGHEST_COUNT | PERCENTAGE |
|------|-------|-------|---------------|------------|
| 2013 |   Jan |     3 |             3 |          1 |
| 2013 |   Feb |     2 |             3 |     0.6667 |
| 2013 |   Mar |     1 |             3 |     0.3333 |
于 2013-09-07T01:45:49.537 回答
-1

您可以使用 -

SELECT MAX(`user_id`) FROM `users`

从那里你可以格式化它。

src = http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column.html

于 2013-09-06T23:44:18.710 回答