简体   繁体   中英

SQL query result needs to be summed

Code is

select customerid, count(campaignid) as T, Convert (varchar, CreatedOn,23) from customerbenefits 
where campaignid='6EDBB808-1A91-4B1D-BE1D-27EF15C5D4C7'
and createdon between '2019-09-01' and '2019-10-01'
group by customerid,CreatedOn
having count(campaignid)>1
order by createdon desc 

Result is

 --                         id            /       count  /time         
 --18655680-3B5E-4001-1984-00000000  / 12   /2019-09-30
 --18655680-3B5E-4001-1984-00000000 /  7    /    2019-09-30
 --18655680-3B5E-4001-1984-00000000 / 6    / 2019-09-30

I want result as

 --                         id      /             count / time     
 --  18655680-3B5E-4001-1984-00000000 / 25/ 2019-09-30

I want it grouped to time filter and sum counts.

How can I change my query?

Use two levels of aggregation:

select customerid, dte, sum(T)
from (select customerid, count(*) as T, convert(varchar(255), CreatedOn, 23) as dte
      from customerbenefits 
      where campaignid = '6EDBB808-1A91-4B1D-BE1D-27EF15C5D4C7' and
            createdon >= '2019-09-01' and
            createdon < '2019-10-01'
      group by customerid, CreatedOn
      having count(*) > 1
     ) t
group by customerid, dte
order by createdon desc ;

Notice that I changed the date comparisons so midnight on 2019-10-01 is not included in the data for September.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM