group wise sum query

  • I have a table in the below format.

    S.no Travel Expense Stay Expense Mis Expens Date Employee

    110150 19/Jan/2012 James

    2555 20/Jan/2012 James

    I want to display the above records in below format.

    Date : 19/Jan/2012 Travel Expense 10

    Stay Expens15

    Mis expense0

    Sub-Total25

    Date : 20/Jan/2012 Travel Expense 5

    Stay Expense5

    Mis Expense 5

    Sub-Total 15

    Total40

  • 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![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • where do you want to display...Report, or UI or Query result?

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply