如何使用日期打破总和的结果呢?

时间:2017-10-12 15:02:13

标签: sql postgresql

我有一个名为推介的表格,其中包含以下列:

id | campaign | module | team | referred | referred_by | createdAt

为了获得排名,我尝试将referred_by的唯一出现次数相加,然后对它们进行排名。这似乎达到了一定程度,然而,当有一个平局我发现等级会重复。我需要的是还要考虑推荐发生的日期(最早的日期应排在第一位,打破平局)。

以下是我原始查询的示例:

SELECT referral.referred_by AS id,
          SUM(1) AS referral_count,
          RANK() OVER (ORDER BY referral.count DESC) AS current_position

  FROM referral

  WHERE referral.campaign = 106 AND
        referral.team = 36 AND
        DATE_PART('month', referral."createdAt") = DATE_PART('month', NOW()) AND
        DATE_PART('year', referral."createdAt") = DATE_PART('year', NOW())

  GROUP BY referral.referred_by
  ORDER BY referral_count DESC LIMIT 20

SELECT date_trunc(r."createdAt"), r.referred_by, count(*)

哪个收益:

id  |   referral_count  |   current_position

894 |   3               |   1

895 |   2               |   2

896 |   2               |   2

897 |   1               |   4

理想情况应为:

id  |   referral_count  |   current_position

894 |   3               |   1

895 |   2               |   2

896 |   2               |   3

897 |   1               |   4

谢谢!

2 个答案:

答案 0 :(得分:1)

您应该可以将created_at添加到您的订购

SELECT referral.referred_by AS id,
          SUM(1) AS referral_count,
          RANK() OVER (ORDER BY referral.count DESC,referral."createdAt") AS current_position

  FROM referral

  WHERE referral.campaign = 106 AND
        referral.team = 36 AND
        DATE_PART('month', referral."createdAt") = DATE_PART('month', NOW()) AND
        DATE_PART('year', referral."createdAt") = DATE_PART('year', NOW())

  GROUP BY referral.referred_by
  ORDER BY referral_count DESC LIMIT 20

SELECT date_trunc(r."createdAt"), r.referred_by, count(*)

答案 1 :(得分:0)

使用CTE,你可以有一个明确的中间步骤

class Case(BaseModel):
    ....
    user = models.ForeignKey(User,related_name='user' )
    assigned_user = models.ForeignKey(User,related_name='assigned_user')