您好我有这样的SQL查询:
SELECT
COUNT(*) AS total,
COUNT(referrer) AS referrer,
DATE_FORMAT(created_at, "%Y") AS YEAR,
DATE_FORMAT(created_at, "%m") AS MONTH,
DATE_FORMAT(created_at, "%d") AS DAY
FROM
users
GROUP BY
EXTRACT(DAY FROM created_at),
EXTRACT(MONTH FROM created_at),
EXTRACT(YEAR FROM created_at)
ORDER BY
created_at ASC
这为我提供了按日(月和年)排序的总表。我需要的是添加一个子查询来显示一个具有条件的count()。类似的东西:
(SELECT count(*) FROM users WHERE result = '1') as winners
问题显然在于主查询的分组,因为我得到相同的结果而没有为每一行分组子查询。
执行此类查询的正确方法是什么?
答案 0 :(得分:1)
怎么样
SELECT
COUNT(*) AS total,
COUNT(referrer) AS referrer,
SUM(case when result = '1' then 1 else 0 end) as winners
DATE_FORMAT(created_at, "%Y") AS YEAR,
DATE_FORMAT(created_at, "%m") AS MONTH,
DATE_FORMAT(created_at, "%d") AS DAY
FROM
users
GROUP BY
EXTRACT(DAY FROM created_at),
EXTRACT(MONTH FROM created_at),
EXTRACT(YEAR FROM created_at)
ORDER BY
created_at ASC;
假设created_at
是一个时间戳,我们可以重新编写您的查询,只需要一个字段进行分组,如下所示:
SELECT
COUNT(*) AS total,
COUNT(referrer) AS referrer,
SUM(case when result = '1' then 1 else 0 end) as winners
DATE_FORMAT(created_at, "%Y") AS YEAR,
DATE_FORMAT(created_at, "%m") AS MONTH,
DATE_FORMAT(created_at, "%d") AS DAY
FROM
users
GROUP BY date(created_at)
ORDER BY
created_at ASC;
请注意我手边没有mysql
。
答案 1 :(得分:1)
您可以使用UNION
SELECT
COUNT(*) AS total,
COUNT(referrer) AS referrer,
DATE_FORMAT(created_at, "%Y") AS YEAR,
DATE_FORMAT(created_at, "%m") AS MONTH,
DATE_FORMAT(created_at, "%d") AS DAY
FROM
users
GROUP BY
EXTRACT(DAY FROM created_at),
EXTRACT(MONTH FROM created_at),
EXTRACT(YEAR FROM created_at)
ORDER BY
created_at ASC
UNION
SELECT count(*) FROM users
GROUP BY
EXTRACT(DAY FROM created_at),
EXTRACT(MONTH FROM created_at),
EXTRACT(YEAR FROM created_at)
HAVING result = '1'