Select rows with highest value of multiple columns [duplicate] - mysql

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL how to find rows which have highest value of specific column
Here is my table schema
--transaction_details--
transaction_id primary_key auto inc
entity_name
entity_transaction
Now, one entity can have multiple transactions. I want to query last transaction made for every entity, which is unlike this post that looks up a specific column. This can be done by selecting the rows with last/max transaction_id for each entity. But I am unable to write this query. I tried using group by entity_name but its selecting any random row.

You can do something like this, if entity_transaction is always the same for the same entity_name:
select max(transaction_id), entity_name, entity_transaction
from transaction_details
group by entity_name, entity_transaction
If you can have different values for entity_transaction for the same entity_name, use this query:
select g.transaction_id, g.entity_name, d.entity_transaction
from
(
select max(transaction_id) transaction_id, entity_name
from transaction_details
group by entity_name
) g
inner join transaction_details d
on g.entity_name = d.entity_name and g.transaction_id = d.transaction_id

try this:
select *
from <table> t
join
( select entity_name,max(transaction_id) as transaction_id
from <table>
group by entity_name)a
on a.entity_name=t.entity_name
and a.transaction_id=t.transaction_id

Related

Join mysql table with distinct value from another table

I encountered a problem on a database I am working with. I have a table of counsels which may hold repeating values, but their is an enrolment number filed which is unique and can be used to fetch them. However, I want to join from a cases_counsel table on the "first" unique value of the counsel table that matches that column on the cases counsel table.
I want to list the cases belonging to a particular counsel using the enrolment_number as the counsel_id on the cp_cases_counsel table. That means I want to pick just a distinct value of a counsel, then use it to join the cp_cases_counsel table and also return the count for such.
However, I keep getting duplicates. This was the mysql query I tried
SELECT T.suitno, T.counsel_id, COUNT(*) as total from cp_cases_counsel T
INNER JOIN (SELECT
enrolment_number as id, MIN(counsel)
FROM
cp_counsel
GROUP BY
enrolment_number
) A
ON A.id = T.counsel_id
GROUP BY T.suitno, T.counsel_id
and
SELECT enrolment_number as id, MIN(counsel) as counsel, COUNT(*) as total FROM cp_counsel
JOIN cp_cases_counsel ON cp_cases_counsel.counsel_id = cp_counsel.enrolment_number
GROUP BY enrolment_number
For the second query, it's joining twice and I am having like double of what I am supposed to get.
The columns that you want in the results are councel (actually only one of all its values) from cp_counsel and counsel_id from cp_cases_counsel, so you must group by them and select them:
SELECT a.counsel, t.counsel_id, COUNT(*) AS total
FROM cp_cases_counsel t
INNER JOIN (
SELECT enrolment_number, MIN(counsel) AS counsel
FROM cp_counsel
GROUP BY enrolment_number
) a ON a.enrolment_number = t.counsel_id
GROUP BY a.counsel, t.counsel_id;

How to get distinct count of rows according to dates

Actually, i did counted distinct empid rows according to dates. But the problem is i get only one empid record of that specific dates.Please let me know how to get all empid records. Here is my sql query.
$sql = "
SELECT COUNT(DISTINCT subcount.empid) AS CountOf
, subcount.name
, subcount.date
, subcount.empid
, calendar.cdate
FROM subcount
, calendar
WHERE subcount.date = calendar.cdate
GROUP
BY subcount.date
";
Here is sql database.
For example, When you look at 2020-11-10 there are two empid with 10 and 7.
When i tried to get both records i get only empid 10 record or 7 record, though i need both record counts:
Here is the output:
Please help me on this.
I think what you are asking is to get list of employees with count of their submissions on a given date, this could show do it:
SELECT cnt.empid AS EmpId
, sc.Name
, cnt.`date` AS Timestamp
, cnt.CountOf AS SubmissionCount
FROM subcount AS sc
INNER JOIN
(
SELECT subcount.empid
subcount.`date`,
count(*) AS CountOf
FROM subcount
INNER JOIN calendar
ON subcount.`date` = calendar.cdate
GROUP BY
subcount.`date`, subcount.empid
) AS cnt
ON sc.empid == cnt.empid
It uses nested SELECT with GROUP BY to calculate count per employee (empid) and date (not only employee). Outer SELECT join nested SELECT to get subcount.Name piece of data which isn't retrieved in nested SELECT so it needs to be retrieved using outer SELECT.
GROUP BY ___ means result rows per ___. If you group by employee ID, you get one row per employee ID. If you want one row per employee ID and date, group by employee ID and date.
SELECT any_value(s.name), s.`date`, s.empid, c.cdate, count(*)
FROM subcount s
JOIN calendar c on c.cdate = s.`date`
GROUP BY s.`date`, s.empid
ORDER BY s.`date`, s.empid;
I expect a calendar table to have one row per date, so there is exactly one cdate for a result row. The name, however, can be different from row to row, so we must tell the DBMS, which to pick. With ANY_VALUE I tell it that I don't care which.

Get a row which has the maximum id

Problem in simple words, 1st must be left joined to the 2nd table where the record is latest. So, I use an approach of using function MAX()
Currently I have 2 tables.
matches
matches_payments
|
Now I want to join the second table to first one using MAX(id) on matches_payments
Desired result
but I am not getting desired result due to greatest-n-per-group problem.
Query
SELECT matches.id, mp.*
FROM matches
LEFT JOIN (SELECT
MAX(id) AS id,
match_id
paymentStatus
FROM matches_payments
GROUP BY match_id) AS mp ON mp.id = matches.id;
Desired result is not produced due to : Stackoverflow Question
When using this feature, all rows in each group should have the same values for the columns that are ommitted from the GROUP BY part. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.
FROM MySQL Dev
PS : I know the tables are poorly designed. It is not my work as the last developer did those.
You need two joins. You need a self-join of the matches_payments table to get the row with the highest ID for each match_id, as shown in SQL Select only rows with Max Value on a Column. Then you LEFT JOIN this to matches to combine the two tables:
SELECT m.*, mp.paymentStatus, mp.paymentAmount
FROM matches AS m
LEFT JOIN (
SELECT mp1.*
FROM matches_payments AS mp1
JOIN (SELECT match_id, MAX(id) AS id
FROM matches_payments
GROUP BY match_id) AS mp2
ON mp1.match_id = mp2.match_id AND mp1.id = mp2.id
) AS mp ON mp.match_id = m.id

Join 2 tables, display one column and group by same column

I have 2 tables:
[CompanyGroups] (id,id_company,id_group)
[CompanyRegions] (id,id_company,id_region)
I want to select only id_company where (id_group in (...) or id_region in (..))
Select g.id_company, r.id_company
from CompanyGroups g, CompanyRegions r
where (g.id_group in (...) or r.id_region in (...)) group by id_company
The results are in 2 columns: g.id_company has some ids and r.id_company has others ids.
How to grup them in only 1 column?
I learnt Database concept quite long ago. So I try to recall those concept and answer what I remember to your question.
You are joining two tables without specifying any joining relationships between them. Then you select fields from each table, so the MySQL will join the two table by mapping each record from CompanyGroups to each record from CompanyRegions.
To solve your problem, you should use UNION instead.
SELECT id_company
FROM CompanyGroups
WHERE id_group in (...)
UNION
SELECT id_company
FROM CompanyRegions
WHERE id_region in (...)
The answer by sagi might result in duplicates so I would extend the answer:
SELECT DISTINCT a.id_company
FROM (
SELECT g.id_company FROM CompanyGroup g
WHERE g.id_group in(...)
UNION
SELECT r.id_company FROM CompanyRegions r
WHERE r.id_region in(...)
) a

Combine rows and put their values in seperate column in mysql

I want to combine two or more rows which have the same name and put their values in two separate column. The problem can be clearer with the following images:
My expected output is:
You can check the fiddle here: fiddle
What I have tried so far is with the MySQL code:
Select subjects, mark_score, activity
FROM(
SELECT subjects, mark_score,
(SELECT regd, subjects, mark_score
FROM exo_i WHERE entry='7' and regd='19') as activity
FROM exo_i WHERE regd='19' GROUP BY subjects)t
As discussed in the comment, the requirement is to display "marks" for the "FA1" entry and "activity" for the "SA1" activity. Assuming there can't be multiple rows with these values (i.e., the combination of regd, subjectsa and activity is unique), you could have a subquery for each of these activities, and join them:
SELECT a.regd, a.subjects, a.marks, b.activity
FROM (SELECT regd, subjects, marks
FROM mytable
WHERE entry = 'FA1') a
JOIN (SELECT regd, subjects, marks AS activity
FROM mytable
WHERE entry = 'SA1') b ON a.regd = b.regd AND a.subjects = b.subjects