Saturday, 1 July 2017

Group By Abd PIVOT in SQL




Select * from tblProduct

SalesAgent | SalesCountry| SalesAmount
Tom| UK |200
shyam| US |180
shyam |UK |260
ram| India |450
Tom |India |350
ram| US |200
Tom |US |130
shyam |India |540
shyam |UK |120
ram| UK |220
shyam |UK |420
ram |US |320
Tom |US |340
Tom |UK |660
shyam |India |430
ram |India |230
ram |India |280
Tom |UK |480
shyam |US |360
ram| UK| 140
==================Group By=====================
Select SalesCountry, SalesAgent, SUM(SalesAmount) as Total 
from tblProduct
group by SalesCountry, SalesAgent
order by SalesCountry, SalesAgent

SalesCountry| SalesAgent | Total
India |ram 960
India |shyam |970
India |Tom |350
UK| ram |360
UK |shyam |800
UK |Tom |1340
US |ram| 520
US |shyam |540

US Tom 470

===============PIVOT=================
Select SalesAgent, India, US, UK
from 
(
   Select SalesAgent, SalesCountry, SalesAmount from tblProducts
) as SourceTable
Pivot
(
 Sum(SalesAmount) for SalesCountry in (India, US, UK)
) as PivotTable

Write a in StordProcedure

CREATE PROCEDURE [dbo].[SpGropByTblProductSales]
as
BEGIN
Select SalesCountry, SalesAgent, SUM(SalesAmount) as Total
from tblProductSales
group by SalesCountry, SalesAgent
order by SalesCountry, SalesAgent
END


Result
SalesAgent India US UK
ram         960        520 360
shyam        970       540 800
Tom               350     470     1340

No comments:

Post a Comment

IIS deployment support details

  Node JS - IIS deployment support details node: http://go.microsoft.com/?linkid=9784334 IISNode: https://github.com/azure/iisnode/releases/...