SQL。附加表中的过去实例数

时间:2018-11-27 09:14:20

标签: sql mysqli mysql-workbench

这是我想要的输出:

CampaignName    CampaignDate    UsersTargeted   CountOfUsersBought   
    2x1          2018-11-24           1 (UserId 2)     1 (UserId 2)
    3x2          2018-11-25           2 (Both)         1 (UserId 1)

“ CountOfUsersBought”我希望它成为所有目标用户之一。

从中获取数据以填充先前输出的表(每日更新)具有以下结构:

UserId     EligibleForOffer(0,1)    BoughtToday(0,1)     Timestamp
   1                0                   0               2018-11-24
   1                1                   0               2018-11-25
   1                1                   1               2018-11-26
   1                0                   0               2018-11-27
   2                1                   0               2018-11-24
   2                1                   1               2018-11-25
   2                1                   0               2018-11-26
   2                0                   1               2018-11-27

我想在变量'CountOfUsersBought'中存储实际购买的所有用户的数量,不仅是今天,而且是所有时间。您将如何进行此查询?

请注意,用户也没有报价购买,因此我只想计算过去的实例,其中EligibleForOffer = 1 AND BoughtToday = 1 AND Timestamp <='CampaignDate'+ 1天

我知道在另一张桌子上针对每个广告系列定位的用户,我只想保留“今天”接受了提供给他们的要约的用户数量。

1 个答案:

答案 0 :(得分:1)

您可以GROUP BY日期并使用SUM查找有资格参加广告活动的用户数量,并使用CASE来确定您的条件。奖励是MIN,用于查找与该条件相关的特定用户仅仅是一个用户匹配。

CREATE TABLE Campain
(
     UserId INT
    ,EligibleForOffer   BIT
    ,BoughtToday        BIT
    ,Timestamp          DATE
)

INSERT INTO Campain
VALUES
 (1,0,0,'2018-11-24')
,(1,1,0,'2018-11-25')
,(1,1,1,'2018-11-26')
,(1,0,0,'2018-11-27')
,(2,1,0,'2018-11-24')
,(2,1,1,'2018-11-25')
,(2,1,0,'2018-11-26')
,(2,0,1,'2018-11-27')

SELECT   Timestamp
        ,SUM(CAST(EligibleForOffer AS INT)) NumberOfUsersTargeted
        ,CASE WHEN SUM(CAST(EligibleForOffer AS INT))=1 THEN 'UserId-'+CAST(MIN(UserId) AS VARCHAR) WHEN SUM(CAST(EligibleForOffer AS INT))>1 THEN 'Multiple Users(Both)' ELSE 'No Target' END UsersTargetedDetail
        ,SUM(CAST(BoughtToday AS INT)) NumberOfBought
        ,CASE WHEN SUM(CAST(BoughtToday AS INT))=1 THEN 'UserId-'+CAST(MIN(UserId) AS VARCHAR) WHEN SUM(CAST(BoughtToday AS INT))>1 THEN 'Multiple Users(Both)' ELSE 'No Buying' END BoughtDetail
FROM Campain
GROUP BY Timestamp