如何按 column3 从不同的 column1 和 column2 组中获取最小值和最大值?
How can I get minimum and maximum values from different column1 and column2 group by column3?
我有一个 table 存放产品的地方 [prod]
以及产品买卖的地方 [market]
以及买卖价格 [buy / sell]
。我想获得每种产品的最低购买价格和最高销售价格以及市场名称。我怎样才能在 MS SQL 中完成它?
我的 table 看起来像这样 ;
id | prod |market| buy | sell|
---+------+------+-----+-----+
1 | a | x | 25 | 26 |
2 | b | x | 15 | 16 |
3 | c | x | 17 | 19 |
4 | a | y | 24 | 25 |
5 | b | y | 14 | 17 |
6 | c | y | 19 | 24 |
7 | a | z | 23 | 24 |
8 | b | z | 17 | 18 |
9 | c | z | 18 | 22 |
这就是我想要的 table 的样子;
|prod|MarketMin|MarketMax| Min Buy |Max Sell |
+----+---------+---------+----------+---------+
| a | z | x | 23 | 26 |
| b | y | z | 14 | 24 |
| c | x | y | 17 | 24 |
您可以在子查询中使用 RANK()
来实现:
SELECT mn.prod, mn.MarketMin, sq.MarketMax, mn.MinBuy, sq.MaxSell
FROM
(
SELECT prod, market AS MarketMin, buy AS MinBuy, RANK() OVER(PARTITION BY prod ORDER BY buy ASC) as buy_rnk
from MARKETVALUES
) as mn
INNER JOIN
(
SELECT prod, MarketMax, MaxSell
FROM
(
SELECT prod, market AS MarketMax, sell AS MaxSell, RANK() OVER(PARTITION BY prod ORDER BY sell DESC) as sell_rnk
from MARKETVALUES
) as mx
WHERE sell_rnk =1
) as sq
ON mn.prod=sq.prod
WHERE buy_rnk=1
中的demo
编辑: Demo_v2
Demo_v2 有备用查询(不使用 RANK()
但使用多个 JOINS
和 sub-queries
)。 这个方法会比RANK()
.
慢
我有一个 table 存放产品的地方 [prod]
以及产品买卖的地方 [market]
以及买卖价格 [buy / sell]
。我想获得每种产品的最低购买价格和最高销售价格以及市场名称。我怎样才能在 MS SQL 中完成它?
我的 table 看起来像这样 ;
id | prod |market| buy | sell|
---+------+------+-----+-----+
1 | a | x | 25 | 26 |
2 | b | x | 15 | 16 |
3 | c | x | 17 | 19 |
4 | a | y | 24 | 25 |
5 | b | y | 14 | 17 |
6 | c | y | 19 | 24 |
7 | a | z | 23 | 24 |
8 | b | z | 17 | 18 |
9 | c | z | 18 | 22 |
这就是我想要的 table 的样子;
|prod|MarketMin|MarketMax| Min Buy |Max Sell |
+----+---------+---------+----------+---------+
| a | z | x | 23 | 26 |
| b | y | z | 14 | 24 |
| c | x | y | 17 | 24 |
您可以在子查询中使用 RANK()
来实现:
SELECT mn.prod, mn.MarketMin, sq.MarketMax, mn.MinBuy, sq.MaxSell
FROM
(
SELECT prod, market AS MarketMin, buy AS MinBuy, RANK() OVER(PARTITION BY prod ORDER BY buy ASC) as buy_rnk
from MARKETVALUES
) as mn
INNER JOIN
(
SELECT prod, MarketMax, MaxSell
FROM
(
SELECT prod, market AS MarketMax, sell AS MaxSell, RANK() OVER(PARTITION BY prod ORDER BY sell DESC) as sell_rnk
from MARKETVALUES
) as mx
WHERE sell_rnk =1
) as sq
ON mn.prod=sq.prod
WHERE buy_rnk=1
中的demo
编辑: Demo_v2
Demo_v2 有备用查询(不使用 RANK()
但使用多个 JOINS
和 sub-queries
)。 这个方法会比RANK()
.