简体   繁体   中英

SQL Subquery within select from same table

I am running a query to pull back data made in our system and compare it to a separate table of invoices, which is working. However, now i need to to only pull that sum(volumnece) only for the invoices greater than the date entered in our system.

Here is my query:

SELECT  
MIN(c.created_at) AS date,
c.meta_account_Id, 
c.organization_Id, 
c.user_id, 
c.meta_distributorId, 
c.meta_accountName,
CASE 
    WHEN sum(s.volumece) IS NULL THEN 0
    ELSE sum(s.volumece)
END AS ces
FROM [commitments] c
LEFT JOIN [Sales2] s ON c.organization_Id=s.org_id AND 
c.meta_account_Id=s.account_id
WHERE c.status='active'
GROUP BY c.meta_account_Id, c.organization_Id, c.user_id, 
c.meta_distributorId, c.meta_accountName

Here is what I think it should look like but obviously incorrect:

SELECT  
MIN(c.created_at) AS date,
c.meta_account_Id, 
c.organization_Id, 
c.user_id, 
c.meta_distributorId, 
c.meta_accountName,
CASE 
    WHEN sum(s.volumece) IS NULL THEN 0
    ELSE (SELECT sum(s.volumece) WHERE s.invoice_date>=c.created_at)
END AS ces
FROM [commitments] c
LEFT JOIN [Sales2] s ON c.organization_Id=s.org_id AND 
c.meta_account_Id=s.account_id
WHERE c.status='active'
GROUP BY c.meta_account_Id, c.organization_Id, c.user_id, 
c.meta_distributorId, c.meta_accountName

Basically the [Sales2] is a table of invoices and the [commitments] is a table of new invoices created in our system. Matching those up by account_id and then pulling all back from the day created and going forward, no invoices previous to the one entered in our system.

Examples:

This one should really sum up to 0 ces because all invoice_dates were after the date was enetered

Commitments

Sales2

I think your case statement needs to be in the sum() clause not outside of it.

sum( CASE WHEN s.volumece IS NULL THEN 0
          when s.invoice_date>=c.created_at then s.volumece
          else 0
          end)

Try to keep the sum(case ...) instead of case when then sum() end. Make sense? Case clause applies to each volumece and not to the total aggregate.

Probably not the most elegant use of the case null there either

sum( CASE when s.invoice_date>=c.created_at then coalesce(s.volumece,0)
          else 0
          end)

simpler?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM