SQL使用多个变量的日期和ID计算每日增量

时间:2018-07-04 23:03:02

标签: sql

我有一个具有以下结构的表:

+----------+-----+-------+----------+
| Date     | ID  | Likes | Comments |
+----------+-----+-------+----------+
| 1/1/2018 | AAA | 70    | 90       |
| 1/2/2018 | AAA | 80    | 110      |
| 1/1/2018 | BBB | 60    | 5        |
| 1/2/2018 | BBB | 90    | 6        |
+----------+-----+-------+----------+

对于每天和ID,我需要计算增量值。所需的输出应如下所示:desired output

+----------+-----+-------+----------+-------------+----------------+ 
| Date     | ID  | Likes | Comments | daily_likes | daily_comments |
+----------+-----+-------+----------+-------------+----------------+ 
| 1/1/2018 | AAA | 70    | 90       | 70          | 90             |
| 1/2/2018 | AAA | 80    | 110      | 10          | 20             |
| 1/1/2018 | BBB | 60    | 5        | 60          | 5              |
| 1/2/2018 | BBB | 90    | 6        | 30          | 1              |
+----------+-----+-------+----------+-------------+----------------+  

我已经尝试过此代码,但它会不断将Daily_likes或Daily_comments聚合在一起。

SELECT
    "date",
    "created_time",
    ("likes_count" - LAG("likes_count", 1) OVER (ORDER BY "date")) AS "daily_likes",
    ("comments_count" - LAG("comments_count", 1) OVER (ORDER BY "date")) AS "daily_comments",
    "id",
    "likes_count",
    "comments_count",
    "user_username"
FROM 
    "blablabla"
GROUP BY 
    1,
    "id",
    "likes_count",
    "comments_count",
    "user_username",
    "created_time"
ORDER BY 
    1 DESC;

1 个答案:

答案 0 :(得分:2)

您发布的表结构与查询不匹配。而且我想知道为什么您要进行分组,更不用说几乎每列和一个文字了...

一个查询,它将产生从您发布的表中发布的所需输出,如下所示:

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

SQL Fiddle

根本不需要分组。

(但是请注意,要显示每天的增加,这要求源表必须为每个用户提供每天的数据。如果有差距,则需要整天(在相应的范围)供所有用户填写。