我想从表USERS中获得一个列表,它给了我所有具有相同COMPANYID但地址1或地址2不匹配的USERS。
| userID| COMPANYID| ADDRESS 1 | ADDRESS 2
| 3 | B | Street B | 12
| 4 | B | Street B | 13
| 5 | C | Street C | 14
| 6 | C | Street C | 14
| 7 | C | Street C | 15
我想获得COMPANYID存在多次的所有行,但公司用户之间的地址不匹配。这就是我想要的:
SELECT *FROM USERS WHERE comapnyID IN (SELECT companyID FROM USERS GROUP BY companyID HAVING COUNT(*)>1) ORDER BY companyID
我可以通过查询获得第一部分:
gsutil mv
但我不想包含地址已匹配的那些。
答案 0 :(得分:1)
很难:)
select * from USERS where companyid in (
select t1.companyid from (
SELECT n.companyid,n.address1,n.address2,
CASE WHEN n.address1=o.address1 AND n.address2=o.address2 THEN "No Change"
ELSE "Changed"
END as ChangeFlag
FROM USERS n
LEFT OUTER JOIN USERS o ON n.companyid=o.companyid
) t1
where ChangeFlag="Changed")
order by 1,2
答案 1 :(得分:0)
尝试以下查询
SELECT * FROM USERS WHERE comapnyID IN (SELECT COUNT(companyID) FROM USERS GROUP BY companyID HAVING COUNT(companyID)>1) group by comapnyID ORDER BY companyID
答案 2 :(得分:0)
尝试此查询
SELECT
A.*
FROM
USERS AS A
JOIN
USERS AS B ON A.COMPANYID = B.COMPANYID
and A.userId = B.userId
AND A.ADDRESS2 <> B.ADDRESS2
AND A.ADDRESS1 <> B.ADDRESS1
答案 3 :(得分:0)
SELECT T.* FROM
USERS T
INNER JOIN
(
SELECT DISTINCT T1.COMPANYID FROM
(
SELECT COMPANYID,COUNT(*) AS CADDRESS2
FROM USERS
WHERE COMPANYID IN (SELECT COMPANYID FROM USERS GROUP BY COMPANYID HAVING COUNT(*)>1)
GROUP BY COMPANYID
) AS T1
INNER JOIN
(
SELECT COMPANYID,COUNT(*) CADDRESS2
FROM USERS
WHERE COMPANYID IN (SELECT COMPANYID FROM USERS GROUP BY COMPANYID HAVING COUNT(*)>1)
GROUP BY COMPANYID,ADDRESS2
) AS T2
ON T1.COMPANYID = T2.COMPANYID
AND T1.CADDRESS2 != T2.CADDRESS2
) AS T4
ON T.COMPANYID = T4.COMPANYID
<强>输出强>
USER COMPANYID ADDRESS1 ADDRESS2
3 B Street B 12
4 B Street B 13
5 C Street C 14
6 C Street C 14
7 C Street C 15
现场演示
答案 4 :(得分:0)
这个应该有效:
SELECT * FROM USERS
WHERE COMPANYID
IN(SELECT COMPANYID
FROM USERS
WHERE userID
!= 0 GROUP BY COMPANYID
有COUNT()&gt; 1)
和COMPANYID
不在(
SELECT COMPANYID
FROM USERS
GROUP BY COMPANYID
,address1
,address2
有COUNT()&gt; 1)ORDER BY COMPANYID