不是SQL专家。我正在使用带有EF迁移的postgres数据库。坚持这个要求。在这里。
我的表是这样的:
A B C D
20 1 1 1
59 0 0 1
57 1 1 1
10 1 0 0
30 1 1 1
15 0 0 0
行的顺序就像最旧到最新(从上到下)。
我的项目中有一半查询如下:
SELECT dcr."A"
FROM "DCR" dcr
LEFT JOIN "DCM" dcm ON "Id" = dcm."DCRID"
LEFT JOIN "DC" dc ON dc."Id" = dcm."DCID"
WHERE dcr."B" != 0
AND dcr."C" != 0
AND dcr."B" != 0
ORDER BY "UtcDate" desc
limit(1)
当匹配条件时,这将获取最新A的第一部分值。但不是Max部分和分区部分,如下所述。
我想找到((最新的A,其中B = C = D = 1除以前一行中A的最大值,其中B = C = D = 1) - 1)* 100。
我希望在单个查询中发生这种情况,并且有多个这样的组。假设该表包含大约60行,我们可以根据其他列对它们进行分组。每个小组应评估上述公式。
以上示例的预期结果应为:
result = ((30 / 57) - 1) * 100 = (0.5263 - 1) * 100 = -47.73
答案 0 :(得分:1)
您可以使用子查询来获取最大值。我不知道你为什么以这种奇怪的方式写查询,但我会保留它:
SELECT dcr."A" / (SELECT MAX("A")
FROM "DCR"
WHERE dcr."B" != 0
AND dcr."C" != 0
AND dcr."D" != 0)) - 1) * 100
FROM "DCR" dcr
LEFT JOIN "DCM" dcm ON "Id" = dcm."DCRID"
LEFT JOIN "DC" dc ON dc."Id" = dcm."DCID"
WHERE dcr."B" != 0
AND dcr."C" != 0
AND dcr."D" != 0
ORDER BY "UtcDate" desc
limit(1)
答案 1 :(得分:0)
也许是这样的?
select (t1."A"/max(t2."A"))*100 from
(select row_number() over() as id,*
from t
where t."A"=1 and t."B" =1 and t."C"=1 ) as t1
join
(select row_number() over() as id,*
from t
where t."A"=1 and t."B" =1 and t."C"=1 ) as t2
on t1.id>t2.id
group by t1."A",t1."E"