0

我只想知道如何在下面提到的查询中添加计数函数,其中我只需要显示那些 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
4

3 回答 3

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
于 2013-09-07T06:56:04.360 回答
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;
于 2013-09-07T06:56:42.230 回答
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_pathproject_detailsmin()

以下使用带有窗口函数的子查询:

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;
于 2013-09-07T13:43:50.553 回答