Sql server 从表中获取记录,该表在所有月份中的特定列具有非空值

Sql server 从表中获取记录,该表在所有月份中的特定列具有非空值,sql-server,Sql Server,我有一张桌子: Project_Id Period Value 123 Jan-15 0 123 Feb-15 34 123 Mar-15 78 123 Apr-15 56 456 Jan-15 0 456 Feb-15 0 456 Mar-15 0 456 Apr-15 0 789 Jan-15 45 789 Feb-15 4 789 Mar-15 18 789 Apr-15 26 仅当我在所有月份没有0 for Value字段时,我才需要检索项目数据,如: P

我有一张桌子:

Project_Id  Period  Value

123 Jan-15  0
123 Feb-15  34
123 Mar-15  78
123 Apr-15  56
456 Jan-15  0
456 Feb-15  0
456 Mar-15  0
456 Apr-15  0
789 Jan-15  45
789 Feb-15  4
789 Mar-15  18
789 Apr-15  26
仅当我在所有月份没有0 for Value字段时,我才需要检索项目数据,如:

Project_Id  Period  Value
123 Jan-15  0
123 Feb-15  34
123 Mar-15  78
123 Apr-15  56
789 Jan-15  45
789 Feb-15  4
789 Mar-15  18
789 Apr-15  26
项目456不应该出现在我的结果中,因为对于所有的月份,该特定项目的值都是0

有人能帮我查询吗?

使用SUM和COUNT来确定0值的数量:

内部选择获取至少有一个值不是0的所有项目ID


一些测试数据,但想法仍然是一样的

create table #test123
   (
   pid     int,
   value int
   ) 


   insert into #test123
   select 1,0
   union all
   select 1,1
   union  all
   select 2,0
   union all
   select 2,0
   union all
   select 3,2


   select * from #test123 t2 where exists (select 1 from #test123 t1 
                                                    where t1.pid=t2.pid
                                                         group by pid
                                                      having sum(value)>0
                                            )

为了提高性能,我不希望通过连接来检查重复值:

;WITH CTE as
(
  SELECT 
    Project_Id,
    Period,
    Value,
    max(abs(value)) over (Partition by Period) value
  FROM YourTable
)
SELECT 
  Project_Id,
  Period,
  Value
FROM CTE
WHERE value > 0

*使用abs检查负值。如果所有值都为正值,abs可以省略。

你让我怀疑了一下自己,嘿嘿。
select * from your_table
where project_id in 
(
  select project_id
  from your_table
  group by project_id
  having sum(case when value <> 0 then 1 else 0 end) > 0
)
create table #test123
   (
   pid     int,
   value int
   ) 


   insert into #test123
   select 1,0
   union all
   select 1,1
   union  all
   select 2,0
   union all
   select 2,0
   union all
   select 3,2


   select * from #test123 t2 where exists (select 1 from #test123 t1 
                                                    where t1.pid=t2.pid
                                                         group by pid
                                                      having sum(value)>0
                                            )
;WITH CTE as
(
  SELECT 
    Project_Id,
    Period,
    Value,
    max(abs(value)) over (Partition by Period) value
  FROM YourTable
)
SELECT 
  Project_Id,
  Period,
  Value
FROM CTE
WHERE value > 0