SELECT query with multiple sub-queries for counts

跟風遠走 提交于 2019-12-05 19:07:45

Here is a way to do that without all the sub-queries

SELECT  Count(r.id) AS cnt_total,
        sum(case when r.action = 'notnow' then 1 else 0 end) as 'cnt_notnow',
        sum(case when r.action = 'insert' then 1 else 0 end) as 'cnt_insert',
        sum(case when r.action = 'update' then 1 else 0 end) as 'cnt_update',
        sum(case when r.action = 'verify' then 1 else 0 end) as 'cnt_verify'        
FROM    auto_reminders_members r

WHERE  r.reminder_id = 1
       AND CONVERT(DATE, r.date_last_reminder) = '20130328'

I also cleaned up the query a bit, removing the group by as this will always be 1, and changing the date comparison to avoid using the messy between logic (Thanks Aaron for the comment)

Here is a way using GROUPING SETS and PIVOT, but this will hinge on the version you are using, which you forgot to tell us:

DECLARE @reminder_id INT, @date DATE;

SELECT @reminder_id = 1, @date = '20130328';

;WITH x AS 
(
  SELECT [action] = COALESCE([action],'Total'), c2 = COUNT(*)
    FROM dbo.auto_reminders_members
    WHERE reminder_id = @reminder_id
    AND CONVERT(DATE, date_last_reminder) = @date
    GROUP BY GROUPING SETS(([action]), ())
)
SELECT reminder_id = @reminder_id, * FROM x 
PIVOT 
(
  MAX([c2]) FOR [action] IN ([Total],[notnow],[insert],[update],[verify])
) AS p;

If 2005, you can replace the GROUPING SETS line with the old-style syntax:

    GROUP BY [action] WITH ROLLUP

I really wish people would stop condoning BETWEEN and this magic "end of day" stuff. If you want a full day your WHERE clause should either be:

WHERE CONVERT(DATE, r.date_last_reminder) = '20130328'

Or, if you are on 2005:

WHERE r.date_last_reminder >= '20130328'
  AND r.date_last_reminder <  '20130329'

Some important points here, mostly that 23:59:59.997 may round up or miss data depending on the underlying data type, that there is no reason you should ever be converting a datetime value to a string to perform a query, and that regional formats like m/d/y are bad for a variety of reasons (for example if your query was for 03/08/2013 I wouldn't know if you were after March 8th or August 3rd).

Please read these articles:

You should also be careful about using reserved words / keywords for column names, like entity_id and action.

You may be able to do something like this

SELECT Count(r.id) AS cnt_total,
  SUM(CASE WHEN r1.action = 'notnow') THEN 1 ELSE 0 END) AS cnt_notnow,
  SUM(CASE WHEN r1.action = 'insert') THEN 1 ELSE 0 END) AS cnt_insert,
  SUM(CASE WHEN r1.action = 'update') THEN 1 ELSE 0 END) AS cnt_update,
  SUM(CASE WHEN r1.action = 'verify') THEN 1 ELSE 0 END) AS cnt_verify,

FROM   auto_reminders_members r
WHERE  r.reminder_id = 1
       AND r.date_last_reminder BETWEEN CONVERT(DATETIME, '03/28/2013', 101) AND
                                            CONVERT(DATETIME,
                                            '03/28/2013' + ' 23:59:59.997 ', 101
                                            )
GROUP  BY r.reminder_id

Try this:

select 
    reminder_id,
    count(1) as Total,
    sum(case when  r1.action = 'notnow' then 1 else 0 end) as cnt_notnow,
    sum(case when  r1.action = 'insert' then 1 else 0 end) as cnt_insert,
    sum(case when  r1.action = 'update' then 1 else 0 end) as cnt_update,
    sum(case when  r1.action = 'verify' then 1 else 0 end) as cnt_verify
from auto_reminders_members r
WHERE  r.reminder_id = 1
   AND r.date_last_reminder BETWEEN CONVERT(DATETIME, '03/28/2013', 101) AND
                                        CONVERT(DATETIME,
                                        '03/28/2013' + ' 23:59:59.997 ', 101
                                        )
GROUP  BY r.reminder_id 

Found one alternate solution:

 SELECT Sum(1)   AS cnt_total,
   Sum(CASE
         WHEN r.action = 'notnow' THEN 1
         ELSE 0
       END) AS cnt_notnow,
   Sum(CASE
         WHEN r.action = 'insert' THEN 1
         ELSE 0
       END) AS cnt_insert,
   Sum(CASE
         WHEN r.action = 'update' THEN 1
         ELSE 0
       END) AS cnt_update,
   Sum(CASE
         WHEN r.action = 'verify' THEN 1
         ELSE 0
       END) AS cnt_verify

FROM auto_reminders_members r WHERE r.reminder_id = 1 AND r.date_last_reminder BETWEEN CONVERT(DATETIME, '03/28/2013', 101) AND CONVERT(DATETIME, '03/28/2013' + ' 23:59:59.997 ', 101 )

select convert(nvarchar(10),warnt.created_dt,120) 'Date',loc.loc_name 'Location',--   
loctype.LocationTypeDesc,
 (select SUM(stk.sel_price) from tbl_mst_stock as stk 
inner join tbl_gen_warranty as wrn on stk.Stock_ID=wrn.Stock_Id
inner join tbl_mst_model as mdl on mdl.Model_ID=wrn.model_id
where wrn.mobile_type like 'SL')'Selleing Price',
(Select COUNT(stk.stk_code) from tbl_mst_stock as stk 
inner join tbl_gen_warranty as warn on stk.Stock_ID=warn.Stock_Id
inner join tbl_mst_model mdl on mdl.Model_ID=warn.model_id
    where warn.mobile_type like 'SL') 'Stock count'
From tbl_mst_location as loc 
inner join tbl_mst_location_types loctype on loc.LocationTypeID=loctype.LocationTypeID
inner join tbl_gen_warranty as warnt on loc.Location_ID=warnt.Location_id
Where  loctype.LocationTypeID=1 and loctype.group_id=1 
and (CONVERT(nvarchar(10),warnt.created_dt,120) 
Between CONVERT(nvarchar(10),'2013-01-01',120) and convert(nvarchar(10),'2013-07-09'))
Group by loc.loc_name,loctype.LocationTypeDesc,warnt.created_dt,loctype.LocationTypeID
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!