logo
down
shadow

SQL Optimization - 3 Tables - Multiple SUMs - 20k records - 12 Seconds


SQL Optimization - 3 Tables - Multiple SUMs - 20k records - 12 Seconds

By : Alekhya Chowdary Myn
Date : November 21 2020, 01:01 AM
this will help I recommend you ditch the correlated subquery in the SELECT list, and use a join operation to an inline view. I'd write the query like this:
code :
SELECT DATE(o.odate)                AS ODate
     , COUNT(o.orderID)             AS OTotal
     , ps.ProductSum                AS ProductSum
     , SUM(os.shipping) / 118 * 100 AS Shipping
     , SUM(os.tax)                  AS Tax
     , SUM(o.ordersum)              AS allPayments
     , SUM(os.coupon)               AS CouponDiscount
     , SUM(os.discount)             AS Discount
     , SUM(o.ordersum)
       / COUNT(DISTINCT o.orderID)  AS BasketAVG
  FROM orders o
  JOIN order_sum os
    ON os.orderID = o.orderID
  LEFT
  JOIN ( SELECT op.orderID
              , SUM(op.psum) AS ProductSum
           FROM order_products op
          GROUP BY op.orderID 
       ) ps
    ON ps.orderID = o.orderID
 WHERE o.status_id NOT IN (24, 26, 27, 28, 29)
   AND o.odate BETWEEN '2014-12-01' AND '2014-12-30'
 GROUP BY DATE(o.odate)
 ORDER BY DATE(o.odate) ASC
... ON orders (odate, status)
  LEFT
  JOIN ( SELECT op.orderID
              , SUM(op.psum) AS ProductSum
           FROM order_products op
           JOIN orders oo
             ON oo.orderID = op.orderID
          WHERE oo.status_id NOT IN (24, 26, 27, 28, 29)
            AND oo.odate BETWEEN '2014-12-01' AND '2014-12-30'
          GROUP BY op.orderID
       ) ps
... ON order_products (orderID, psum)
   AND o.odate >= '2014-12-01 00:00:00'
   AND o.odate <  '2014-12-30 00:00:00'


Share : facebook icon twitter icon
MySQL query - Multiple sums across multiple tables, need to ignore null values

MySQL query - Multiple sums across multiple tables, need to ignore null values


By : Robin
Date : March 29 2020, 07:55 AM
help you fix your problem I am trying to do the below SUM of thumbsup minus thumbsdown from 5 different tables and then SUM all these values together, which it works if all 'commthumbs' returns a row, but if one or more of the 'commthumbs' have no rows then it returns a null value. I have tried using IFNULL as shown in the first LEFT JOIN below as an example. I have also tried ISNULL and COALESCE in place of IFNULL but still can't seem to get it to work. Any suggestions as to what I am doing wrong? , Try this
code :
  SELECT 
        user.userID, user.username,
        SUM(IFNULL(a.commthumbs,0)+IFNULL(b.commthumbs,0)+IFNULL(c.commthumbs,0)+IFNULL(d.commthumbs,0)) AS 'commthumbs', 
        IFNULL(e.fixthumbs,0) AS 'fixthumbs'
    FROM
        user

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(gameCommThUp,0)-IFNULL(gameCommThDown,0)) AS 'commthumbs'
        FROM
        gamecomm
        GROUP BY userID) a ON a.userID = user.userID

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(fixCommThUp,0)-IFNULL(fixCommThDown,0)) AS 'commthumbs'
        FROM 
        fixcomm
        GROUP BY userID) b ON b.userID = user.userID

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(replyCommThUp,0)-IFNULL(replyCommThDown,0)) AS 'commthumbs'
        FROM gamereply
        GROUP BY userID) c ON c.userID = user.userID

    LEFT JOIN (
        SELECT userID, SUM(IFNULL(fixReplyThUp,0)-IFNULL(fixReplyThDown,0)) AS 'commthumbs'
        FROM fixreply
        GROUP BY userID) d ON d.userID = user.userID

    LEFT JOIN (
        SELECT 
        userID, SUM(IFNULL(fixThUp,0)-IFNULL(fixThDown,0)) AS 'fixthumbs'
        FROM 
        fix
        GROUP BY userID) e ON e.userID = user.userID

    WHERE user.userID = 2;
Sort Records comparing sums across multiple tables

Sort Records comparing sums across multiple tables


By : Abdul Rahmat
Date : March 29 2020, 07:55 AM
Hope this helps Gordon was correct about the need to sum before comparing, due to the Cartesian product. However as his query isn't producing the correct result here is the query which does.
code :
select J.id [Job]
  , coalesce(O.InvoicesReceived,0) InvoicesReceived
  , coalesce(O.ContractGiven,0) ContractGiven
  , coalesce(E.GrossValue,0) + coalesce(A.GrossValue,0) TotalQuoteCost
from Job J
left join (select Job, SUM(O.InvoicesReceived) InvoicesReceived, SUM(O.ContractGiven) ContractGiven from [Order] O group by Job) O on O.Job = J.id
left join (select Job, SUM(E.GrossValue) GrossValue from Estimate E group by Job) E on E.Job = J.id
left join (select Job, SUM(A.GrossValue) GrossValue from AdditionalEstimate A group by Job) A on A.Job = J.id
where (
  coalesce(O.InvoicesReceived,0) > (coalesce(E.GrossValue,0) + coalesce(A.GrossValue,0))
) OR ( 
  coalesce(O.ContractGiven,0) > (coalesce(E.GrossValue,0) + coalesce(A.GrossValue,0))
)

select [User Name], count(*)
from (
  select U.UserName [User Name], J.id
    , coalesce(O.InvoicesReceived,0) InvoicesReceived
    , coalesce(O.ContractGiven,0) ContractGiven
    , coalesce(E.GrossValue,0) + coalesce(A.GrossValue,0) TotalQuoteCost
  from Job J
  inner join [User] U on U.id = J.UserId
  left join (select Job, SUM(O.InvoicesReceived) InvoicesReceived, SUM(O.ContractGiven) ContractGiven from [Order] O group by Job) O on O.Job = J.id
  left join (select Job, SUM(E.GrossValue) GrossValue from Estimate E group by Job) E on E.Job = J.id
  left join (select Job, SUM(A.GrossValue) GrossValue from AdditionalEstimate A group by Job) A on A.Job = J.id
  where (
    coalesce(O.InvoicesReceived,0) > (coalesce(E.GrossValue,0) + coalesce(A.GrossValue,0))
  ) OR ( 
    coalesce(O.ContractGiven,0) > (coalesce(E.GrossValue,0) + coalesce(A.GrossValue,0))
  )
) x
group by [User Name]
Joining tables, Total order price based on a DATE and getting 2 separate sums of different dates records instead of 1 wh

Joining tables, Total order price based on a DATE and getting 2 separate sums of different dates records instead of 1 wh


By : niko
Date : March 29 2020, 07:55 AM
With these it helps I am making a reservation/order system where employees create reservations for customers. Each reservation is a new Reservation_id they manually assign tables and know what table is reserved for a specific date. Now I am working on a way to let the personnel take orders from customers, this is not based on their Reservation_id but based on the table they are sitting at that date of time, , I'm not sure, but I think you want this?
code :
SELECT O.Res_Datum, O.Res_ID, O.Tafel_Id, SUM(MI.ItemPrice) AS TotalReceiptPrice
FROM Orders AS O INNER JOIN MenuItem AS MI ON O.MenuItemID = MI.MenuItemID 
GROUP BY O.Res_Datum, O.Res_ID, O.Tafel_Id
multiple sums on grouped tables

multiple sums on grouped tables


By : user3559099
Date : March 29 2020, 07:55 AM
I hope this helps . , You may first get the sum and then join them -
code :
SELECT H.ref, H_TOT, I_TOT
FROM (SELECT ref, SUM(total) H_TOT
      FROM Header
      GROUP BY ref) H
JOIN (SELECT ref, SUM(total) I_TOT
      FROM Items
      GROUP BY ref) I ON H.ref = I.ref
ORDER BY H.ref
Select query takes 3 seconds to pull 330 records. Need Optimization

Select query takes 3 seconds to pull 330 records. Need Optimization


By : Sna
Date : March 29 2020, 07:55 AM
will be helpful for those in need Is anything else happening on this machine?
Even if you made worst possible data structure, SELECT * FROM Users should not take 3 seconds for 310 records. Either there is more (a lot more) records inside or there is some problem outside of SQL server (some other process blocking code or hardware issues).
Related Posts Related Posts :
  • MySQL Innodb Full text Proximity Search Gives Horrible Performance
  • MySQL best approach for db normalising, relationships and foreign keys
  • How to update one table based on the count value of another table while matching ids?
  • MAMP Pro 5.1.1-terminates MySQL when quitting
  • SQL - Get date of most votes cast
  • "Fuzzier" search in mysql
  • Tracing mysqld Using SystemTap
  • SELECT + INSERT + Query Cache = MySQL lock up
  • SQL vs. NoSQL for medium complexity search systems
  • SQL Error when creating table
  • Is it possible to write a query to compare rows to other rows in same table?
  • Display all duplicate records based multiple columns
  • summing time column in mysql
  • InnoDB: Cannot open table
  • Why is IN() considered O(logN) operation?
  • Can a deadlock occur on commit?
  • Is there a fast way to do a '%phrase%' search in any DB?
  • Is using an IN over a huge data set a good idea?
  • How can I know if a table is already arranged in ascending order in MySQL?
  • MySQL - Designing database for a simple game
  • Why am I getting "Host '192.168.1.220' is not allowed to connect to this MySQL server"?
  • what type of password hash? possible mysql hash?
  • MySQL - Using a date range vs functions
  • Using IS NULL and COALESCE in OrderBy Doctrine Querybuilder
  • How to merge MySQL columns into one column if there are empty values in the table?
  • Cardinality Confusion
  • Renaming column multiple ids in SELECT
  • Group all from and to messages per user
  • How to handled the null values in WHERE IN condition in mysql
  • Is it okay to update primary key field to shift a record to the top?
  • Stop query through pdo
  • How to check whether particular value in field in MySQL exists
  • Execute a statement for every table in a database
  • insertion 74G data into mysql table cost more then 2 days, how to improve insert performance
  • Where can I see the differents "Hibernate Console Configurations" in Eclipse
  • MySql | relational database vs non relational database in terms of Performance
  • Exporting mysql database using mysqldump including procedures
  • Trigger MySQL not working
  • How do I update values for individual rows quickly?
  • MySQL join query with multiple where condition
  • MySQL stored procedure is not working
  • MySQL - Order By exact match at the end
  • Select max date or null date from same table MySQL
  • Best solution workaround for needing a mysql event on insert?
  • MySQL select several columns of several tables at the same time without using JOIN
  • Is it more efficient to have a table with one of its columns mostly empty or make a new table and refer to it?
  • mysql data truncated with ñ character
  • MySQL Distinct Active Users for the last month query
  • Get all rows that match another attribute in the same table
  • MySQL statement to get min value with max ID
  • DATEDIFF Current/Date for Last Record
  • What is the logic or procedure for combining multiple DB query's results into one elegant table?
  • Modify TIMESTAMP MySQL for use as Primary Key
  • Django - Efficiently bulk create inherited models
  • MySQL Dual table Join Dual table
  • Ruby on Rails - database where sorted by id
  • MySQL 5.6 : Access denied for user 'root' @ 'localhost' when password contains backslash
  • sql query case dateadd
  • Click on one button multiple times and mySql
  • Select daily amount of specific values from same column
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org