473,774 Members | 2,270 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

2 x SUM(IF.. and 2x LEFT JOIN

Hi,

Suppose I have a query like:

SELECT
products.name AS product,
SUM(IF(stock.in voice=0,1,0)) AS in_stock,
SUM(IF(shopcart .status=1,1,0)) AS reserved
FROM products
LEFT JOIN stock ON products.id=sto ck.product_id
LEFT JOIN shopcart ON products.id=sho pcart.product_i d
GROUP BY products.id

I get wrong results..
E.g. I now have 1 item 'reserved' and 5 in stock; I get 5 reserverd and 5 in
stock..
Is there a workaround for this problem??
Thanx in advance,

Marco
Jul 23 '05 #1
1 4625
Quarco wrote:
Hi,

Suppose I have a query like:

SELECT
products.name AS product,
SUM(IF(stock.in voice=0,1,0)) AS in_stock,
SUM(IF(shopcart .status=1,1,0)) AS reserved
FROM products
LEFT JOIN stock ON products.id=sto ck.product_id
LEFT JOIN shopcart ON products.id=sho pcart.product_i d
GROUP BY products.id

I get wrong results..
E.g. I now have 1 item 'reserved' and 5 in stock; I get 5 reserverd and 5 in
stock..
Is there a workaround for this problem??


An outer join doesn't return just zero or 1 match; it returns N matches,
which result in N rows. So for example if you have 5 in stock for
product id 327, then you get 5 rows corresponding to product id 327.
Thus those 5 rows _each_ match the one item reserved.

Try this query and see what I mean:

SELECT
products.name AS product,
IF(stock.invoic e=0,1,0) AS in_stock,
IF(shopcart.sta tus=1,1,0) AS reserved
FROM products
LEFT JOIN stock ON products.id=sto ck.product_id
LEFT JOIN shopcart ON products.id=sho pcart.product_i d
ORDER BY products.id;

It works both ways too. If you have 2 reserved and 5 in_stock, then you
get 2*5 rows returned, and the sum for both in_stock and reserved
becomes 10.

I can suggest two alternatives:

1. Do each sum calculation in separate queries:

SELECT
products.name AS product,
SUM(IF(stock.in voice=0,1,0)) AS in_stock,
FROM products
LEFT JOIN stock ON products.id=sto ck.product_id
GROUP BY products.id;
SELECT
products.name AS product,
IF(shopcart.sta tus=1,1,0) AS reserved
FROM products
LEFT JOIN shopcart ON products.id=sho pcart.product_i d
GROUP BY products.id;

2. Do the summation in subqueries (requires MySQL 4.1):

SELECT
p.name AS product,
(SELECT SUM(IF(s.invoic e=0,1,0)) FROM stock AS s WHERE s.product_id
= p.id) AS in_stock,
(SELECT SUM(IF(h.status =1,1,0)) FROM shopcart AS h WHERE
h.product_id = p.id) AS reserved
FROM products AS p
ORDER BY products.id

Regards,
Bill K.
Jul 23 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
4321
by: turtle | last post by:
I have a report that I need a field summed in the header if another field = yes. Hrs Yes/No 5 Y 10 N 8 Y 2 N In the header I would like it to sum the hours where Yes/No field =
1
1645
by: Tempy | last post by:
Hi all, i am a newbie to this game and want to know if it is possible with VBA to count up all the rows for a specific field for a table or average or sum ? If it is possible, could you help me with some code please. I add up fields succesfully with the following :- myLcPo = Nz(DSum("", _
1
1978
by: Ladislau S. | last post by:
Dear reader, I am an occasional user of MS Access 2000 running on Windows 98. My hobby is ship model building so I made a database for things that I want to buy. After two strokes I bin unable to remember or find how to calculate the sum of the prices of a column. I made query to calculate the price of itch item (I have some multiple items). Whit this query I made a nice report, bat the best, how match is the price of my wish list I do...
4
59076
by: Tee GEE | last post by:
Is there a SumIF function in Access? I have to SUM a duration of time, but only if a logical Yes/No check box is TRUE. I am working with the expression builder and a Text Box. Thanks for the help. Forgive me...I'm a beginner programmer with expert expectations. *** Sent via Developersdex http://www.developersdex.com ***
0
1687
by: SonyBoy34 | last post by:
I'm trying to get a monthly total of invoices and turnover (from table 'invoices') and the total payments for those invoices (from table 'payments'). This is the query that I use: SELECT COUNT(i.inv_nr) as nbr_inv, SUM(IF(i.cancelled='0',i.total_amount,0)) as turnover, DATE_FORMAT(i.date_sign,'%m %Y') AS month, SUM(IF(i.cancelled='1',1,0)),
2
2160
by: EManning | last post by:
Using A2K. I've got a report/subreport that looks like the following: <main report> Account AAA Beginning Fund Balance: $10,000 <subreport> "Expense" "Total" "Balance" Expense #1 $4,000 $6,000 Expense #2 $50 $5,950 Expense #3 $100 $5,850
2
1955
by: Samuels90 | last post by:
Hey everyone, I need to find a value in a pivot table with a range of values over 12 months (Book5) when 3 criteria are met, Branch#, LOB# and Month#. Sum(if() works for the 1st month, but I do not know how to do the coding when the month changes. Attached are copies of the two files I am working with and my coding so far. Sub glvalueamount() Dim glvalue As Integer Dim glperiod As String If (glperiod = "01") Then
4
5439
by: Fred's | last post by:
hELLO, I have a text box in my report that have the the below formula that sum the quantity of shipments not on time. Up to here, everything is good, but now i try to figure how can I sum if there is no value? =Sum() Please help!!!
54
8364
by: bearophileHUGS | last post by:
Empty Python lists don't know the type of the items it will contain, so this sounds strange: 0 Because that may be an empty sequence of someobject: 0 In a statically typed language in that situation you may answer the
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10040
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8939
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.