简体   繁体   中英

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. 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 :\\

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:

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

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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