SQL Server: Returning Results of Group By Based on Substring of Column -
for more context on question please see here.
i have query uses group by substring
use thedatabase; declare @fromdate datetime = '2016-02-01 00:00:00.000'; declare @todate datetime = '2016-02-02 23:59:59.999'; declare @source varchar(15) = 'server001'; declare @countfortype bigint; declare @totalfortype decimal(30,8); declare @country varchar(10); select @countfortype = count(*), @totalfortype = sum(typetable.amount), @country = case when (charindex('[', typetable.source) > 0 , charindex(']', typetable.source) > 0) substring(typetable.source, charindex('[', typetable.source) +1, (charindex(']', typetable.source) - 1) - charindex('[', typetable.source)) else null end thetypetable typetable (nolock) typetable.startdate > @fromdate , typetable.startdate < @todate , typetable.source @source group case when (charindex('[', typetable.source) > 0 , charindex(']', typetable.source) > 0) substring(typetable.source, charindex('[', typetable.source) +1, (charindex(']', typetable.source) - 1) - charindex('[', typetable.source)) else null end i'd able report format, either looping through , print out values print or place in result set. either fine.
from researching, there 2 things here compile report:
use cursor , loop through results, printing values. i'm not sure how go doing this.
get rid of scalar variables , have query return result set. i've done below. below re-written query. however, returns single row.
returns single row:
select count(*) countfortype, sum(typetable.amount) totalfortype, case when ( charindex('[', typetable.source) > 0 , charindex(']', typetable.source) > 0) substring( typetable.source, charindex('[', typetable.source) +1, (charindex(']', typetable.source) - 1) - charindex('[', typetable.source)) else null end country thetypetable typetable (nolock) typetable.startdate > @fromdate , typetable.startdate < @todate , typetable.source @source group case when ( charindex('[', typetable.source) > 0 , charindex(']', typetable.source) > 0) substring( typetable.source, charindex('[', typetable.source) +1, (charindex(']', typetable.source) - 1) - charindex('[', typetable.source)) else null end which returns like:
countfortype totalfortype country ========================================= 590 82983909 null ideally, i'd report, either in result set or printing output, has following information:
countfortype: 104 totalfortype: 110000.00000000 country: en-us countfortype: 55 totalfortype: 95000.00000000 country: de-ch countfortype: 25 totalfortype: 5000.00000000 country: tr-tr countfortype: 30 totalfortype: 10000.00000000
i can use bit scripting,
select 'countfortype: ' & count (*) + ' totalfortype: ' & sum(typetable.amount) totalfortype .... here after last apostrophe in line, pressed enter, make line change part of query.
execute query in text mode, pressing ctrl+t first , hope result.
Comments
Post a Comment