sql - Select statement by group by total -
sql - Select statement by group by total -
i have 2 tables contact
, invoice
linked contactid
please see fiddle
i selecting contact have spend more 2500 per year , query works fine.
i wanted display in below format.
any help on please using sql-server
. can using crystal-report cross tab, trying thing using sql-server
you can pivot, unpivot info original query in desired format:
with t ( select c.contactid, contactname = c.name, year = datepart(year, i.invdate), invoices = cast(count(i.invoiceid) float), invtotal = cast(sum(i.invtotal) float) invoice inner bring together dbo.contact c on c.contactid = i.invcontactid grouping c.contactid, c.name, datepart(year, i.invdate) having sum(i.invtotal) > 2000 ) select contactname = case when pvt.measure = 'invtotal' '' else pvt.contactname end, pvt.measure, [2012] = isnull(pvt.[2012], 0), [2013] = isnull(pvt.[2013], 0), [2014] = isnull(pvt.[2014], 0) t unpivot ( value measure in ([invoices], [invtotal]) ) upvt pivot ( sum(value) [year] in ([2012], [2013], [2014]) ) pvt order pvt.contactname, measure;
example on sql fiddle
sql sql-server-2008-r2 pivot
Comments
Post a Comment