我只是想知道如何在下面提到的查询中添加count函数,其中我只需要显示那些p_id的计数应该等于1的记录
select Distinct p_id,i.img_path as ImagesName,
(
select p.project_details from [Project] p where p.p_id=i.p_id
) as ProjectName
from [p_Image] i
答案 0 :(得分:0)
请尝试:
SELECT
*
FROM(
select
p_id,
i.img_path as ImagesName,
(
select p.project_details from [Project] p where p.p_id=i.p_id
) as ProjectName,
COUNT(*) OVER (PARTITION BY p_id) CNT
from [p_Image] i
)x WHERE CNT=1
答案 1 :(得分:0)
试试这个:
select p_id, i.img_path as ImagesName, p.project_details as ProjectName, count(*) as sum
from [p_Image] i
join [Project] p on (p.p_id=i.p_id)
group by p_id
having sum = 1;
答案 2 :(得分:0)
您的查询相当于:
select p_id, i.img_path as ImagesName, p.project_details as ProjectName
from p_Image i left outer join
project p
on p.p_id=i.p_id;
以下是获得“独特”p_id的两种方法:
select p_id, min(i.img_path) as ImagesName, min(p.project_details) as ProjectName
from p_Image i left outer join
project p
on p.p_id = i.p_id
group by p_id
having count(*) = 1;
逻辑:当计数为1时,min()
img_path
和project_details
只有一个值。 min()
会返回该值。
以下使用带有窗口函数的子查询:
select p_id, ImagesName, ProjectName
from (select p_id, i.img_path as ImagesName, p.project_details as ProjectName,
count(*) over (partition by p_id) as cnt
from p_Image i left outer join
project p
on p.p_id=i.p_id
) pi
where cnt = 1;