Combining sum() of similar entry's, and including a WHERE clause SQL - php

I am trying to add up the the numbers from amount, if the booking_id matches. I have been having trouble with summing these numbers as well as adding in a WHERE clause.
This is my code so far
At this time it is summing the numbers correctly, although if I add in the where it doesn't show any results
select *, Sum(amount) FROM payment group by booking_id where booking_id = 1
I have tried some methods like adding queries in queries but I have had no luck. The results I'm attempting to get are below.
booking_id amount
----------------------
1 | 5
2 | 6
1 | 6
3 | 2
3 | 3
4 | 4
Output should be:
booking_id amount
----------------------
1 | 11
2 | 6
3 | 5
4 | 4
I am attempting to group the results so that booking_id with a value of 1 will return a sum of 5+6.
My goal is to be able to add together the amounts that have the same booking id. As well as to be able to include a WHERE clause within this query

To get all booking_id's as requested, simply skip the WHERE clause:
select booking_id, Sum(amount)
FROM payment
group by booking_id
To get all booking_id's for a specific ident (as later requested), add the WHERE clause:
select booking_id, Sum(amount)
FROM payment
where client_id = 123
group by booking_id

Where should be before group by
select booking_id , Sum(amount) FROM payment
where booking_id = 1
group by booking_id

you did wrong only in order to write sql
select booking_id, Sum(amount) FROM payment
where client_id = 1 -- your condition
group by booking_id
Check this link for order

Related

My current MySQL join is not working

I have the following tables:
Users
id | name
-----------------
1 | Johny Bravo
Orders
id | users_id | number
----------------------
1 | 1 | 111111
2 | 1 | 222222
3 | 1 | 333333
4 | 1 | 444444
Example
id | text | number
------------------
1 | test | 111111
2 | test | 111111
3 | test | 222222
4 | test | 222222
5 | test | 333333
6 | test | 333333
Desired Outcome
id: 1
name: Johny Brawo
count(orders): 4
count(example): 6
My current query, which doesn't work
SELECT users.id, users.name, count(orders.id), count(example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id
My current result
id: 1
name: Johny Brawo
count(orders): 8
count(example): 8
Any help would be greatly appreciated.
try count(distinct orders.id), count(distinct example.id)
I've not done any MySQL really, but this works in other Databases...
Starting - a little bit of theory. What does your query do?
First it SELECTs something from users table.
Then it LEFT JOINs with orders table. Number of returned rows is a multiplication of rows from users table and matching rows from orders table. So with only this join you will have 6 rows, each one with Johny Bravo as user, but with different orders data.
Then - another LEFT JOIN. This time with example table. Again - a number of returned rows is a multiplication of rows from orders table and matching rows from example table. So without GROUP BY and COUNT you will have eight rows of result.
Now, the GROUP BY query part. What does it do? It just groups rows with matching GROUP BY column(s). So it will group all rows with same users.id. There are eight of them.
Standard COUNT() will return a number of rows with not null value. As there were eight rows, both counts will return 8.
Now, as #GPW suggested, the solution is a COUNT(DISTINCT x). This function returns a count of unique not null rows.
Thus, the query should look like:
SELECT users.id, users.name, count(DISTINCT orders.id), count(DISTINCT example.id)
FROM users
LEFT JOIN orders ON orders.users_id=users.id
LEFT JOIN example ON example.number=orders.number
GROUP BY users.id
UPDATE - ordering and strict databases
You have also asked about ordering the result. You can order it by any column from your query. As MySQL is not very strict when it comes to grouping, you will also be able to order by any column from users table, as users table results are unique (grouped by id). You can also add, for example ORDER BY COUNT(DISTINCT orders.id) DESC to find users with largest number of orders.
Most databases, though, is more strict in GROUP BY queries. It allows to SELECT only columns with aggregated values or those explicitly contained in GROUP BY clause. So your GROUP BY clause should rather look like
GROUP BY users.id, users.name

how to query for at least X results with a specific attribute

I am trying to get a certain amount of rows of which another amount of rows satisfy a specific condition.
I'll explain.
table 1:
ID | NAME
1 | Thomas
2 | Jason
3 | Oleg
4 | Matt
5 | Sheldon
6 | Jenny
table 2:
ID | ACTIVE
1 | 1
2 | 0
3 | 1
4 | 1
5 | 0
6 | 1
Query:
SELECT tbl_1.ID, tbl_1.NAME, tbl_2.ACTIVE
FROM tbl_1 JOIN tbl_2 ON
tbl_1.ID = tbl_2.ID
WHERE tbl_2.ACTIVE=1
LIMIT 5
in this example I would like to get a minimum number of 5 users, of which 3 are active.
of course the query above will not do the job right, as it limits the total rows to 5. But 3 of the rows in the result (or less if no more exist) MUST be active.
the other way I can think of getting this done, is a union, but my query is so cumbersome, long and complex.
Any ideas?
Use ORDER BY instead:
SELECT tbl_1.ID, tbl_1.NAME, tbl_2.ACTIVE
FROM tbl_1 JOIN
tbl_2
ON tbl_1.ID = tbl_2.ID
ORDER BY (tbl_2.ACTIVE = 1) DESC
LIMIT 5;
This puts the active users at the top of the list and then fills in the rest with other users.
Note: The ORDER BY clause could simply be ORDER BY tbl_2.ACTIVE DESC. I left the boolean logic so you could see the similarity to the WHERE clause.
The way to at least x results is to use the count aggregate and the keyword having
select f1, count(*) records
from yourTable
where whatever
group by f1
having count(*) > x

select and get the most repeated occurrence on mysql

I have a table and i need to recover most repeated occurrence
in the example the occurrence repeats is kills:8
I not want to get the most value, i need get the most repeated value
id | member | kills
1 | - | 9
2 | - | 8
3 | - | 4
4 | - | 8
5 | - | 7
thank you
Group by kills, then order by count of the values in a descending manner, then limit to only one row.
SELECT
kills,
COUNT(id) AS kill_count
FROM table
GROUP BY kills
ORDER BY kill_count DESC
LIMIT 1
Try this query
SELECT kills, COUNT(id) FROM TABLE_NAME GROUP BY kills HAVING COUNT(id) > 1
Juz refer the link
SELECT kills,
count(kills)
FROM TEMP
GROUP BY kills
ORDER BY count(kills) DESC LIMIT 1;
My only idea is to run a while loop that counts each value in the kills column, tallies it and then runs if statements to get the highest tally. Hope this helps.

Counting column times number ordered in mysql

we are working with a table that has a column for every SKU ordered by a customer. So if a particular SKU has been ordered by five different customers, it will appear 5 times. Also, some customers may order 2 of that SKU so in the 'number_ordered' column next to it, there will be a 2. I'm not so good at drawing this out in words so I'll give an example of what the database looks like.
+------------+-----------------+
| item_SKU | Number Ordered |
+------------+-----------------+
| SKU001 | 3 |
| SKU001 | 2 |
| SKU002 | 15 |
| SKU003 | 1 |
+------------+-----------------+
How can I times the sku by the number ordered and then add them all together in MySQL. I need to put it into PHP but I can do that if i get some hints on how to do this.
Cheers
Use this to get the total ordered item of same item_SKU and use it in PHP. If you need the order count also, use COUNT() function
SELECT item_SKU, SUM(Number_Ordered) as Total_Ordered_Item, COUNT(Number_Ordered) as Total_Order_Count
FROM table
GROUP BY item_SKU
Try using count' with group by sku name (SKU001). it returns an output with the count of different sku's.
try below SQL query
1.Sum of Orders
select item_SKU,sum(number_ordered) as orders from `table Name` group by item_SKU order by item_SKU
output
item_SKU | Number Ordered
SKU001 | 5
SKU002 | 15
SKU003 | 1
2. Query to count no of orders
select item_SKU,count(number_ordered) as orders from `table Name` group by item_SKU order by item_SKU
output
item_SKU | Number Ordered
SKU001 | 2
SKU002 | 1
SKU003 | 1
Try this query:
SELECT item_SKU,
COUNT(item_SKU) CNT,SUM(Number_Ordered) TOTAL
FROM TABLE1 GROUP BY item_SKU;
SQL Fiddles
Select item_SKU, SUM(NumberOrdered) As total from [table name] group by item_SKU
Try this one. It gives you total no of occurrence as 'COUNT' and sum of number_ordered as 'SUM_NUM_ORDER'
SELECT item_SKU,COUNT(item_SKU) as COUNT,SUM(Number_Ordered) as SUM_NUM_ORDER FROM TABLE1 GROUP BY item_SKU;
DEMO: http://sqlfiddle.com/#!2/9ec2b9/10

Select a column only if id is distinct MySQL

I have the following table:
AMAZON_ID | DATE | STATUS
1 | 01/03/2014 | Pending
1 | 01/03/2014 | Shipped
2 | 01/04/2014 | Pending
3 | 01/05/2014 | Cancelled
4 | 01/06/2014 | Pending
How can I select the earliest date from table where status is equals Pending where the count of id is not more then one, it should be like the following:
AMAZON_ID | DATE | STATUS
2 | 01/04/2014 | Pending
I can not figure that out, this is what I have so far but its not working:
SELECT date
FROM table
WHERE status = 'Pending'
AND COUNT(id) < 2
ORDER BY date ASC
LIMIT 1;
Use a subquery to GROUP BY the id's that have COUNT of 1. Make sure your id is IN the results of this subquery, with a status of pending. Then ORDER BY date and LIMIT to the first result.
SELECT date
FROM table
WHERE
status = 'Pending' AND
id IN (
SELECT id
FROM table
GROUP BY id
HAVING COUNT(*) = 1
)
ORDER BY date ASC
LIMIT 1;
One thing you can do is use a WHERE IN, and use a select statement to populate the WHERE clause with distinct ids
SELECT date
FROM table
WHERE status = 'Pending'
AND id IN (SELECT DISTINCT id FROM table)
ORDER BY date ASC
LIMIT 1;
It depends on what you really mean by "count of id is not more than one".
I have renamed your column date to ts to make the queries valid SQL (as DATE is a SQL function so it may confuse parsers). See the SQL fiddle for the complete schema I used and the example queries.
Option 2: one row per ID total
In this case you have a problem because you want a query to get one piece of information (the minimum date) that is based on a different piece of information about the same table. This means that you need to queries, luckily you can just join the data of the two queries and filter appropriately.
SELECT data.id, status, MIN(ts)
FROM data
JOIN (SELECT id, COUNT(*) AS amount FROM data GROUP BY id) AS totals
ON totals.id = data.id
WHERE
status = "Pending"
AND totals.amount < 2
GROUP BY data.status;
Option 1 (easy): only one pending row per ID
NOTE: this answer does not answer the OP's question
In this case, the situation is quite easy as you can just filter all your rows with status "pending", the minimum date and the total amount of rows that match your result and, after the aggregation (i.e.: using HAVING) filter those that have less than 2 amounts.
In SQL that would be:
SELECT id, status, MIN(ts) AS minTS, COUNT(*) AS amount
FROM data
WHERE
status = "Pending"
GROUP BY id, status
HAVING amount < 2

Categories