我有一张表回复给我的内容如下:
name | value
John | 3
John | 4
John | 5
Robert | 10
Robert | 6
Robert | 4
等...
我需要在不同的名称上显示row_num,如下所示:
row_num | name | value
1 | John | 3
1 | John | 4
1 | John | 5
2 | Robert | 10
2 | Robert | 6
2 | Robert | 4
主要的问题是我的Postgres版本是8.2,我现在无法升级,所以在做完我的研究之后我发现有些有用的功能可以帮助我在我的版本上不可用(如{ {1}},row_number()
等。)
有办法吗?
答案 0 :(得分:0)
SELECT
COALESCE(r.row_num, m.row_max) AS row_num,
t.name,
t.value
FROM tmp t
LEFT JOIN (
SELECT
r1.name,
COUNT(*) AS row_num
FROM (SELECT DISTINCT name FROM tmp) r1
JOIN (SELECT DISTINCT name FROM tmp) r2
ON r1.name > r2.name
GROUP BY 1) r
ON t.name = r.name
LEFT JOIN (
SELECT
COUNT(*) AS row_max
FROM (SELECT DISTINCT name FROM tmp) r3
) m ON True;
答案 1 :(得分:0)
这适用于您的示例数据:
main, READ: TLSv1 Alert, length = 2
main, RECV TLSv1 ALERT: fatal, handshake_failure
%% Invalidated: [Session-1, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA]
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
我只能在9.4上对此进行测试,但我认为它也适用于8.x,但它不会很快。
SQLFiddle:http://sqlfiddle.com/#!15/3580a/1
但您真的升级到支持和维护的版本
答案 2 :(得分:0)
使用(临时)视图模拟子查询和CTE的老技巧:
CREATE TABLE a (name text, val integer);
INSERT INTO a (name , val ) VALUES
('John' , 3 )
, ('John' , 4 )
, ('John' , 5 )
, ('Robert' , 10 )
, ('Robert' , 6 )
, ('Robert' , 4 )
;
CREATE VIEW d AS SELECT DISTINCT name FROM a;
CREATE VIEW c AS
SELECT d0.name, COUNT(*) AS rnk
FROM d d0
JOIN d d1 ON d1. name <= d0.name
GROUP BY d0.name
;
-- SELECT * FROM d;
-- SELECT * FROM c;
SELECT c.rnk, a.name, a.val
FROM a
JOIN c ON a.name = c.name
;
DROP VIEW d;
DROP VIEW c;