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


SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Today @ 3:20 AM
Points: 2,341, Visits: 3,175
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





No loops! No CURSORs! No RBAR! Hoo-uh!

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?

Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Are you too recursively challenged?
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: Friday, February 01, 2013 2:51 AM
Points: 225, Visits: 80
where do you want to display...Report, or UI or Query result?
Post #1412797
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse