gpt4 book ai didi

sql - 我需要帮助编写复杂的 SQL 语句

转载 作者:行者123 更新时间:2023-12-04 13:42:15 24 4
gpt4 key购买 nike

**PLEDGE TABLE**
PledgeID PledgeAmount PledgeDate DonorID
---------|-------------|------------|---------
1 | 100 | 04/03/2014 | 1
2 | 200 | 04/03/2013 | 1
3 | 100 | 04/03/2009 | 2
4 | 2,000 | 01/01/2012 | 3
5 | 1,000 | 01/01/2012 | 4
6 | 500 | 01/01/2009 | 4

**DONOR TABLE**
DonorID Name SpouseID
---------|-------------|-------------
1 | John Smith | 3
2 | Jack Johnson| NULL
3 | Jane Smith | 1
4 | John Adams | NULL

我有 2 个表:一个 Donor 表和一个 Pledge 表。我想运行一个查询,该查询仅返回前几年而非今年提供的每对夫妇的一条记录(特别是最大或最近的 promise 日期)。这对我们的非营利组织非常重要,因为最适合向其募捐的人是过去的捐助者。但是,在我们的数据库中,有时妻子会捐助,而下一年丈夫会捐助,所以它在两者之下。有些还没有结婚。

所以在上表中,只有John Adam在2012年的质押和Jack Johnson在2009年的质押应该归还。简·史密斯 (Jane Smith) 自 2012 年以来就没有捐过钱,但她不应退还,因为她的丈夫今年捐过钱。

最佳答案

我还没有测试过,但像下面这样的东西应该可以工作:

(select dt.donor_id, null spouse_id, max(pledge_date) maxDate
from donor_table dt inner join pledge_table pt on (pt.donor_id = dt.donor_id)
where dt.spouse_id is null group by dt.donor_id
having max(pledge_date) is not null and max(pledge_date) < '2014-01-01'
union distinct
(select dt.donor_id, dt.spouse_id
,case when max(pt1.pledge_date) is null then max(pt2.pledge_date) else when
max(pt2.pledge_date is null then max(pt1.pledge_date) else
greatest(max(pt1.pledge_date), max(pt2.pledge_date)) end maxDate
from donor_table dt left outer join pledge_table pt1 on (pt1.donor_id = dt.donor_id)
left outer join pledge_table pt2 on (pt2.donor_id = dt.spouse_id)
where dt.donor_id < dt.spouse_id
group by dt.donor_id, dt.spouse_id
having case when max(pt1.pledge_date) is null then max(pt2.pledge_date) else when
max(pt2.pledge_date is null then max(pt1.pledge_date) else
greatest(max(pt1.pledge_date), max(pt2.pledge_date)) end is not null
and case when max(pt1.pledge_date) is null then max(pt2.pledge_date) else when
max(pt2.pledge_date is null then max(pt1.pledge_date) else
greatest(max(pt1.pledge_date), max(pt2.pledge_date)) end < '2014-01-01'
)

第一个查询返回没有配偶的捐赠者的值。第二个返回配对,我使用 dt.donor_id < dt.spouse_id 来避免重复。同样在该查询中,我在两种情况下都进行了左外连接,否则您可能会错过结果。可能会有轻微的语法错误,但类似的东西应该可以工作。我还输入了日期“2014-01-01”,这样它会返回您在 2013 年或之前但不是在 2014 年捐赠的捐助者

我正在使用 mysql 中最强大的功能。

看起来很复杂,因为我在重复

 case when max(pt1.pledge_date) is null then max(pt2.pledge_date) else when   
max(pt2.pledge_date is null then pt1.pledge_date else
greatest(max(pt1.pledge_date), max(pt2.pledge_date)) end

为了简化,您可以为此定义一个函数。它基本上是在一个或多个值为空的情况下计算配偶和捐赠者的最大值(value)

关于sql - 我需要帮助编写复杂的 SQL 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27536816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com