Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

group wise sum query Expand / Collapse
Author
Message
Posted Monday, January 28, 2013 11:10 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Monday, January 28, 2013 11:42 PM
Points: 2, Visits: 10
I have a table in the below format.

S.no Travel Expense Stay Expense Mis Expens Date Employee
1 10 15 0 19/Jan/2012 James
2 5 5 5 20/Jan/2012 James


I want to display the above records in below format.




Date : 19/Jan/2012 Travel Expense 10
Stay Expens 15
Mis expense 0
Sub-Total 25


Date : 20/Jan/2012 Travel Expense 5
Stay Expense 5
Mis Expense 5
Sub-Total 15
Total 40

Post #1412764
Posted Monday, January 28, 2013 11:50 PM


Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Tuesday, October 7, 2014 10:53 PM
Points: 3,421, Visits: 5,359
Is something like this close enough for you?

DECLARE @Expenses TABLE
([S.no] INT
,[Travel Expense] MONEY
,[Stay Expense] MONEY
,[Mis Expens] MONEY
,[Date] DATE
,[Employee] VARCHAR(10))

INSERT INTO @Expenses
SELECT 1,10,15,0,'2012-01-19','James' UNION ALL SELECT 2,5,5,5,'2012-01-20','James'

SELECT [Date]
,CASE WHEN Category IS NULL AND [Date] IS NULL THEN 'Total'
WHEN Category IS NULL THEN 'Subtotal'
ELSE Category END
,Expense=SUM(Expense)
FROM @Expenses
CROSS APPLY (
VALUES ('Travel Expense', [Travel Expense])
,('Stay Expense', [Stay Expense])
,('Mis Expens', [Mis Expens])) a(Category, Expense)
GROUP BY Date, Category WITH ROLLUP





My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
Post #1412772
Posted Tuesday, January 29, 2013 1:12 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Tuesday, September 10, 2013 7:12 AM
Points: 273, Visits: 83
where do you want to display...Report, or UI or Query result?
Post #1412797
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse