I am fairly new to MySQL queries, especially more complex ones. I have two tables that I want to join together (x and y). Table x contains Name, ID and TotalNum where y contains ID and Online. So it looks like this:
Name | Store| TotalNum
Blah | 1 | 3
Blah1 | 2 | 2 Etc..
Store| Lane | Online
1 | 1 | 1
1 | 2 | 1
1 | 3 | 0
2 | 1 | 1
2 | 2 | 0
Etc..
I am trying to join my tables together and return a count where Online = 1 So, the result I am after is:
Name | TotalNum | Online
Blah | 3 | 2
Blah1 | 2 | 1
Etc..
So far I have the following query:
SELECT s.Name, s.TotalNum, COUNT(r.Online = 1) AS Online FROM TableX AS r
LEFT JOIN TableY AS s ON s.Store = r.Store
WHERE r.Store = 'xx'
But it just returns a count of the total rows regardless if Online = 1 or 0. Any help appreciated. Thanks
SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list. You can also use the ALL keyword in the COUNT function.
SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).
MySQL COUNT syntax example As a part of the SELECT statement, the syntax mostly looks as below: SELECT COUNT(expression) FROM table WHERE condition; Expression is the parameter where you specify which values you want to count. It can be a field or string type value.
COUNT() with HAVING The HAVING clause is used instead of WHERE clause with SQL COUNT() function. The GROUP BY with HAVING clause retrieves the result for a specific group of a column, which matches the condition specified in the HAVING clause.
This should do it:
SELECT x.Name, x.TotalNum, SUM(y.Online = 1) Online FROM TableX x
LEFT JOIN TableY y ON x.Store = y.Store
WHERE x.Store = 'xx'
If you also want a 0
if there is no matching element in the TableY
then you should do COALESCE
the results: COALESCE(SUM(y.Online = 1))
.
Additionally, it is no clear what you mean by ID
as I don't see any on the query nor in the tables. However, this query works in the bases that you can only one distinct name
and TotalNum
for a single Store
.
It's just a matter of summing online
!
SELECT
s.Name,
s.TotalNum,
sum(r.Online) AS Online
FROM TableX AS r
LEFT JOIN TableY AS s ON s.Store = r.Store
WHERE r.Store = 'xx'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With