How to total on distinct?

  • Hi,

    I have to create a report like this:

    Deposit ID | Deposit Amount | Receipt # | Receipt Amount

    1 | 1000 | 1 | 500

    | | 2 | 500

    2 | 2000 | 3 | 1500

    | | 4 | 500

    ------------------------------------------------------------

    Total | 3000 | 1 | 3000

    I've pulled all the data into one dataset and have the layout and totalling of the Receipt Amount fine.

    My problem is that the total Deposit Amount is way over because it occurs once in each row, even though I am only displaying it once for each row. Is there a way that I can get this totalled properly?

  • i might be reading it wrong, but i think you just want to use either a CTE or a subquery, so you can further group your data;

    something like this, maybe?

    SELECT

    [Deposit ID],

    SUM([Deposit Amount]) AS TotalDeposits,

    SUM([Receipt Amount]) AS TotalReceipts

    FROM (SELECT

    DISTINCT

    [Deposit ID],

    [Deposit Amount],

    [Receipt #],

    [Receipt Amount]

    FROM MyTable) MyAlias

    GROUP BY [Deposit ID]

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!

  • Frank Cazabon (3/12/2013)


    Hi,

    I have to create a report like this:

    Deposit ID | Deposit Amount | Receipt # | Receipt Amount

    1 | 1000 | 1 | 500

    | | 2 | 500

    2 | 2000 | 3 | 1500

    | | 4 | 500

    ------------------------------------------------------------

    Total | 3000 | 1 | 3000

    I've pulled all the data into one dataset and have the layout and totalling of the Receipt Amount fine.

    My problem is that the total Deposit Amount is way over because it occurs once in each row, even though I am only displaying it once for each row. Is there a way that I can get this totalled properly?

    Try getting your totals like this:

    SELECT

    SUM(DepositAmount) OVER (PARTITION BY DepositID) AS TotalDeposits

    ,SUM(ReceiptAmount) OVER (PARTITION BY ReceiptID) AS TotalReceipts

  • Thanks Steven & Lowell, that helped. I didn't quite use your queries but I adjusted my query (stored procedure actually) to do the totalling for me.

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

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