Group by in MySQL - mysql

I have a table of the following structure:
ID | COMPANY_ID | VERSION | TEXT
---------------------------------
1 | 1 | 1 | hello
2 | 1 | 2 | world
3 | 2 | 1 | foo
is there a way to get the most recent version of records only, i.e. I would want to have as a result set the IDs 2 and 3?

I'm sure there are better ways, but I tend to use this kind of query:
SELECT *
FROM
(SELECT * FROM test ORDER BY VERSION DESC) AS my_table
GROUP BY COMPANY_ID
Produces this result set:
ID | COMPANY_ID | VERSION | TEXT
---------------------------------
2 | 1 | 2 | world
3 | 2 | 1 | foo

Try this:
SELECT *
FROM (
SELECT company_id, MAX(version) maxVersion
FROM table
GROUP BY company_id ) as val
JOIN table t ON (val.company_id = t.company_id AND t.version = val.maxversion)

If your IDs are ordered (newer version iff higher id):
SELECT t.*, a.maxversion
FROM (
SELECT MAX(id) maxid, MAX(version) maxversion
FROM table
GROUP BY company_id
) a
INNER JOIN table t
ON a.maxid = t.id
However, if your IDs are not properly ordered, you need to use the following query:
SELECT t.*
FROM (
SELECT company_id, MAX(version) maxversion
FROM table
GROUP BY company_id
) v
INNER JOIN table t
ON v.company_id = t.company_id
AND v.maxversion = t.version
(assuming there's an UNIQUE constraint/index on (company_id, version))

Related

MySQL Output column based on value that corresponds with max ID

There are a lot of questions dealing with max values but I can't find any that relate to this issue.
ID | Company | Result
----------------------
1 | 1 | A
2 | 1 | C
3 | 1 | B <--
4 | 2 | C
5 | 2 | B
6 | 2 | A <!--
7 | 3 | C
8 | 3 | A
9 | 3 | B <--
I need to output the Companies whose last Result (based on ID) was "B".
To further complicate the issue, the $query will be used this:
select * from table where Company in ($query)
Any ideas? Thanks!
On MySQL 8+, here is a query you may try using analytic functions:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Company ORDER BY ID DESC) rn
FROM yourTable
)
SELECT ID, Company, Result
FROM cte
WHERE rn = 1 AND Result = 'B';
Demo
On earlier versions of MySQL, we can try joining to a subquery which finds the most recent record for each company:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT Company, MAX(ID) AS MAX_ID
FROM yourTable
GROUP BY Company
) t2
ON t1.Company = t2.Company AND
t1.ID = t2.MAX_ID
WHERE
t1.Result = 'B';
Demo

Calculate date difference from previous row of each unique ID in MySQL

I am a SQL beginner and am learning the ropes of querying. I'm trying to find the date difference between purchases by the same customer. I have a dataset that looks like this:
ID | Purchase_Date
==================
1 | 08/10/2017
------------------
1 | 08/11/2017
------------------
1 | 08/17/2017
------------------
2 | 08/09/2017
------------------
3 | 08/08/2017
------------------
3 | 08/10/2017
I want to have a column that shows the difference in days for each unique customer purchase, so that the output will look like this:
ID | Purchase_Date | Difference
===============================
1 | 08/10/2017 | NULL
-------------------------------
1 | 08/11/2017 | 1
-------------------------------
1 | 08/17/2017 | 6
-------------------------------
2 | 08/09/2017 | NULL
-------------------------------
3 | 08/08/2017 | NULL
-------------------------------
3 | 08/10/2017 | 2
What would be the best way to go about this using a MySQL query?
Not so hard, just use a subquery to find previous purchase for each existing purchase for the customer, and self-join to that record.
Select t.id, t.PurchaseDate, p.Purchase_date,
DATEDIFF(t.PurchaseDate, p.Purchase_date) Difference
From myTable t -- t for This purchase record
left join myTable p -- p for Previous purchase record
on p.id = t.Id
and p.purchase_date =
(Select Max(purchase_date)
from mytable
where id = t.id
and purchase_date <
t.purchaseDate)
This is rather tricky in MySQL. Probably the best way to learn if you are a beginning is the correlated subquery method:
select t.*, datediff(purchase_date, prev_purchase_date) as diff
from (select t.*,
(select t2.purchase_date
from t t2
where t2.id = t.id and
t2.purchase_date < t.purchase_date
order by t2.purchase_date desc
limit 1
) as prev_purchase_date
from t
) t;
Performance should be okay if you have an index on (id, purchase_date).
It is possible to solve it not using dependent subquery
SELECT yt.id, create_date, NULLIF(yt.create_date - tm.min_create_date, 0)
FROM your_table yt
JOIN
(
SELECT id, MIN(create_date) min_create_date
FROM your_table
GROUP BY id
) tm ON tm.id = yt.id
sqlfiddle demo

Mysql - Select at least one or select none

I have a table as so...
----------------------------------------
| id | name | group | number |
----------------------------------------
| 1 | joey | 1 | 2 |
| 2 | keidy | 1 | 3 |
| 3 | james | 2 | 2 |
| 4 | steven | 2 | 5 |
| 5 | jason | 3 | 2 |
| 6 | shane | 3 | 3 |
----------------------------------------
I'm running a select like so:
SELECT * FROM table WHERE number IN (2,3);
The problem im trying to solve is that I want to only grab get results from groups that have 1 or more rows of each number. For instance the above query is returning id's 1-2-3-5-6, when I'd like the results to exclude id 3 since the group of '2' can only return 1 result for the number of '2' and not for BOTH 2 and 3, since there's no row with the number 3 for the group 2 i'd like it to not even select id 3 at all.
Any help would be great.
Try it this way
SELECT *
FROM table1 t
WHERE number IN(2, 3)
AND EXISTS
(
SELECT *
FROM table1
WHERE number IN(2, 3)
AND `group` = t.`group`
GROUP BY `group`
HAVING MAX(number = 2) > 0
AND MAX(number = 3) > 0
)
or
SELECT *
FROM table1 t JOIN
(
SELECT `group`
FROM table1
WHERE number IN(2, 3)
GROUP BY `group`
HAVING MAX(number = 2) > 0
AND MAX(number = 3) > 0
) q
ON t.`group` = q.`group`;
or
SELECT *
FROM table1
WHERE `group` IN
(
SELECT `group`
FROM table1
WHERE number IN(2, 3)
GROUP BY `group`
HAVING MAX(number = 2) > 0
AND MAX(number = 3) > 0
);
Sample output (for both queries):
| ID | NAME | GROUP | NUMBER |
|----|-------|-------|--------|
| 1 | joey | 1 | 2 |
| 2 | keidy | 1 | 3 |
| 5 | jason | 3 | 2 |
| 6 | shane | 3 | 3 |
Here is SQLFiddle demo
On this, you can approach from a fun way with multiple joins for what you WANT qualified, OR, apply a prequery to get all qualified groups as others have suggested, but readability is a bit off for me..
Anyhow, here's an approach going through the table once, but with joins
select DISTINCT
T.id,
T.Name,
T.Group,
T.Number
from
YourTable T
Join YourTable T2
on T.Group = T2.Group AND T2.Group = 2
Join YourTable T3
on T.Group = T3.Group AND T3.Group = 3
where
T.Number IN ( 2, 3 )
So on the first record, it is pointing to by it's own group to the T2 group AND the T2 group is specifically a 2... Then again, but testing the group for the T3 instance and T3's group is a 3.
If it cant complete the join to either of the T2 or T3 instances, the record is done for consideration, and since indexes work great for joins like this, make sure you have one index for your NUMBER criteria, and another index on the (GROUP, NUMBER) for those comparisons and the next query sample...
If doing by more than this simple 2, but larger group, prequery qualified groups, then join to that
select
YT2.*
from
( select YT1.group
from YourTable YT1
where YT1.Number in (2, 3)
group by YT1.group
having count( DISTINCT YT1.group ) = 2 ) PreQualified
JOIN YourTable YT2
on PreQualified.group = YT2.group
AND YT2.Number in (2,3)
Maybe this,if I understand you
SELECT id FROM table WHERE `group` IN
(SELECT `group` FROM table WHERE number IN (2,3)
GROUP BY `group`
HAVING COUNT(DISTINCT number)=2)
SQL Fiddle
This will return all ids where BOTH numbers exist in a group.Remove DISTINCT if you want ids for groups where just one numbers is in.

SQL: How to return an non-existing row?

Say I have the following table:
=================================================
| color_id | parent_id | language_id | name |
=================================================
| 1 | 50 | 1 | Black |
-------------------------------------------------
Then say I need the row WHERE parent_id = 50 AND language_id = 2. Obviously, I would get nothing back based on my example table. However, I still need a result -- probably something like this:
=================================================
| color_id | parent_id | language_id | name |
=================================================
| NULL | 50 | 2 | NULL |
-------------------------------------------------
Is there a way to do this in SQL?
You could do a union query of both the potentially valid record and your default, then select the first one:
SELECT * FROM
(SELECT color_id, parent_id, language_id, name, 1 as order_rank
FROM some_table
WHERE parent_id = %parent_id% AND language_id = %language_id%
UNION
SELECT NULL, %parent_id%, %language_id%, NULL, 2 as order_rank
)
ORDER BY order_rank
LIMIT 1
(Edited with static value for ordering as suggested by OMG Ponies)
try working with LEFT JOIN statement. i'm probably not doing this 100% but a bit of trial and error on your part should make this work.
SELECT table1.field1, table1.field2, table2.field3, table2.field4
FROM my_table table1
LEFT JOIN my_table table2 ON table1.field1=table2.field1 OR table1.field2=table2.field2
a left join on a forced fixed value first table SHOULD work.
select
YourTable.color_id,
ForcedSQL1Record.parent_id,
ForcedSQL1Record.language_id,
YourTable.name
from
( select 50 as Parent_ID,
2 as Language_ID
from YourTable
limit 1 ) ForcedSQL1Record
left join
YourTable
on ForcedSQL1Record.Parent_ID = YourTable.Parent_ID
AND ForcedSQL1Record Language_ID = YourTable.Language_ID

SELECT all the newest records distinct

i have table structure like this
sn | person_id | image_name |
1 | 1 | abc1.jpb
2 | 1 | aa11.jpg
3 | 11 | dsv.jpg
4 | 11 | dssd.jpg
5 | 11 | sdf.jpg
I need distinct person_id newest row as following
2 | 1 | aa11.jjpb
5 | 11 | sdf.jpg
IT is possible ?
SELECT * FROM yourtable GROUP BY person_id ORDER BY sn DESC
Essentially you want to select all records from your table. Then it is grouped by the person_id (limiting the result to 1 per person id)... Ordering by SN decending means that it will return the most recent (highest) sn
Update: (and verified)
SELECT * FROM (SELECT * FROM stackoverflow ORDER BY sn DESC) a GROUP BY person_id ORDER BY sn
SELECT * FROM table GROUP BY person_id HAVING MAX(sn)
EDIT
SELECT f.*
FROM (
SELECT person_id, MAX(sn) as maxval
FROM table GROUP BY person_id
) AS x INNER JOIN table AS f
ON f.person_id = x.person_id AND f.sn = x.maxval;
where table is your table name.
SELECT * FROM table a WHERE a.`id` = ( SELECT MAX(`id`) FROM table b WHERE b.`person_id` = a.`person_id` );
What you are doing inside the parenthesis is selecting the max id for the rows that have that distinct person_id. So for each unique person_id you are getting the most recent entry.