Sql 划分顺序记录
我在MS Access中有一个表,如: 表格Sql 划分顺序记录,sql,ms-access,Sql,Ms Access,我在MS Access中有一个表,如: 表格 +-----+-----+-----+ |第一|第二|第三| +-----+-----+-----+ |A | 1 | 100| |A | 2 | 200| |A | 3 | 300| |B | 1 | 100| |B | 2 | 200| |B | 3 | 300| |C | 1 | 100| |C | 2 | 200| |C | 3 | 300| +-----+-----+-----+ 现在我想从第3列读取值,对其进行某种操作,并将其存储到另一
+-----+-----+-----+
|第一|第二|第三|
+-----+-----+-----+
|A | 1 | 100|
|A | 2 | 200|
|A | 3 | 300|
|B | 1 | 100|
|B | 2 | 200|
|B | 3 | 300|
|C | 1 | 100|
|C | 2 | 200|
|C | 3 | 300|
+-----+-----+-----+
现在我想从第3列读取值,对其进行某种操作,并将其存储到另一个表中,如:
摘要
+-----+---------+---------+
|第一|第二|第三|
+-----+---------+---------+
|A | 100/200 | 200/300|
|B | 100/200 | 200/300|
|C | 100/200 | 200/300|
+-----+---------+---------+
换句话说,对于summary.2nd
,这意味着:
select table.3rd FROM table where table.1st = A AND table.2nd = 1
除以
select table.3rd FROM table where table.1st = A AND table.2nd = 3
有人能告诉我怎么做吗
可能是VBA/ADO记录集等 试试这个SQL
INSERT INTO Summary
SELECT DISTINCT a.[1st],
a.[3rd] / b.[3rd] AS [2nd],
a.[3rd] / c.[3rd] AS [3rd]
FROM ((tbl AS a
INNER JOIN tbl AS b
ON a.[1st] = b.[1st])
INNER JOIN tbl AS c
ON a.[1st] = c.[1st] )
WHERE a.[2nd] = 1
AND b.[2nd] = 2
AND c.[2nd] = 3
一种方法是条件聚合:
select [1st],
max(iif([2nd] = 1, [3rd], null)) / max(iif([2nd] = 2, [3rd], null)) as [2nd],
max(iif([2nd] = 2, [3rd], null)) / max(iif([2nd] = 3, [3rd], null)) as [3rd]
from t
group by [1st];
下面是另一种选择,使用计算的联接条件:
select
t1.[1st],
t1.[3rd]/t2.[3rd] as [2nd],
t2.[3rd]/t3.[3rd] as [3rd]
from
(
[table] t1 inner join [table] t2
on t1.[1st] = t2.[1st] and t1.[2nd] = t2.[2nd]-1
)
inner join [table] t3
on t1.[1st] = t3.[1st] and t1.[2nd] = t3.[2nd]-2
由于2nd
列的值1、2和3不是硬编码的,因此这适用于2nd
列中任何三个值按顺序相差一的整数
将
[table]
更改为您的表名。@Jbill。非常感谢。