SQL总列数

时间:2015-10-02 18:44:47

标签: sql-server-2008

你好,我有一个查询,我在那里得到按月分组的记录数(参见下面的示例结果)。我希望SQL做的是在底部有一个额外的Total行,它将是“AccountID”列中所有值的总和。我已经突出显示了“Total”行,我将此添加到当前结果集中。感谢任何帮助!!

enter image description here

以下是我用于收集数据的当前查询:

  SELECT Distinct
  Month = MONTH(pv.VisitStartDateTime)
  ,AccountID_Count = count(pv.AccountID) 

   FROM  hpavisit pv With ( NOLOCK )
   left outer join HPat pt With ( NOLOCK )
   ON      pv.Pat_OID = pt.ObjectID
   and pt.isdeleted = 0
   Left Outer Join HCareUnit HCU With ( NOLOCK )
   on      HCU.ObjectID = pv.PatLocation_oid
   Left Outer Join HCareUnit HCU1 With ( NOLOCK )
   on      HCU1.ObjectID = pv.UnitContacted_oid

   WHERE pv.PatLocation_oid <> 0 and pv.PatLocation_oid is not null
   and pv.IsDeleted = 0    
   and pv.VisitStartDateTime > '08/31/2014 23:23:59'
   and pv.VisitStartDateTime < '03/01/2015'
   GROUP BY MONTH(pv.VisitStartDateTime)

1 个答案:

答案 0 :(得分:0)

在SQL2008上,您可以添加sumary row

SELECT Distinct
  Month = MONTH(pv.VisitStartDateTime)
 ,AccountID_Count = count(pv.AccountID) 

   FROM  hpavisit pv With ( NOLOCK )
   left outer join HPat pt With ( NOLOCK )
   ON      pv.Pat_OID = pt.ObjectID
   and pt.isdeleted = 0
   Left Outer Join HCareUnit HCU With ( NOLOCK )
   on      HCU.ObjectID = pv.PatLocation_oid
   Left Outer Join HCareUnit HCU1 With ( NOLOCK )
   on      HCU1.ObjectID = pv.UnitContacted_oid

   WHERE pv.PatLocation_oid <> 0 and pv.PatLocation_oid is not null
   and pv.IsDeleted = 0    
   and pv.VisitStartDateTime > '08/31/2014 23:23:59'
   and pv.VisitStartDateTime < '03/01/2015'
   GROUP BY MONTH(pv.VisitStartDateTime)
   Union ALL
SELECT Distinct
  'TOTAL',
 ,AccountID_Count = count(pv.AccountID) 

   FROM  hpavisit pv With ( NOLOCK )
   left outer join HPat pt With ( NOLOCK )
   ON      pv.Pat_OID = pt.ObjectID
   and pt.isdeleted = 0
   Left Outer Join HCareUnit HCU With ( NOLOCK )
   on      HCU.ObjectID = pv.PatLocation_oid
   Left Outer Join HCareUnit HCU1 With ( NOLOCK )
   on      HCU1.ObjectID = pv.UnitContacted_oid

   WHERE pv.PatLocation_oid <> 0 and pv.PatLocation_oid is not null
   and pv.IsDeleted = 0    
   and pv.VisitStartDateTime > '08/31/2014 23:23:59'
   and pv.VisitStartDateTime < '03/01/2015'

在SQL20008R2上,您可以尝试:

SELECT Distinct
  Month = MONTH(pv.VisitStartDateTime)
 ,AccountID_Count = count(pv.AccountID) 

   FROM  hpavisit pv With ( NOLOCK )
   left outer join HPat pt With ( NOLOCK )
   ON      pv.Pat_OID = pt.ObjectID
   and pt.isdeleted = 0
   Left Outer Join HCareUnit HCU With ( NOLOCK )
   on      HCU.ObjectID = pv.PatLocation_oid
   Left Outer Join HCareUnit HCU1 With ( NOLOCK )
   on      HCU1.ObjectID = pv.UnitContacted_oid

   WHERE pv.PatLocation_oid <> 0 and pv.PatLocation_oid is not null
   and pv.IsDeleted = 0    
   and pv.VisitStartDateTime > '08/31/2014 23:23:59'
   and pv.VisitStartDateTime < '03/01/2015'
   GROUP GROUP BY GROUPING SETS( 
   (MONTH(pv.VisitStartDateTime),
   ())