我正在尝试通过CustomerID和Status找到比较行的最佳方法。换句话说,仅当多行和CustomerID之间的状态相等时才显示CustomerID。如果没有,请不要显示CustomerID。
示例数据
[cloudera@quickstart ~]$ ./test_3.sh
08/22/2016
[cloudera@quickstart ~]$
结果我希望
CUSTOMERID STATUS
1000 ACTIVE
1000 ACTIVE
1000 NOT ACTIVE
2000 ACTIVE
2000 ACTIVE
答案 0 :(得分:2)
这里唯一的“代码”是代码块中的最后4行。另一个是建立样本数据。
with T1 as (
Select 1000 as CUSTOMERID, 'ACTIVE' as STATUS from dual union all
select 1000, 'ACTIVE' from dual union all
select 1000, 'NOT ACTIVE' from dual union all
select 2000, 'ACTIVE' from dual union all
select 2000, 'ACTIVE' from dual )
SELECT customerID, max(status) as status
FROM T1
GROUP BY customerID
HAVING count(distinct Status) = 1
答案 1 :(得分:1)
您可以使用WHERE NOT EXISTS
:
Select Distinct CustomerId, Status
From YourTable A
Where Not Exists
(
Select *
From YourTable B
Where A.CustomerId = B.CustomerId
And A.Status <> B.Status
)
答案 2 :(得分:1)
SELECT DISTINCT o.*
FROM
(
SELECT
CustomerId
FROm
TableName
GROUP BY
CustomerId
HAVING
COUNT(DISTINCT Status) = 1
) t
INNER JOIN TableName o
ON t.CustomerId = o.CustomerId
答案 3 :(得分:0)
这里使用IN
非常简单:
SELECT DISTINCT CustomerID, Status
FROM My_Table
WHERE CustomerID IN
(SELECT CustomerID
FROM My_Table
GROUP BY CustomerID
HAVING COUNT(Distinct Status) = 1)
添加:根据您的评论,您真正想要的是所有没有“非活动”的ID。行,这实际上更容易:
SELECT Distinct CustomerID, Status
FROM My_Table
WHERE CustomerID NOT IN
(SELECT CustomerID
FROM My_Table
WHERE Status = 'Not Active')
答案 4 :(得分:0)
这是SQL Server的答案,我相信它应该适用于Oracle。
SELECT
a.AGMTNUM
FROM TableA a
WHERE NOT EXISTS (SELECT 1 FROM TableB b WHERE b.Status = 'NOT ACTIVE' AND a.AGMTNUM = b.AGMTNUM)
AND EXISTS (SELECT 1 FROM TableB c WHERE c.Status = 'ACTIVE' AND a.AGMTNUM = c.AGMTNUM)
这将仅返回至少具有一个“ACTIVE”值且没有“NOT ACTIVE”值的值。