SQL Server: Group Query Based on Substring of Column -
this question has answer here:
i need substring column 'source' typetable , able stats on each region 1 column. row 'server001[en-us]'. print stats each country. is, need countfortype , totalfortype each country.
so, believe server001 calls , group them country i'm looking for.
my query, far, looks this:
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 typetable.source; -- believe issue may here -- source entire string 'server001[en-us]'. need group , provide stats per country, substring of source. --print report: print 'countfortype: ' + cast(@countfortype varchar); print 'totalfortype: ' + cast(@totalfortype varchar); --for each country, print amounts/ percentages etc... print 'country: ' + cast (@country varchar); the report like:
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 could let me know if on right track here, or if should rewritten? pointers appreciated.
you had code. group case statement used country:
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 and way, code not comments want do:
--print report: print 'countfortype: ' + cast(@countfortype varchar); print 'totalfortype: ' + cast(@totalfortype varchar); --for each country, print amounts/ percentages etc... print 'country: ' + cast (@country varchar); you storing data in scalar variables, means execution of query store 1 value each of variables. not allow loop through each result. output in exact format specified in question, need use either while loop or cursor.
however, question whether need sql output format. better let sql return result set, , format output in front end application.
Comments
Post a Comment