匹配ID的计数,在C中作为查询

时间:2018-04-09 18:51:03

标签: sql sql-server tsql

enter image description here

我想添加一列来显示drgpackid匹配的所有记录的计数。

基本上我想在提供的示例中使用一行,并计算具有该ID并满足查询条件的记录数。

with C as (
      select t1.*
      from DrgPack t1 join
           DrgPack t2
           on t1.DrgID = t2.DrgID and t1.CentralMaintFieldMask <> t2.CentralMaintFieldMask
     )
select *
from rxworkflowpack
where drgpackid in (select ID from c where CentralMaintFieldMask = 0)

3 个答案:

答案 0 :(得分:0)

你可以使用这样的窗口函数:

with C as (
      select t1.*
      from DrgPack t1 join
           DrgPack t2
           on t1.DrgID = t2.DrgID and t1.CentralMaintFieldMask <> t2.CentralMaintFieldMask
     )
select DISTINCT *, COUNT(*) OVER (PARTITION BY drgpackid) AS CountRecords from rxworkflowpack
where drgpackid in (select ID from c where CentralMaintFieldMask = 0)

答案 1 :(得分:0)

有一千种方法可以做到这一点,比如添加另一个带有计数的CTE并加入它

with C as (
      select t1.*
      from DrgPack t1 join
           DrgPack t2
           on t1.DrgID = t2.DrgID and t1.CentralMaintFieldMask <> t2.CentralMaintFieldMask
     ),
     D as (
     select drgpackid, count(*) from rxworkflowpack group by drgpackid)
select *
from rxworkflowpack left join D on rxworkflowpack.drgpackid = d.drgpackid
where drgpackid in (select ID from c where CentralMaintFieldMask = 0)

答案 2 :(得分:0)

您应该使用<来重复计算

  select t1.drgpackid, count(*) as cnt
  from DrgPack t1 
  join DrgPack t2
        on t1.DrgID = t2.DrgID 
       and t1.CentralMaintFieldMask < t2.CentralMaintFieldMask
  join rxworkflowpack  
        on rx.ID = t1.drgpackid  
       and rx.CentralMaintFieldMask = 0 
  group by t1.drgpackid