简体   繁体   中英

SQL Query: Joining on a SUM()

I'm trying to run a query that sums the value of items and then JOIN on the value of that SUM.

So in the below code, the Contract_For is what I'm trying to Join on, but I'm not sure if that's possible.

SELECT `items_value`.`ContractId` as `Contract`,
`items_value`.`site` as `SiteID`,
SUM(`items_value`.`value`) as `Contract_For`,
`contractitemlists`.`Text` as `Contracted_Text`
FROM items_value
LEFT JOIN contractitemlists ON (`items_value`.`Contract_For`) =  `contractitemlists`.`Ref`;
WHERE `items_value`.`ContractID`='2';

When I've face similar issues in the past, I've just created a view that holds the SUM, then joined to that in another view.

At the moment, the above sample is meant to work for just one dummy value, but it's intended to be stored procedure, where the user selects the ContractID. The error I get at the moment is 'Unknown Column items_value . Contract_For

You cannot use aliases or aggregate using expressions from the SELECT clause anywhere but HAVING and ORDER BY*; you need to make the first "part" a subquery, and then JOIN to that.

It might be easier to understand, though a bit oversimplified and not precisely correct, if you look at it this way as far as order of evaluation goes...

  • FROM (Note: JOIN is only within a FROM)
  • WHERE
  • GROUP BY
  • SELECT
  • HAVING
  • ORDER BY

In actual implementation, "under the hood", most SQL implementations actually use information from each section to optimize other sections (like using some where conditions to reduce records JOINed in a FROM); but this is the conceptual order that must be adhered to.

*In some versions of MSSQL, you cannot use aliases from the SELECT in HAVING or ORDER BY either.


Your query needs to be something like this:

SELECT s.*
   , `cil`.`Text` as `Contracted_Text`
FROM (
   SELECT `iv`.`ContractId` as `Contract`
         , `iv`.`site` as `SiteID`
         , SUM(`iv`.`value`) as `Contract_For`
   FROM items_value AS iv
   WHERE `iv`.`ContractID`='2'
) AS s
LEFT JOIN contractitemlists AS cil ON `s`.`Contract_For` =  cil.`Ref`
;

But as others have mentioned, the lack of a GROUP BY is something to be looked into; as in "what if there are multiple site values."

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