I am trying to update eid of the pay table with eid of payc table by joining payid .In the PayC table there are duplicate eid s' for matched payid s',Need to get only one EID for every matched PAYID
update PAY
SET eid = (select t.EID from (select a.EID,a.PAYID, count(a.EID) as cnt
from PAYC a,PAYC b
where a.payid = b.payid
group by a.PAYID,a.eid
having count( a.eid) > 1) t
where T.payid = PAYID)
WHERE EXISTS (select 'X' from (select a.EID,a.PAYID, count(a.EID) as cnt
from PAYC a,PAYC b
where a.payid = b.payid
group by a.PAYID,a.eid
having count( a.eid) > 1) t
where T.payid = PAYID)
Error:Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
we can find duplicate EID by this query BUT NEED TO FETCH ONLY ONE EID
select a.EID,COUNT(a.PAYID), count(a.EID) as cnt
from PAYC a,PAYC b
where a.payid = b.payid
group by a.PAYID,a.eid
having count( a.eid) > 1 AND
COUNT(a.PAYID) >1
sample data
paycid payid eid amount year quarter
1 101 1000 2000 2001 1
2 101 1000 3000 2001 2
Need to fetch
eid
1000
for the matched payid
select top 1 * from stuff
可能会。
Something like this might help?
WITH Duplicates AS (
SELECT
a.EID,
a.PAYID,
ROW_NUMBER() OVER (PARTITION BY a.PAYID ORDER BY a.EID) AS ROWID
FROM
PAYC a
INNER JOIN PAYC b ON b.PAYID = a.PAYID
GROUP BY
a.EID,
a.PAYID
HAVING
COUNT(a.EID) > 1)
UPDATE
p
SET
EID = d.EID
FROM
PAY p
INNER JOIN Duplicates d ON d.PAYID = p.PAYID AND d.ROWID = 1;
Although I have to admit that I don't understand the logic of your self-join from PAYC to PAYC. Surely you don't need to do this to find cases where there are multiple EIDs per PAYID? In which case you could just remove the INNER JOIN PAYC b line entirely?
After thinking about this some more, could you not simply do this?
WITH Duplicates AS (
SELECT
PAYID,
MAX(EID) AS EID
FROM
PAYC
GROUP BY
PAYID
HAVING
COUNT(DISTINCT EID) > 1)
UPDATE
p
SET
EID = d.EID
FROM
PAY p
INNER JOIN Duplicates d ON d.PAYID = p.PAYID;
Then use MAX, MIN or whatever aggregation your require to pick the EID you want to use to update your PAY table (my example uses MAX). This is why your original query didn't work, you didn't tell it which EID to use, and it was returning multiple values.
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.