动态使用不同的单元格值作为查询

时间:2017-04-26 18:57:44

标签: sql amazon-redshift

如何编写查询,我正在考虑 WINDOW 函数,使用两个参数(例如用户ID和日期)作为动态输入另一个问题?

例如,如果您有以下三(3)行数据。我们称之为 TABLE1

| USER ID | DATE       |
|---------|------------|
| 1       | 2017-04-26 |
| 2       | 2017-04-25 |
| 3       | 2017-04-25 |

如何编写查询以获取每个用户ID的 Total Revenue 等数据点,但收集收入 <或>之后 / strong>与每个用户ID关联的每个日期值?

要构建此示例,如果我们有以下单独的表。我们将对此 TABLE2

进行评分
| USER ID | REVENUE | REVENUE COLLECTION DATE |
|---------|---------|-------------------------|
| 1       | $1      | 2017-04-26              |
| 1       | $1      | 2017-04-20              |
| 2       | $1      | 2017-04-25              |
| 2       | $1      | 2017-04-26              |
| 3       | $1      | 2017-04-01              |

我追逐的输出只会 SUM 收入 TABLE2 revenue_collection_date &gt; = TABLE1 日期

| USER ID | TOTAL REVENUE |
|---------|---------------|
| 1       | $1            |
| 2       | $2            |
| 3       | $0            |

同样,用户ID和总收入的输出仅 选择收款值,其中收集日期上或之后的第一个表格

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题......

SQL Server:

SELECT u.UserID, COALESCE(t.TotalRevenue, 0) AS TotalRevenue
FROM Users AS u
OUTER APPLY
(
    SELECT SUM(r.Revenue) AS TotalRevenue
    FROM Revenue AS r
    WHERE r.UserID = u.UserID
        AND r.CollectionDate >= u.Date
) AS t

POSTGRES:

SELECT u.UserID, COALESCE(t.TotalRevenue, 0) AS TotalRevenue
FROM Users AS u
LEFT JOIN LATERAL
(
    SELECT SUM(r.Revenue) AS TotalRevenue
    FROM Revenue AS r
    WHERE r.UserID = u.UserID
        AND r.CollectionDate >= u.Date
) AS t ON TRUE;

针对您的样本数据:

CREATE TABLE Users
(
    UserID INT,
    Date DATE
);

CREATE TABLE Revenue
(
    UserID INT,
    Revenue DECIMAL(18,2),
    CollectionDate DATE
);

INSERT INTO Users
VALUES
(1, '20170426'),
(2, '20170425'),
(3, '20170425');

INSERT INTO Revenue
VALUES
(1, 1, '20170426'),
(1, 1, '20170420'),
(2, 1, '20170425'),
(2, 1, '20170426'),
(3, 1, '20170401');

返回您的预期结果

这里是PostgreSQL Fiddle