我跟随查询。
select
dsccnf.Id cnfRptClmId,dsccnf.tblRptcatId cnfRptcatId,dsccnf.Category cnfCategory,
dsccnf.ClmNumber cnfNumber,dsccnf.State cnfState
from tblClmPeriod dcp
inner join tblRptClm dsccnf on dsccnf.tblClmPeriodId = dcp.Id and dsccnf.State=3 --and dsccnf.tblClmPeriodId = 10288
|cnfRptClmId|cnfRptcatId|cnfCategory|cnfNumber|cnfState
|21341 |1650 |L2 |A | 3
|21343 |1652 |L2 |A | 3
|21345 |1657 |T1 |A | 3
|21347 |1660 |T2 |B | 3
|21356 |1670 |T1 |A | 3
获取上述数据,现在我只想获取所有项目(cnfRptClmId,cnfCategory | cnfNumber | cnfState) a)一种类型或单一类型加上ClmNumber列(T2 | B),即(| 21347 | 1660 | T2 | B | 3)和类似记录
b)所有记录只发生两次并忽略其余记录,即|21341|1650|L2|A|3
|21343|1652|L2|A|3
|21345|1657|T1|A|3
|21356|1670|T1|A|3
我可以为这两个结果提供两个单独的查询。预先感谢。
答案 0 :(得分:1)
SELECT *
FROM
(
SELECT
dsccnf.Id cnfRptClmId,
dsccnf.tblRptcatId cnfRptcatId,
dsccnf.Category cnfCategory,
dsccnf.ClmNumber cnfNumber,
dsccnf.State cnfState,
COUNT(dsccnf.Category) OVER (PARTITION BY dsccnf.Category) categoryCount
FROM
tblClmPeriod dcp
INNER JOIN tblRptClm dsccnf ON dsccnf.tblClmPeriodId = dcp.Id
AND dsccnf.State = 3
)
WHERE categoryCount = 2
COUNT(dsccnf.Category) OVER (PARTITION BY dsccnf.Category)
将为您提供每行dsccnf.Category
的计数,因此您只需将其包装在子查询中,并仅选择类别count = 2的记录
基于下面的评论..你可以为dsccnf.Category和dsccnf.ClmNumber添加另一个计数,然后检查该计数是否要按其过滤。
SELECT *
FROM
(
SELECT
dsccnf.Id cnfRptClmId,
dsccnf.tblRptcatId cnfRptcatId,
dsccnf.Category cnfCategory,
dsccnf.ClmNumber cnfNumber,
dsccnf.State cnfState,
COUNT(dsccnf.Category) OVER (PARTITION BY dsccnf.Category) categoryCount,
COUNT(dsccnf.Category) OVER (PARTITION BY dsccnf.Category, dsccnf.ClmNumber) categoryClmCount
FROM
tblClmPeriod dcp
INNER JOIN tblRptClm dsccnf ON dsccnf.tblClmPeriodId = dcp.Id
AND dsccnf.State = 3
)
WHERE categoryCount = 2 -- where category appears twice
OR categoryClmCount = 1 -- where category/clm appear only once
答案 1 :(得分:0)
试试这个:
select
dsccnf.Id cnfRptClmId,
dsccnf.tblRptcatId cnfRptcatId,
dsccnf.Category cnfCategory,
dsccnf.ClmNumber cnfNumber,
dsccnf.State cnfState
from tblClmPeriod dcp
inner join tblRptClm dsccnf on dsccnf.tblClmPeriodId = dcp.Id
and dsccnf.State=3
group by
dsccnf.Id,
dsccnf.tblRptcatId,
dsccnf.Category,
dsccnf.ClmNumber,
dsccnf.State
having count(*) = 2