sql - 如何按查询顺序获取一组的所有日期?

标签 sql postgresql group-by

我正在 Postgres 9.3 中对用户事件日志表编写分析查询。它有一个注册日期、一个数据字段(可以求和)和一个用户类型。我已经为这个问题构造了一些样本数据/sql,我希望能得到一些帮助来解决最后一部分。测试所需的 SQL 如下 - 它将删除/创建一个名为 facts 的表 - 所以一定要在沙箱中工作。

我按周和用户类型汇总数据 - 因此您每周都会获得每种用户类型的数据字段计数。我遇到的问题是,对于用户类型 = 'x',我得到的结果丢失了一周。因为在第 9-9-13 周没有用户类型“x”的用户数据,所以不会出现任何行(请参阅下面的示例结果)。我希望该用户类型和星期有一行。我想实现这一点,如果可能的话,使用单个 select 语句,没有临时表或维度表(这是因为我会将此 sql 传递给业务经理,并且单个自包含的 SQL select 语句有望更安全(欢迎对这种方法提出批评,但不接受任何答复。谢谢大家的帮助!

这是我得到的结果:

Sum     test_week       user_type
4   "2013-09-02"    "x"
5   "2013-09-02"    "y"
10  "2013-09-09"    "y"
2   "2013-09-16"    "x"
1   "2013-09-16"    "y"

Here's the results I want:

Sum     test_week       user_type
4   "2013-09-02"    "x"
5   "2013-09-02"    "y"
0   "2013-09-09"    "x"
10  "2013-09-09"    "y"
2   "2013-09-16"    "x"
1   "2013-09-16"    "y"

Here is the test data and SQL select statement:

drop table if exists facts;
create temp table facts (signup_date date, data integer, record_type varchar, alt varchar);
insert into facts (signup_date, data, record_type) values
('9/3/2013',1,'x'),
('9/4/2013',1,'y'),
('9/5/2013',2,'x'),
('9/6/2013',3,'y'),
('9/7/2013',1,'x'),
('9/8/2013',1,'y'),
-- note the week of 9/9 to 9/16 has no 'x' records
('9/9/2013',2,'y'),
('9/10/2013', 3, 'y'),
('9/11/2013', 4, 'y'),
('9/12/2013', 1, 'y'),
('9/17/2013', 2, 'x'),
('9/18/2013', 1, 'y');

select coalesce(data, 0), test_week, record_type
  from 
    (select sum(data) as data, record_type, to_timestamp(EXTRACT(YEAR FROM signup_date) || ' ' || EXTRACT(WEEK FROM signup_date),'IYYY IW')::date as test_week
    from facts
    group by record_type, test_week
    ) as facts
  order by test_week, record_type

最佳答案

select
    coalesce(sum(data), 0) as "Sum",
    to_char(date_trunc('week', c.signup_date), 'YYYY-MM-DD') as test_week,
    c.record_type as user_type
from
    facts f
    right join
    (
        (
            select distinct record_type
            from facts
        ) f1
        cross join
        (
            select distinct signup_date
            from facts
        ) f2
    ) c on f.record_type = c.record_type and f.signup_date = c.signup_date
group by 2, 3
order by 2, 3
;
 Sum | test_week  | user_type 
-----+------------+-----------
   4 | 2013-09-02 | x
   5 | 2013-09-02 | y
   0 | 2013-09-09 | x
  10 | 2013-09-09 | y
   2 | 2013-09-16 | x
   1 | 2013-09-16 | y

关于sql - 如何按查询顺序获取一组的所有日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21717827/

相关文章:

mysql - 按2列分组查询

PostgreSQL - 限制用户仅连接到副本(而不是主节点)

postgresql - 无法在 PostgreSQL 中创建名为 'user' 的数据库表

linq - 按匿名与分组分组按非匿名分组

php - 如何在 Codeigniter Active 记录中编写 MYSQL 查询 !=?

java - SQL转义遵循什么规则?

php - 删除行后重置 auto_increment

postgresql - 将文本转换为 Varchar

MySQL选择分组中的最大记录

python - 聚合值与 pandas 中的相应计数