Getting individual values using GROUP BY - MySQL - mysql

I have a table called lottery_winners with the following useful colums:
+----+------+------+--------+---------+
| id | plid | zbid | amount | numbers |
+----+------+------+--------+---------+
id is the unique, primary id for the table. plid refers to the past_lotteries table (i.e I can get all the lottery winners from a specific lottery in the past this way. zbid is the id of the member/user (the winner). amount is the sum of money they won in the lottery, and finally numbers is a VARCHAR CSV field with their lottery numbers.
Here's an example of what rows could be in the table:
+----+------+------+--------+---------+
| id | plid | zbid | amount | numbers |
+----+------+------+--------+---------+
| 1 | 1 | 2 | 1 | 1,2,3 |
+----+------+------+--------+---------+
| 2 | 1 | 4 | 5 | 4,5,6 |
+----+------+------+--------+---------+
| 3 | 1 | 3 | 7 | 3,4,5 |
+----+------+------+--------+---------+
| 4 | 1 | 2 | 3 | 7,8,9 |
+----+------+------+--------+---------+
| 5 | 2 | 2 | 8 | 8,9,10 |
+----+------+------+--------+---------+
Now, I want to run a SELECT statement which will bring back all the rows but in a really specific order. The rows should be in grouped by zbid as such (in this case I have added a WHERE plid=1 clause):
+----+------+------+--------+---------+
| id | plid | zbid | amount | numbers |
+----+------+------+--------+---------+
| 1 | 1 | 2 | 1 | 1,2,3 |
+----+------+------+--------+---------+
| 4 | 1 | 2 | 3 | 7,8,9 |
+----+------+------+--------+---------+
| 2 | 1 | 4 | 5 | 4,5,6 |
+----+------+------+--------+---------+
| 3 | 1 | 3 | 7 | 3,4,5 |
+----+------+------+--------+---------+
Next criteria is that not only should they be grouped by zbid, but within this grouping they should be ordered by amount DESC. This is what it would now look like:
+----+------+------+--------+---------+
| id | plid | zbid | amount | numbers |
+----+------+------+--------+---------+
| 4 | 1 | 2 | 3 | 7,8,9 |
+----+------+------+--------+---------+
| 1 | 1 | 2 | 1 | 1,2,3 |
+----+------+------+--------+---------+
| 2 | 1 | 4 | 5 | 4,5,6 |
+----+------+------+--------+---------+
| 3 | 1 | 3 | 7 | 3,4,5 |
+----+------+------+--------+---------+
The top two rows have swapped around.
One more criteria. As you can see, although they are grouped by zbid, there's no specific order to them. I want it to group by zbid, but the order should be based on sum(amount) for each group.
The following table shows the totals for each zbid in no specific order (taking into account that plid=1:
+------+-------------+
| zbid | sum(amount) |
+------+-------------+
| 2 | 4 |
+------+-------------+
| 3 | 7 |
+------+-------------+
| 4 | 5 |
+------+-------------+
So using this information the final result using the SELECT statement should be the following (with an added sum(amount) column):
+----+------+------+--------+---------+-------------+
| id | plid | zbid | amount | numbers | sum(amount) |
+----+------+------+--------+---------+-------------+
| 3 | 1 | 3 | 7 | 3,4,5 | 7 |
+----+------+------+--------+---------+-------------+
| 2 | 1 | 4 | 5 | 4,5,6 | 5 |
+----+------+------+--------+---------+-------------+
| 4 | 1 | 2 | 3 | 7,8,9 | 4 |
+----+------+------+--------+---------+-------------+
| 1 | 1 | 2 | 1 | 1,2,3 | 4 |
+----+------+------+--------+---------+-------------+
That's it! Now I've tried a couple of things myself, but I'm not exactly sure how to get the full final result. I have tried:
SELECT id,plid,zbid,amount,numbers,sum(amount) FROM lottery_winners GROUP BY zbid ORDER BY sum(amount) DESC
Now that seemed to meet the final criterion, but it didn't give me individual results for the table.
Please also note that as these results will be paginated, I will need to be adding LIMIT $start,$perpage to the end of the query.

have this a try:
SELECT a.id,
a.plid,
a.zbid,
a.amount,
a.numbers,
c.totalAmount
FROM lottery_winners a
INNER JOIN (
SELECT b.zbid,
SUM(b.amount) totalAmount
FROM lottery_winner b
WHERE b.plid = 1
GROUP BY b.zbid
) c
ON a.zbid = c.zbid
WHERE a.plid = 1
ORDER BY c.totalAmount desc

Related

MySQL get the row with smallest column value for each product group [duplicate]

This question already has answers here:
Retrieving the last record in each group - MySQL
(33 answers)
Closed 3 years ago.
I have tables products and product_prices. Like that;
products:
+-------------+----------+
| products_id | title |
+-------------+----------+
| 1 | phone |
| 2 | computer |
| 3 | keyboard |
+-------------+----------+
product_prices:
+-------------------+-----------+-------+-------------+
| product_prices_id | productid | price | minquantity |
+-------------------+-----------+-------+-------------+
| 1 | 1 | 500 | 1 |
| 2 | 1 | 450 | 2 |
| 3 | 2 | 800 | 1 |
| 4 | 2 | 700 | 2 |
| 5 | 3 | 15 | 1 |
| 6 | 3 | 10 | 3 |
| 7 | 3 | 7 | 10 |
+-------------------+-----------+-------+-------------+
So there's multiple prices depending on quantity.
My SQL query is like this:
SELECT
*
FROM
products product
INNER JOIN
product_prices price
ON price.productid = product.products_id
GROUP BY
product.products_id
ORDER BY
price.price;
I'm getting this error:
Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'price.product_prices_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
The result without GROUP BY is:
+-------------+----------+-------------------+-----------+-------+-------------+
| products_id | title | product_prices_id | productid | price | minquantity |
+-------------+----------+-------------------+-----------+-------+-------------+
| 3 | keyboard | 7 | 3 | 7 | 10 |
| 3 | keyboard | 6 | 3 | 10 | 3 |
| 3 | keyboard | 5 | 3 | 15 | 1 |
| 1 | phone | 2 | 1 | 450 | 2 |
| 1 | phone | 1 | 1 | 500 | 1 |
| 2 | computer | 4 | 2 | 700 | 2 |
| 2 | computer | 3 | 2 | 800 | 1 |
+-------------+----------+-------------------+-----------+-------+-------------+
What I want to do is, get the row with the cheapest price, grouped by products_id;
+-------------+----------+-------------------+-----------+-------+-------------+
| products_id | title | product_prices_id | productid | price | minquantity |
+-------------+----------+-------------------+-----------+-------+-------------+
| 3 | keyboard | 7 | 3 | 7 | 10 |
| 1 | phone | 2 | 1 | 450 | 2 |
| 2 | computer | 4 | 2 | 700 | 2 |
+-------------+----------+-------------------+-----------+-------+-------------+
I think I need to use MIN() but I have tried several things, which did not work. The closest I could do was ordering it by price, limiting to 1, but it was returning 1 product only.
Any ideas?
If it helps, here's the dump for example database I used: https://transfer.sh/dTvY4/test.sql
You need first to find out what are the minimum prices for each product. For that you use the MIN-aggregate function. As you are selecting a normal columnn with aggregate function, you need to list the normal column in the GROUP BY-clause.
Once you know the minimum prices for each product, you just select those rows from the join of the two tables:
select
p.products_id,
p.title,
pr.product_prices_id,
pr.productid,
pr.price,
pr.minquantity
from product_prices pr
join products p on p.products_id=pr.productid
join (
select productid, min(price) as minprice
from product_prices
group by productid
) mpr on mpr.productid=pr.productid and mpr.minprice=pr.price
See SQLFiddle.
In your query you try to use GROUP BY-clause without an aggregate function, hence the error. Also, you are missing the MIN-logic.
Instead of linking a file to the question, you better create a SQLFiddle / db-fiddle for it. This way it is far easier to answer the question.

Update records based on date on MySQL using joins

I have all those tables above.
car_model_tbl
-----------------------------
id | car_model_name|status |
-----------------------------
1 | seria_1 | 1 |
-----------------------------
2 | golf_4 | 1 |
-----------------------------
3 | C_Class | 1 |
-----------------------------
4 | golf_5 | 1 |
-----------------------------
5 | seria_2 | 0 |
-----------------------------
car_manufacturer_tbl
-------------------------
id |car_manufactu_name |
-------------------------
1 | bmw |
-------------------------
2 | volkswagen |
-------------------------
3 | mercedes |
-------------------------
car_service_tbl
---------------------------------
id | model_id| service_date |
---------------------------------
1 | 1 | 2018-03-10 |
---------------------------------
2 | 2 | 2018-02-10 |
---------------------------------
3 | 1 | 2018-01-10 |
---------------------------------
4 | 1 | 2017-12-10 |
---------------------------------
5 | 2 | 2017-12-10 |
---------------------------------
6 | 3 | 2018-02-10 |
---------------------------------
7 | 2 | 2018-01-10 |
---------------------------------
9 | 4 | 2018-03-10 |
---------------------------------
10 | 4 | 2018-02-10 |
---------------------------------
11 | 5 | 2018-02-10 |
---------------------------------
car_model_manufacturer_relation
-------------------------------------------------
id | model_id | manufactu_id| service_status |
-------------------------------------------------
1 | 1 | 1 | 1 |
-------------------------------------------------
2 | 5 | 1 | 1 |
-------------------------------------------------
3 | 2 | 2 | 1 |
-------------------------------------------------
4 | 4 | 1 | 1 |
-------------------------------------------------
5 | 2 | 2 | 1 |
-------------------------------------------------
6 | 3 | 3 | 1 |
-------------------------------------------------
I need to update car_model_manufacturer_relation.service_status = '0'
where car_service_tbl.service_date < "2018-03-01".
In this case car_model_manufacturer_relation.service_status of models 2, 3 and 5 should be set to '0' because every car_service_tbl.service_date for these models is smaller than "2018-03-01".
However, for models 1 and 4 car_model_manufacturer_relation.service_status should stay '1' because even that they have records smaller than "2018-03-01" they also have bigger dates ex. "2018-03-10".
I am trying to create a query for this but until now without success.
You'll need to nest a grouped query, to get the MAX date per model, and update from that.
update car_model_manufacturer_relation as cmmr,
(select model_id, max(service_date) as check_date
from car_service_tbl
group by model_id) as cst
set cmmr.service_status = '0'
where cmmr.model_id = cst.model_id
and cst.check_date < "2018-03-01"
Where you're using more than one table and the table names include underscores, I try and alias the tables to make the code a little shorter and easier on the eye, hence the use of cmmr and cst as table aliases.
The MAX date has also been renamed for clarity as check_date. You can of course name this anything you wish.
With sub query:
UPDATE car_model_manufacturer_relation c
LEFT join (SELECT model_id, service_date FROM car_service_tbl ORDER BY service_date DESC LIMIT 1) as s ON s.model_id = c.model_id
SET service_status=0
WHERE c.service_date < "2018-03-01"
#tyro - be careful with your solution, as a LEFT JOIN would update the service status to 0 when there wasn't a service date within the car_service_tbl. You would need to use a full join, rather than just the LEFT JOIN as you suggested in order to update the records correctly I feel.

mysql: order -> limit -> sum... possible?

i am loosing it over the following problem:
i have a table with participants and points. each participant can have up to 11 point entries of which i only want the sum of the top 6.
in this example lets say we want the top 2 of 3
+----+---------------+--------+
| id | participantid | points |
+----+---------------+--------+
| 1 | 1 | 11 |
+----+---------------+--------+
| 2 | 3 | 1 |
+----+---------------+--------+
| 3 | 3 | 4 |
+----+---------------+--------+
| 4 | 2 | 3 |
+----+---------------+--------+
| 5 | 1 | 5 |
+----+---------------+--------+
| 6 | 2 | 10 |
+----+---------------+--------+
| 7 | 2 | 9 |
+----+---------------+--------+
| 8 | 1 | 3 |
+----+---------------+--------+
| 9 | 3 | 4 |
+----+---------------+--------+
as a result i want something like
+---------------+--------+
| participantid | points |
+---------------+--------+
| 2 | 19 |
+---------------+--------+
| 1 | 16 |
+---------------+--------+
| 3 | 8 |
+---------------+--------+
(it should be ordered DESC by the resulting points)
is this at all possible with mysql? in one query?
oh and the resulting participant ids should be resolved into the real names from another 'partcipant' table where
+----+------+
| id | name |
+----+------+
| 1 | what |
+----+------+
| 2 | ev |
+----+------+
| 3 | er |
+----+------+
but that should be doable with a join at some point... i know...
Using one of the answers from ROW_NUMBER() in MySQL for row counts, and then modifying to get the top.
SELECT ParticipantId, SUM(Points)
FROM
(
SELECT a.participantid, a.points, a.id, count(*) as row_number
FROM scores a
JOIN scores b ON a.participantid = b.participantid AND cast(concat(a.points,'.', a.id) as decimal) <= cast(concat(b.points,'.', b.id) as decimal)
GROUP BY a.participantid, a.points, a.id
) C
WHERE row_number IN (1,2)
GROUP BY ParticipantId
Had an issue with ties until I arbitrarily broke them with the id

How to create a simple crosstab query in MySQL

I have two tables containing fields as below.
Table 1
| SetID | InQty | Day |
| 1 | 10 | 1 |
| 2 | 10 | 2 |
| 3 | 10 | 3 |
Table 2
| SetID | OtQty | Day |
| 1 | 1 | 5 |
| 1 | 2 | 6 |
| 1 | 3 | 7 |
SetID in table 2 is linked with SetId in table 1. Day is placed in place of date, just for convenience only. Expected Output,
| Day | InQty | OtQty |
| 1 | 10 | |
| 5 | | 1 |
| 6 | | 2 |
| 7 | | 3 |
Blank Space can be filled with NULL or Zero.
It appears you are querying ONLY for set ID = 1 otherwise, I would expect to see in/out values for Set 2 and 3. You should be able to get with a simple UNION
select t1.Day, t1.InQty, 0 OutQty
from Table1 t1
where SetID = 1
order by t1.Day
union select t2.Day, 0, t2.OtQty
from Table2 t2
where SetID = 1
Now, if you want totals spanning different "setID"s and keeping them differentiated from each other, just add the setID as a column and also add to the group by clause as well.

select random value from each type

I have two tables, rating:
+-----------+-----------+-------------+----------+
| rating_id | entity_id | rating_code | position |
+-----------+-----------+-------------+----------+
| 1 | 1 | Quality | 0 |
| 2 | 1 | Value | 0 |
| 3 | 1 | Price | 0 |
+-----------+-----------+-------------+----------+
And rating_option
+-----------+-----------+------+-------+----------+
| option_id | rating_id | code | value | position |
+-----------+-----------+------+-------+----------+
| 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 2 | 2 |
| 3 | 1 | 3 | 3 | 3 |
| 4 | 1 | 4 | 4 | 4 |
| 5 | 1 | 5 | 5 | 5 |
| 6 | 2 | 1 | 1 | 1 |
| 7 | 2 | 2 | 2 | 2 |
| 8 | 2 | 3 | 3 | 3 |
| 9 | 2 | 4 | 4 | 4 |
| 10 | 2 | 5 | 5 | 5 |
| 11 | 3 | 1 | 1 | 1 |
| 12 | 3 | 2 | 2 | 2 |
| 13 | 3 | 3 | 3 | 3 |
| 14 | 3 | 4 | 4 | 4 |
| 15 | 3 | 5 | 5 | 5 |
+-----------+-----------+------+-------+----------+
I need a SQL query (not application level, must stay in the database) which will select a set of ratings randomly. A sample result would look like this, but would pick a random value for each rating_id on subsequent calls:
+-----------+-----------+------+-------+----------+
| option_id | rating_id | code | value | position |
+-----------+-----------+------+-------+----------+
| 1 | 1 | 1 | 1 | 1 |
| 8 | 2 | 3 | 3 | 3 |
| 15 | 3 | 5 | 5 | 5 |
+-----------+-----------+------+-------+----------+
I'm totally stuck on the random part, and grouping by rating_id has been a crap shoot so far. Any MySQL ninjas want to take a stab?
Thanks,
Joe
EDIT: I've tried rand() in a bunch of combinations, and I'm sure that it will be necessary to create the randomness of the result, but I cannot figure out how to return one random row for each of the rows in rating. I cannot use order by rand() limit 1 because I need three rows, and order by rand() limit 3 won't give me one of each rating_id, which is the ultimate goal. I need a combination of rand() and either subqueries or joins so that I can ensure one of each rating_id.
Alright, a little messy, but seems to do the job. Someone may know what they're doing better than I do that can clean this up:
SELECT random.rating_id, random.rand_option_id, r3.code, r3.value, r3.position
FROM
(SELECT r.rating_id,
(SELECT r2.option_id
FROM rating_option r2
WHERE r2.rating_id = r.rating_id
ORDER BY RAND() LIMIT 1) AS 'rand_option_id'
FROM rating_option r
GROUP BY r.rating_id
) random
LEFT JOIN rating_option AS r3 ON r3.option_id = rand_option_id
Results (varies every time, of course):
+-----------+----------------+------+-------+----------+
| rating_id | rand_option_id | code | value | position |
+-----------+----------------+------+-------+----------+
| 1 | 4 | 4 | 4 | 4 |
| 2 | 6 | 1 | 1 | 1 |
| 3 | 13 | 3 | 3 | 3 |
+-----------+----------------+------+-------+----------+
You could use the rand() function to do sorting in a select on the rating table.
For example:
select rating_id from rating order by rand() limit 1
As clarified in your comments, and the other posts above
select * from rating_option order by rand()
will return all records in a random order... However, if you want only X number, then inclue that as the limit as noted by others
select * from rating_option order by rand() limit 5 (or whatever number)
Have you looked into the rand() function?
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
http://www.petefreitag.com/item/466.cfm
http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand
Sample code
select *
from rating_option
group by rating_id
order by rand()