1

在 SQLite 中,我有一个这样创建的表(简化):

CREATE TABLE [entries] (
    [id]     INTEGER NOT NULL PRIMARY KEY,
    [local]  VARCHAR,
    [remote] VARCHAR,
    [value]  INTEGER
);

INSERT INTO entries (local, remote, value) VALUES ("a", "b", 1); 
INSERT INTO entries (local, remote, value) VALUES ("b", "a", -1);
INSERT INTO entries (local, remote, value) VALUES ("b", "a", -1);

INSERT INTO entries (local, remote, value) VALUES ("a", "d", 2); 
INSERT INTO entries (local, remote, value) VALUES ("a", "d", 2); 
INSERT INTO entries (local, remote, value) VALUES ("d", "a", -2);

现在我想列出相互匹配的组合。将本地列视为本地银行帐户,将远程列视为远程银行帐户。每当一个事务从本地远程进行,值为x并且存在一个匹配的事务,它接收到值x但作为负值(相对于第一个找到的值),我希望从 SQLite 获得输出。

我目前的做法是这样的:

sqlite3 -header demo.db \
    "SELECT * FROM
        (SELECT * FROM entries) AS q1,
        (SELECT * FROM entries) AS q2

     WHERE q1.local = q2.remote AND
           q1.remote = q2.local AND
           q1.value = (q2.value * -1)"

但这会返回:

id|local|remote|value|id|local|remote|value
1|a|b|1|2|b|a|-1
1|a|b|1|3|b|a|-1
2|b|a|-1|1|a|b|1
3|b|a|-1|1|a|b|1
4|a|d|2|6|d|a|-2
5|a|d|2|6|d|a|-2
6|d|a|-2|4|a|d|2
6|d|a|-2|5|a|d|2

我想要的结果是:

id|local|remote|value|id|local|remote|value
1|a|b|1|2|b|a|-1
4|a|d|2|6|d|a|-2

不应显示没有匹配伙伴的行 - 每行最多只能匹配一个其他交易。我尝试使用GROUP BY,但这不适用于q1.idq2.id作为参数。

4

2 回答 2

2

由于本地/远程/值可能有几行具有相同的值,因此必须计算每个此类集合中行的排名,以便正确配对行。

使用其他数据库比使用 sqlite 更容易(使用行编号原语,CTE 等),但在 sqlite 中,可以像这样获得正确的结果:

SELECT t1.id, t1.local, t1.remote, t1.value,
t2.id, t2.local, t2.remote, t2.value FROM
(SELECT q1.*, count(q1b.id) AS rank
FROM entries q1 LEFT JOIN entries q1b
ON q1.local = q1b.local AND q1.remote = q1b.remote
AND q1.value = q1b.value AND q1.id >= q1b.id
GROUP BY q1.id) AS t1,
(SELECT q2.*, count(q2b.id) AS rank
FROM entries q2 LEFT JOIN entries q2b
ON q2.local = q2b.local AND q2.remote = q2b.remote
AND q2.value = q2b.value AND q2.id >= q2b.id
GROUP BY q2.id) AS t2
WHERE t1.local = t2.remote AND t1.remote = t2.local
AND t1.value = - t2.value
AND t1.id < t2.id AND t1.rank = t2.rank

http://sqlfiddle.com/#!5/c684e/66/0

于 2012-11-15T17:48:36.337 回答
0
SELECT *
FROM (SELECT MIN(id) AS id, local, remote, value
      FROM entries
      GROUP BY local, remote, value
     ) AS e1,
     (SELECT MIN(id) AS id, local, remote, value
      FROM entries
      GROUP BY local, remote, value
     ) AS e2
WHERE e1.local = e2.remote
  AND e1.remote = e2.local
  AND e1.value = -e2.value
  AND e1.id < e2.id
于 2012-11-15T18:45:20.710 回答