I'm attempting to calculate return the maximum value in a table, alongside the other values in that table. However, the table I'm doing this for is not a "real" table, it is one generated by a subquery. This gives me problems, as I don't think I can join to it twice, without respecifying the entire subquery.
I currently have a SQL Server solution to this, using ROW_NUMBER() OVER (PARTITION BY providerId ORDER BY partnershipSetScore DESC) rnk, but I'm looking for a DBMS agnostic version if possible, as the unit tests for the project run in a Sqlite DB which does not have this functionality.
Here is the schema and my SQL Server specific query, in case they are useful:
Course:
- int id
- varchar name
- int schoolId
School:
- int id
- varchar name
Partnership:
- int id
- varchar partnershipName
SchoolPartnership:
- int id
- int schoolId
- int partnershipId
Here's the query:
SELECT
schoolId,
partnershipId AS bestPartnershipSetId,
partnershipScore AS bestPartnershipScore
FROM
(
SELECT
pp.schoolId,
partnershipScores.partnershipId,
partnershipScores.partnershipScore,
ROW_NUMBER() OVER (PARTITION BY schoolId ORDER BY partnershipScore DESC) rnk
FROM schoolPartnership pp
INNER JOIN (
SELECT
pp.partnershipId,
(
(CASE WHEN SUM(CASE WHEN c.name LIKE '%French%' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END)
+ (CASE WHEN SUM(CASE WHEN c.name LIKE '%History%' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END)
) AS partnershipScore
FROM schoolPartnership pp
INNER JOIN course c ON c.schoolId = pp.schoolId
GROUP BY partnershipId
) AS partnershipScores ON partnershipScores.partnershipId = pp.partnershipId
) AS schoolPartnershipScores
WHERE rnk = 1
If you need further information on what I'm trying to achieve, please see Custom sorting algorithm for a large amount of data : This query will be a subquery of a larger query that performs sorting of schools by the most suitable partnership.