Advanced SQL query with sub queries, group by, count and sum functions in to SQLalchemy
-
I have written the following query. select distinct(table3.*), (select count(*) from table2 where table2.cus_id = table3.id) as count, (select sum(amount) from table2 where table2.cus_id = table3.id) as total from table2, table1, table3 where table3.id = table2.cus_id and table2.own_id = table1.own_id; It finds the sum of a column and the number of rows that produce the sum as well as some associated data from another table. (Feel free to optimise if you think it can be improved) I need to convert this in to SQLAlchemy but have no idea where to start. I'd appreciate any advice.
-
Answer:
Here's my re-write of your query: SELECT t3.*, x.count, x.amount FROM TABLE3 t3 JOIN (SELECT t2.cus_id COUNT(*) AS count, SUM(t2.amount) AS total FROM TABLE2 t2 WHERE EXISTS(SELECT NULL FROM TABLE1 t1 WHERE t1.own_id = t2.own_id) GROUP BY t2.cus_id) x ON x.cus_id = t3.id Can't help you with the SQLAlchemy part, sorry.
Anthony Eskinazi at Stack Overflow Visit the source
Related Q & A:
- How can I optimize this dynamic SQL query in oracle with PL/SQL?Best solution by docs.oracle.com
- How to convert sql query to Hibernate Criteria query?Best solution by Stack Overflow
- How to convert my SQL query to MS Access query?Best solution by Stack Overflow
- How to make only ONE Sql query?Best solution by Stack Overflow
- How to convert SQL query to LINQ query?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.