Sql 基于行划分,无需多个查询

Sql 基于行划分,无需多个查询,sql,ms-access,Sql,Ms Access,我有一个3列的表,ID,行号,总计。 我想在单个访问查询中根据ID将第5行的总计$除以第3行 起点是 ID Line Amount 1 | 5 | 4 1 | 3 | 2 2 | 5 | 6 2 | 3 | 2 3 | 5 | 16 3 | 3 | 4 到 我可以创建一个ID为第5行和总计的表,然后创建另一个ID都是唯一的第3行的表,将它们连接起来,然后进行拆分,但我觉得必须有一种更简单的方法 我正在使用MS Access您可以使用条件聚合: select id, (max(ii

我有一个3列的表,ID,行号,总计。 我想在单个访问查询中根据ID将第5行的总计$除以第3行

起点是

ID Line Amount
1 | 5 | 4
1 | 3 | 2
2 | 5 | 6
2 | 3 | 2
3 | 5 | 16
3 | 3 | 4

我可以创建一个ID为第5行和总计的表,然后创建另一个ID都是唯一的第3行的表,将它们连接起来,然后进行拆分,但我觉得必须有一种更简单的方法


我正在使用MS Access

您可以使用条件聚合:

select id,
       (max(iif(linenumber = 5, total, null)) /
        max(iif(linenumber = 3, total, null)
       )
from t
group by id;
结果:

id  Ratio
1   2
2   3
3   4
4   5

SQLFIDLE:

您可以试试这个。在where子句中,必须检查
第3行的值是否不等于
0
。因为这将在运行时给您带来错误

select t5 .id , t5.total/t3.total as Ratio
from table as t5 
     inner join table as t3 
     on t5.id=t3.id and t5.line=5 and t3.line=3
where isnull(t3.total,0)>0 
鉴于你声明:

我想在单个访问查询中根据ID将第5行的总计除以第3行

假设对于给定的
ID
值,可能有多条记录的
line=3
line=5
,您可以使用以下方法对与每个
值(3或5)关联的
金额
进行求和,然后对每个
ID
组获得的总额进行除法:

select t.id, sum(iif(t.line=5,t.amount,0))/sum(iif(t.line=3,t.amount,0)) as ratio
from YourTable t
group by t.id

我不确定您希望如何处理以下情况:给定的
ID
没有
Line=3
记录,或者
Line=3
没有
Amount=0
记录,这两种情况都会导致Div/0错误。

谢谢,我想我正在寻找不同的解决方案。我重新措辞了问题,并添加了结果示例,以使问题更加清楚。@ArchavanichKawmongkolsi。这基本上与
groupby
的查询相同。谢谢,这太棒了!如果有10个不同的行号和5组不同的比率,这还有意义吗?或者,创建其中5个并通过ID@ArchavanichKawmongkolsi-这取决于规则是什么。你在问题中陈述的规则是“第5行除以第3行”。你能概括这条规则吗?如果您可以将其推广,可能会有更好的查询。如果行号已知/固定,则还可以合并多个select语句。
select t1.id, t1.amount/t2.amount as ratio
from t t1
join t t2 on t1.id = t2.id
where t1.line = 5
and t2.line = 3
select t5 .id , t5.total/t3.total as Ratio
from table as t5 
     inner join table as t3 
     on t5.id=t3.id and t5.line=5 and t3.line=3
where isnull(t3.total,0)>0 
select t.id, sum(iif(t.line=5,t.amount,0))/sum(iif(t.line=3,t.amount,0)) as ratio
from YourTable t
group by t.id