我想从一个表中获取一行中的最大值和最小值
例如,我在表a中有以下行:
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'A', 1210885);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AA', 1211091);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AAAA', 9);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AAAE', 1);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AABVF', 11);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AAC', 916);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AACAY', 2);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AACC', 2469);
Insert into TABLE1
(TRADE_DATE, COL_NAME, COL_VALUE, REC_COUNT)
Values
(TO_DATE('12/08/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'STOCK_SYM', 'AACOU', 66);
我想得到如下结果
col_val1 max_val col_val2 min_val
-------- ------- -------- ------
AA 1211091 AAAE 1
A 1210885 AACAY 2
AACC 2496 AAAA 9
AAC 916 AABVF 11
AACOU 66 AACOW 56
我试过了min(col_value) over (partition by trade_date order by rec_count)
,但我只能获得最小值或最大值。当我创建两个表时,一个用min,另一个用max,并从中选择,我得到一个笛卡尔连接。
答案 0 :(得分:3)
返回结果期望值。您应该注意,如果有奇数个结果,则底行将具有相同的col_val1和col_val2值
WITH data as (
SELECT
row_number() over (order by rec_count desc) rn_desc,
row_number() over (order by rec_count asc) rn_asc,
trade_date,
COL_NAME,
col_value,
rec_count
FROM TAble1)
SELECT
d1.col_value col_val1,
d1.rec_count max_val,
d2.col_value col_val2,
d2.rec_count min_val
FROM
data d1
INNER JOIN data d2
ON d1.rn_desc = d2.rn_asc
WHERE
d1.rn_desc <= (select CEIL(COUNT(*)/2) FROM data)
您可以在此data.se query查看一个有效的示例。 (注意,在CEILING
vs CEIL
中,最明显的SQL Server语法转换存在一些细微差别
答案 1 :(得分:2)
我想你可能需要
select col_val, rec_count,
row_number over (partition by trade_date order by rec_count DESC) as HiLoRow
您的答案中的前两列,然后
select col_val, rec_count,
row_number over (partition by trade_date order by rec_count ) as LoHiRow
下半场。 然后从HiLoRow = LoHiRow
中选择这两个,嵌套和连接如果两个col_vals具有相同的rec_count,事情可能仍然不理想 该列表也将是您需要的两倍,因此您可能需要类似
的内容where q1.rec_count >= q2.rec_count
将长度减半。