I have two tables Customers
and Operations
; I want to sum the data Withdraw
and Deposit
from operations table along with customer name from customer table.
I have created a stored procedure:
select
customer_id, customer_fullname,
amount_withdraw, amount_deposit, entry_date
from
Operations b
join
Customers a on b.customer_id2 = a.customer_id
where
customer_id = 19
This is the result I got:
But the result I want should look like this
Do I need two procedures or what?
2条答案
按热度按时间nue99wik1#
You can do this with
UNION
so effectively join multiple queries into the same resultset:http://sqlfiddle.com/#!18/6f74f/2
Is it a good idea to do this... Not usually. Formatting and aggregates like this are better left to the application or reporting layer. The first problem with the above query is the order of the results, the second problem is that you are using the same column to return different sets of information.
If you really want to do this in SQL, we can fix the order based on the nullability of the date column, but the syntax looks a bit strange. We can't use functions in the order by clause for
UNION
queries, so to do this we have to wrap the rollup data into either a sub-query or a CTEhttp://sqlfiddle.com/#!18/6f74f/1
The sorting can be fixed a different way by adding an arbitrary column instead of relying on nullability of the
entry_date
makes it a bit more obvious, we can then remove the column from the final output if you are using the result directly, but often we would leave it in so that the sorting can be re-affirmed in the reporting layer. This shows how to remove it:Another term for this order column is a Discriminator as it allows us to identify which of the underlying queries the results came from.
http://sqlfiddle.com/#!18/7022a/7
If you wanted to package this into a stored procedure, then use this syntax:
http://sqlfiddle.com/#!18/8a727/1
A more standard solution would be to move the aggregates to other columns, you could also use window queries, but those would have a different layout to your request.
A simple window query solution:
http://sqlfiddle.com/#!18/6f74f/4
You can still use UNION to produce a similar result, however when we do this, it is really usefull to keep the discriminator column so we know what each row represents:
http://sqlfiddle.com/#!18/11d586/4
Finally, we need to talk abot efficiency. Given that your aggregate rows apply to the original query, and you are using stored procedures, we can use temporary tables to store the results of the initial query and then we can query against that recordset directly rather than back into the database.
https://dbfiddle.uk/URG52cH1 (Dot Net Fiddle stopped working ;)
This is effectively the same workflow that a reporting or application layer would typically use:
rxztt3cl2#
Use SUM and Group By
You might want to make the sp accept a parameter for customer id