简体   繁体   English

访问查询; 从列表创建主/从

[英]Access Query; Creating Master/Slave from list

Asked a question a few days ago, but have decided to go down a differnt route so am re-doing the question as the edit's were getting a bit messy. 几天前被问到一个问题,但是决定走一条不同的路,所以由于编辑变得有些混乱,所以我还是在做这个问题。

I have a list of data containing two columns: 我有一个包含两列的数据列表:

pID     sKey
100     8611
100     2318
101     3516
101     5413
102     6546
102     5646
102     8411
103     8795
103     5845

The first sKey to appear would become the Master sKey for that pID and each sKey after would be a slave. 出现的第一个sKey将成为该pID的主sKey,之后的每个sKey将是一个从属。 The data would look like this. 数据看起来像这样。

pID     sKey     sKey_1
100     8611    2318    
101     3516     5413
102     6546     5646
102     6546     8411
103     8795    5845     

This query gets me close 该查询使我关闭

SELECT MyTable.pID, MyTable.sKey, MyTable_1.sKey
FROM MyTable 
    INNER JOIN MyTable AS MyTable_1 
    ON MyTable.pID = MyTable_1.pID
WHERE (((IIf([MyTable.sKey]=[MyTable_1.sKey],"Y","N"))="N"))


pID     sKey     sKey
100     2318     8611
100     8611     2318
101     3516     5413
101     5413     3516
102     5646     6546
102     5646     8411
102     6546     5646
102     6546     8411
102     8411     5646
102     8411     6546
103     5845     8795
103     8795     5845

But as you can see it reverses the order and doubles each one up, and when it hits an instance where there is 3 or more sKey's it goes a bit crazy :\\ 但是,正如您所看到的,它颠倒了顺序,并将每个顺序加倍,当它碰到一个实例,该实例中有3个或更多sKey时,它会有点疯狂:\\

Anyone have any ideas, or can point me in the right direction? 任何人都有任何想法,或者可以为我指明正确的方向?

If you're trying to use the MIN(skey) as your Master, then something like this should work: 如果您尝试将MIN(skey)用作主服务器,则应执行以下操作:

select 
  p.pId, 
  p.skey,
  p3.skey skey1
from mytable p
  join (select pID, min(skey) minskey
        from mytable
        group by pID
        ) p2 on p.pid = p2.pid and p.skey = p2.minskey
  join mytable p3 on p.pid = p3.pid and p.skey != p3.skey

SQL Fiddle Demo SQL小提琴演示

This produces slightly different results than yours above. 这会产生与您上面的结果略有不同的结果。

If your desired results are to use the first skey that shows up, then I'd recommend adding an Identity/AutoNumber column to your table just to seed from. 如果您想要的结果是使用显示的第一个关键字,那么我建议您在表中添加一个Identity / AutoNumber列,以作为其种子。 You can't guarantee the order of the results without that column. 没有该列,您无法保证结果的顺序。 So assuming you were to add such a column, then something like this should work: 因此,假设您要添加这样的列,则应如下所示:

select 
  p.pId, 
  p.skey,
  p3.skey skey1
from mytable p
  join (select pID, min(id) minId
        from mytable
        group by pID
        ) p2 on p.id = p2.minId
  join mytable p3 on p.pid = p3.pid and p.id <> p3.id
order by p.pid, p3.id

SQL Fiddle Demo With AutoNumber 带自动编号的SQL小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM