可以像这样进行查询吗?我有ID,一些IN值,Out值,最后一列TOTAL是IN和OUT之差的总和。我真的需要完整的总和。 必须在SUM列中对等于的ID2行求和。没有固定的ID2数量,有时它只是一行总和,其他情况会有更多。我还可以添加一个差异列,只是将该行中的值相加为相同的ID2。
我怀疑的是,是否有可能在一行中累加,在其他列的某些行中累积?
ID ID2 IN OUT TOTAL (IN-OUT)
1 2 200 150 blank-null-space-or whatever but a character
2 2 350 250 doesn't matter, also it can have the same SUM result as below
3 2 600 400 350 ( = 200 - 150 + 350 - 250 + 600 - 400)
4 3 100 80 20
或者我必须在JavaScript的客户端执行此操作?哪个更好或者你建议?也许它在JavaScript中更容易,但我想一步到位来减少池连接。
一个简单的可验证的例子是
CREATE TABLE "table1" (
"ID" int NOT NULL,
"ID2" int DEFAULT NULL,
"`EXT_ID" int DEFAULT NULL,
"IN" int DEFAULT NULL
"OUT" int DEFAULT NULL
);
INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100, 80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100, 80),
(7, 4, 7, 120, 70),
(8, 4, 7, 150, 90);
编辑:添加了外国ID列" EXT_ID"具有条件的条件仅显示一行,而具有MAX值的条件显示相同的" ID2"。
更正了SQL语法。
答案 0 :(得分:1)
是的,它是可行的。您可以使用分组(如果您只想要总数)
CREATE TABLE "table1" (
"ID" int NOT NULL,
"ID2" int DEFAULT NULL,
"EXT_ID" int DEFAULT NULL,
"IN" int DEFAULT NULL,
"OUT" int DEFAULT NULL
);
INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100, 80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100, 80),
(7, 4, 7, 120, 70),
(8, 4, 7, 150, 90);
select "ID2", sum("IN" - "OUT")
from "table1"
group by "ID2";
是的,它是可行的。您可以使用窗口函数
CREATE TABLE "table1" (
"ID" int NOT NULL,
"ID2" int DEFAULT NULL,
"IN" int DEFAULT NULL,
"OUT" int DEFAULT NULL
);
INSERT INTO "table1" ("ID", "ID2", "IN", "OUT") VALUES
(1, 2, 200, 150),
(2, 2, 350, 250),
(3, 2, 600, 400),
(4, 3, 100, 80);
select * , sum("IN" - "OUT") over (partition by "ID2" order by "ID")
from "table1"
order by "ID2", "ID";
正如您在https://www.postgresql.org/docs/current/static/functions-window.html
中看到的那样答案 1 :(得分:1)
试试这个吗?
select (SUM(`IN` - `OUT`)) as 'Total'
from (
select *
from table1
where ID2 IN (select ID2 from table1 where ID = "3")
) as temptable;
但这只能得到1行的结果,你可能需要编辑它。