根据另一列的值找到一组列的最小值?
Find the minimum value of a group of columns based on the value of another column?
这适用于 SQL 服务器。有没有办法根据另一列的值来获取一组 select 列的最小值?在此示例中,我想找到每个 Name 拥有的最小交易并将其放在 'Minimum Transaction' 列中。我无法对 'Name' 的值进行硬编码。我已经尝试过子查询,但我无法理解逻辑是如何工作的。
SELECT ID, Name, Transactions, Minimum Transaction =
(
SELECT MIN(Transactions)
FROM MyTable M
JOIN MyTable M ON N.ID = M.ID
)
FROM MyTable N
WHERE Name = 'Sarah' OR 'Sue' OR 'Joe' OR 'Tim'
预期结果
ID
Name
Transactions
Minimum Transaction
1
Sarah
2
Sarah
3
Sue
4
Sue
5
Sue
6
Joe
7
Tim
8
Tim
使用MIN(Transactions) OVER(PARTITION BY Name)
:
SELECT ID, Name, Transactions,
MIN(transactions) over (partition by Name) as "Minimum Transaction" from
MyTable
order by id;
PARTITION BY
相对于 GROUP BY
只影响 window 函数,不影响返回的行。
这适用于 SQL 服务器。有没有办法根据另一列的值来获取一组 select 列的最小值?在此示例中,我想找到每个 Name 拥有的最小交易并将其放在 'Minimum Transaction' 列中。我无法对 'Name' 的值进行硬编码。我已经尝试过子查询,但我无法理解逻辑是如何工作的。
SELECT ID, Name, Transactions, Minimum Transaction =
(
SELECT MIN(Transactions)
FROM MyTable M
JOIN MyTable M ON N.ID = M.ID
)
FROM MyTable N
WHERE Name = 'Sarah' OR 'Sue' OR 'Joe' OR 'Tim'
预期结果
ID | Name | Transactions | Minimum Transaction |
---|---|---|---|
1 | Sarah | ||
2 | Sarah | ||
3 | Sue | ||
4 | Sue | ||
5 | Sue | ||
6 | Joe | ||
7 | Tim | ||
8 | Tim |
使用MIN(Transactions) OVER(PARTITION BY Name)
:
SELECT ID, Name, Transactions,
MIN(transactions) over (partition by Name) as "Minimum Transaction" from
MyTable
order by id;
PARTITION BY
相对于 GROUP BY
只影响 window 函数,不影响返回的行。