How to get daily profit from sql table

I am trying to find a solution to the problem of finding daily profit from db (ms access) table. The difference between other tips I have found on the internet is that the table does not have a "Price" and "Cost" field, but a "Type" field that distinguishes whether it is "S" revenue or "C" cost

this is the "Record" table

| Date | Price | Quantity | Type |
-----------------------------------
|01/02 | 20    | 2        | C    |
|01/02 | 10    | 1        | S    |
|01/02 | 3     | 10       | S    |
|01/02 | 5     | 2        | C    |
|03/04 | 12    | 3        | C    |
|03/03 | 200   | 1        | S    |
|03/03 | 120   | 2        | C    |

      

So far I have tried different solutions like:

SELECT 
    (SELECT SUM (RS.Price* RS.Quantity) 
     FROM Record RS WHERE RS.Type='S' GROUP BY RS.Data
    ) as totalSales,
    (SELECT SUM (RC.Price*RC.Quantity) 
     FROM Record RC WHERE RC.Type='C' GROUP BY RC.Date
    ) as totalLosses, 
    ROUND(totalSales-totaleLosses,2) as NetTotal, 
    R.Date 
FROM RECORD R";

      

in my mind it could work, but obviously it doesn't

and

SELECT RC.Data, ROUND(SUM (RC.Price*RC.QuantitY),2) as DailyLoss
INTO #DailyLosses
FROM Record RC
WHERE RC.Type='C' GROUP BY RC.Date 

SELECT RS.Date, ROUND(SUM (RS.Price*RS.Quantity),2) as DailyRevenue
INTO #DailyRevenues
FROM Record RS
WHERE RS.Type='S'GROUP BY RS.Date 

SELECT Date, DailyRevenue - DailyLoss as DailyProfit 
FROM #DailyLosses dlos, #DailyRevenues drev
WHERE dlos.Date = drev.Date";

      

My problem outside the correct syntax is the approach to this problem

+3


source to share


1 answer


You can use grouping and conditional summing. Try the following:

SELECT data.Date, data.Income - data.Cost as Profit
FROM (
    SELECT Record.Date as Date,
        SUM(IIF(Record.Type = 'S', Record.Price * Record.Quantity, 0)) as Income,
        SUM(IIF(Record.Type = 'C', Record.Price * Record.Quantity, 0)) as Cost,
    FROM Record
    GROUP BY Record.Date
) data

      



In this case, you first create a subquery to get separate fields for revenue and value, and then your outer query uses subtraction to get the actual profit.

+1


source







All Articles