0

I'm trying to write a query to process a single table that looks like this:

record_id   item_id   part_id   part_length
-----------  -------   --------  ------------
     1         0         0         123.12
     2         0         0         123.09
     3         0         1         231.24
     4         0         1         239.14
     5         1         0          45.91
     6         1         0          46.12
     7         1         1          62.24
     8         1         1          59.40

which is basically a table of inaccurate length measurements of some parts of some items recorded multiple times (not twice, actually each part has 100s of measurements). With a single select, I want to get a result like this:

record_id   item_id   part_id   unit      part_length_ratio
-----------  -------   --------  -----     ----------------
     1         0         0        1       123.12 / 231.24 
     2         0         0        1       123.09 / 239.14 
     3         0         1        0       231.24 / 123.12
     4         0         1        0       239.14 / 123.09
     5         1         0        1        45.91 /  62.24
     6         1         0        1        46.12 /  59.40
     7         1         1        0        62.24 /  45.91
     8         1         1        0        59.40 /  46.12

which is basically selecting each part of an item as the unit and calculates the ratio of the length of other parts of the same item to this unit while matching the measurement times. I wrote a script which computes this kind of table but would like to do it with sql. I can understand if you fail to understand the question :)

for each item i
  for each part unit of i
     for each part other of i
        if unit != other
           print i.id other.part_id unit.part_id other.length / unit.length
4

1 回答 1

1

正如我在评论中所说,表格是无序集:没有第一行或第二行......

...除非您想使用该id列来明确地对行进行排序。

但是,您能保证每种情况总是(确切地)有两个样本,并且“较低的 ID”总是与第一个样本匹配吗?这似乎在现实生活中非常脆弱,可能会有测试将执行两次或测试将丢失或“延迟”完成的情况。没有提到对您的数据库的并发访问。

您不能简单地添加一个“样本编号”列吗?

于 2013-08-15T10:58:15.647 回答