我试图通过加入payid来更新payc表的eid来支付表格。在PayC表中,匹配的payid s有重复的eid s',每个匹配的PAYID只需要一个EID
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)
错误:子查询返回的值超过1。 当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
我们可以通过此查询找到重复的EID,但只需要一个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
示例数据
paycid payid eid amount year quarter
1 101 1000 2000 2001 1
2 101 1000 3000 2001 2
需要提取
eid
1000
匹配的payid
答案 0 :(得分:0)
select top 1 * from stuff
可能会这样做。
答案 1 :(得分:0)
这样的事可能会有所帮助吗?
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;
虽然我不得不承认我不理解你从PAYC到PAYC的自我加入的逻辑。当然,您不需要这样做才能找到每个PAYID有多个EID的情况?在这种情况下,您可以完全删除INNER JOIN PAYC b线?
在考虑了这个之后,你能不能简单地做到这一点?
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;
然后使用MAX,MIN或您需要的任何聚合来选择您要用来更新PAY表的EID(我的示例使用MAX)。这就是为什么您的原始查询无效,您没有告诉它使用哪个EID,并且它返回了多个值。