sqlite 如何获取每个键具有最大值的列?

rfbsl7qr  于 2022-11-15  发布在  SQLite
关注(0)|答案(4)|浏览(155)

我有一张table:

CREATE TABLE ask (
    item TEXT ,
    value INTEGRER NOT NULL
);

INSERT INTO ask (item,value) VALUES
("A", 1),
("A", 4),
("A", 3),
("B", 0),
("B", 1),
("C", 2),
("C", 4);

Item|值

A|1
A|4
A|3
B|0
B|1
C|2
C|4
我想要两个额外的列,每个项目的最大值和最小值:
Item|Value|min_val|max_val
-|-|
A|1|1|4
A|4|1|4
A|3|1|4
B|0|0|1
B|1|0|1
C|2|2|4
C|4|2|4
我如何才能在SQLite中获得它?这不起作用:

SELECT *, max(value) AS max_val, min(val) AS min_val FROM ask;
kmpatx3s

kmpatx3s1#

使用窗口函数而不是聚合函数:

SELECT *, 
       MIN(value) OVER (PARTITION BY item) min_val, 
       MAX(value) OVER (PARTITION BY item) max_val 
FROM ask;

请参阅demo

0vvn1miw

0vvn1miw2#

你不应该这样做。最有可能的是,您应该保持表的原样,而创建一个视图:

CREATE VIEW ask_minmax AS (
    SELECT item,
           max(value) AS maxval,
           min(value) AS minval
    FROM ask
    GROUP BY item
);
q5lcpyga

q5lcpyga3#

将CREATE TABLE中的第一个文本数据类型更改为varchar

CREATE TABLE ask (
item VARCHAR,
value Integer NOT NULL)

插入您的数据

INSERT INTO ask (item,value)
VALUES
('A',   1),
('A',   4),
('A',   3),
('B',   0),
('B',   1),
('C',   2),
('C', 4);

然后,在运行以下查询之后

With T1 As
(SELECT  item,max(value) as max_val, min(value) as min_val FROM ask
GROUP bY item)
Select T2.item,T2.value,T1.min_val,T1.max_val From ask T2
join T1 On T1.item = T2.item
bn31dyow

bn31dyow4#

您可以创建一个具有最大/最小值的临时表,然后将其联接以创建所需的表/结果。
即。

select item, max(value) maxval, min(value) minval
from ask group by item;

然后

SELECT a.item, a.value, maxval, minval
from 
  ask a
join
  (select item, max(value) maxval, min(value) minval from ask group by item) b
on a.item = b.item;

相关问题