INSERT INTO @PaymentsTable1 VALUES (1, 1, 1, 'CA')
INSERT INTO @PaymentsTable1 VALUES (2, 1, 2, 'MX')
INSERT INTO @PaymentsTable1 VALUES (1, 1, 1, 'CA')
INSERT INTO @PaymentsTable1 VALUES (2, 1, 2, 'GB')
INSERT INTO @PaymentsTable1 VALUES (1, 1, 1, 'CA')
INSERT INTO @PaymentsTable1 VALUES (2, 1, 2, 'IN')
DECLARE @Count INT
SELECT @Count = COUNT(DISTINCT PMJ.CountryCode) FROM @PaymentsTable1 PMJ GROUP BY PMJ.PId
IF (@Count >= 3)
SELECT DISTINCT Pkey, PId, DataId FROM @PaymentsTable1
ELSE
SELECT 0 AS [Pkey], 0 AS [PId], 0 AS [DataId]
我需要具有不同国家/地区代码> = 3
的记录在这种情况下,只应返回第二条记录。有了这个实现,
来两条PId记录的逻辑是什么。
答案 0 :(得分:0)
由于您没有包含表定义,因此我假设您按以下顺序排列了列:PKey, PId, DataId, CountryCode
。因此,如果代码不起作用,您将需要列的切换顺序:)
这可以解决你的问题:)
;with cte as (
select PKey, PId, DataId from @PaymentsTable1
group by PKey, PId, DataId
having Count(distinct CountryCode) >= 3
)
select * from cte
union all
select 0 as PKey, 0 as PId, 0 as DataId where not exists(select * from cte)