简体   繁体   English

同一个表上的 2 个不同查询,计数和分组依据

[英]2 different queries on same table with count and group by

I have a table entries with the following columns: id, email, sku, payment, created_at我有一个包含以下列的表entries :id、email、sku、payment、created_at

I need to write a few queries to get some analytics on the entries.我需要编写一些查询来对条目进行一些分析。 The two queries I'd like to combine into one are:我想合并为一个的两个查询是:

SELECT sku, count(email) AS total_current FROM entries WHERE payment IS NOT NULL AND created_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK) GROUP BY sku ORDER BY sku ASC SELECT sku, count(email) AS total_current FROM entries WHERE payment IS NOT NULL AND created_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK) GROUP BY sku ORDER BY sku ASC

And

SELECT sku, count(email) AS total_previous FROM entries WHERE payment IS NOT NULL AND created_at < DATE_SUB(NOW(), INTERVAL 1 WEEK) AND created_at >= DATE_SUB(NOW(), INTERVAL 2 WEEK) GROUP BY sku ORDER BY sku ASC SELECT sku, count(email) AS total_previous FROM entries WHERE payment IS NOT NULL AND created_at < DATE_SUB(NOW(), INTERVAL 1 WEEK) AND created_at >= DATE_SUB(NOW(), INTERVAL 2 WEEK) GROUP BY sku ORDER BY sku ASC

The goal here is to have 1 set of results with 3 columns that show the number of records for each sku for one date range in the 2nd column, and the number of records for the same sku in the 3rd column.这里的目标是让 1 组结果包含 3 列,在第二列中显示一个日期范围内每个 sku 的记录数,在第三列中显示相同 sku 的记录数。

  1. Sku (where everything is grouped) Sku(所有内容都分组的地方)

  2. total_current (count # of records that fall within the first query's date range for each separate sku) total_current(计算每个单独 sku 的第一个查询日期范围内的记录数)

  3. total_previous (count # of records that fall within the second query's date range for each separate sku) total_previous(计算每个单独 sku 的第二个查询日期范围内的记录数)

And the results should be sorted by sku ascending.并且结果应按sku升序排序。

I have tried a lot of different things using UNION, and JOIN, etc., but with no luck so far.我使用 UNION 和 JOIN 等尝试了很多不同的东西,但到目前为止都没有运气。

You can use conditional aggregation to combine the two queries:您可以使用条件聚合来组合两个查询:

SELECT sku, 
       count(CASE 
                WHEN created_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK)  THEN email
             END) AS total_current,
       count(CASE 
                WHEN  created_at < DATE_SUB(NOW(), INTERVAL 1 WEEK) AND
                     created_at >= DATE_SUB(NOW(), INTERVAL 2 WEEK)  THEN email
             END) AS total_previous
FROM entries 
WHERE payment IS NOT NULL AND 
      created_at >= DATE_SUB(NOW(), INTERVAL 2 WEEK)
GROUP BY sku 
ORDER BY sku ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM