mariadb 用于查找连接表的最后一行的SQL窗口函数

jckbn6z7  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(132)

我在MariaDB 10.3服务器中有如下表。

  • 人员(标识、姓名)
  • 捐赠(标识,人员标识,金额,提供日期,市场活动)

从个人到捐赠者之间存在一对多的关系。假设“活动”描述了捐赠的目的,但我们只使用活动名称A和B。只有这两个。
我需要一个为每个人返回一行的查询,其中的列是从他们最近一次向A捐款到他们最近一次向B捐款的所有列。
例如:(此代码是错误的,但可能比我的文字更好地传达信息!)

WITH lastDonationA AS (
  SELECT *
  FROM donation
  WHERE campaign = 'A' AND  /* IS LAST ROW */
  GROUP BY person_id
)
WITH lastDonationB AS (
  SELECT *
  FROM donation
  WHERE campaign = 'B' AND /* IS LAST ROW */
  GROUP BY person_id
)
SELECT person.name, lastDonationA.*, lastDonationB.*
FROM person
LEFT JOIN lastDonationA ON lastDonationA.person_id = person.id
LEFT JOIN lastDonationB ON lastDonationB.person_id = person.id
;

我有一种预感,窗口函数将是好的,但我不能完全理解它!

s2j5cfk0

s2j5cfk01#

我想我被FIRST_VALUE窗口函数搞糊涂了,它听起来很完美,但不适合这个用例。

WITH orderedDonationsForA AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY date_given DESC) rn
  FROM donation
  WHERE campaign = 'A'
),
orderedDonationsForB AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY date_given DESC) rn
  FROM donation
  WHERE campaign = 'B'
)
SELECT person.*, lastAdonation.*, lastBdonation.*
FROM person
LEFT JOIN orderedDonationsForA lastAdonation
  ON lastAdonation.person_id AND lastAdonation.rn = 1
LEFT JOIN orderedDonationsForB lastBdonation
  ON lastAdonation.person_id AND lastBdonation.rn = 1

这是通过对每个人内部的行从最近到最早进行编号来实现的,然后连接通过ON子句挑选出第一个行。

相关问题