gpt4 book ai didi

sql - 查找该结果的对应列的最小值和值

转载 作者:行者123 更新时间:2023-12-01 05:14:49 25 4
gpt4 key购买 nike

我的 SQL Server 数据库中有一个用户数据表,我正在尝试汇总数据。基本上,我需要一些最小值、最大值和总和值并按某些列分组
这是一个示例表:

Member ID | Name  | DateJoined | DateQuit  | PointsEarned | Address
00001 | Leyth | 1/1/2013 | 9/30/2013 | 57 | 123 FirstAddress Way
00002 | James | 2/1/2013 | 7/21/2013 | 34 | 4 street road
00001 | Leyth | 2/1/2013 | 10/15/2013| 32 | 456 LastAddress Way
00003 | Eric | 2/23/2013 | 4/14/2013 | 15 | 5 street road
我希望汇总表显示如下结果:
Member ID | Name  | DateJoined | DateQuit  | PointsEarned | Address
00001 | Leyth | 1/1/2013 | 10/15/2013 | 89 | 123 FirstAddress Way
00002 | James | 2/1/2013 | 7/21/2013 | 34 | 4 street road
00003 | Eric | 2/23/2013 | 4/14/2013 | 15 | 5 street road
到目前为止,这是我的查询:
Select MemberID, Name, Min(DateJoined), Max(DateQuit), SUM(PointsEarned), Min(Address)
From Table
Group By MemberID
Min(Address) 这次起作用了,它检索到最早的 DateJoined 对应的地址。但是,如果我们交换原始表中的两个地址,我们将检索与 1/1/2013 加入日期不对应的“123 FirstAddress Way”。

最佳答案

对于几乎所有内容,您都可以使用简单的 groupby,但是由于您需要“与最小日期加入的行相同的地址”有点棘手,您可以通过多种方式解决它,一个是每次都搜索地址的子查询

SELECT
X.*,
(select Address
from #tmp t2
where t2.MemberID = X.memberID and
t2.DateJoined = (select MIN(DateJoined)
from #tmp t3
where t3.memberID = X.MemberID))
FROM
(select MemberID,
Name,
MIN(DateJoined) as DateJoined,
MAX(DateQuit) as DateQuit,
SUM(PointsEarned) as PointEarned
from #tmp t1
group by MemberID,Name
) AS X

`
或者其他是带有 Join 的子查询
SELECT
X.*,
J.Address
FROM
(select
MemberID,
Name,
MIN(DateJoined) as DateJoined,
MAX(DateQuit) as DateQuit,
SUM(PointsEarned) as PointEarned
from #tmp t1
group by MemberID,Name
) AS X
JOIN #tmp J ON J.MemberID = X.MemberID AND J.DateJoined = X.DateJoined

关于sql - 查找该结果的对应列的最小值和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21685669/

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