Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
Hello,

Trying to write a query to get the max value per user id. 

Joining my two tables produces a result set where the values that I need to compare are across multiple columns and multiple rows.

The values that I am comparing are across 5 columns and multiple rows. And within each row I have a column (pname) that represents the column that has the highest numeric value per row. I am looking to display just the row that has the highest 'pname' value per user id


Below is my initial query and the initial result set it generates.


  SELECT
  s.id,
  s.pname,
  s.p1,
  s.p2,
  s.p3,
  s.p4,
  s.p5

FROM "sdata" "s"
INNER JOIN "customer" "c" on "c"."id" = "s"."id"

id	pname	P1	P2	P3	P4	P5
12344	P2	1	9	4	3	4
12344	P4	2	5	4	9	5
12344	P3	3	4	9	3	6
5395	P1	9	4	6	4	3
5395	P5	2	1	5	1	9
390	P5	1	4	4	2	9


What I have tried:

SELECT
s.id,
s.pname,
s.p1,
s.p2,
s.p3,
s.p4,
s.p5

FROM "sdata" "s"
INNER JOIN "customer" "c" on "c"."id" = "s"."id"
Posted
Updated 4-Nov-16 6:04am
Comments
Richard Deeming 4-Nov-16 11:08am    
What is your expected output?

Try a GROUP BY: SQL GROUP BY Statement[^] as an inner query to return the id and MAX(pname) AS pname, then JOIN that with your original table as a WHERE s.id = grouped.id AND s.pname = grouped.pname
 
Share this answer
 
First of all, I would suggest changing the design of the tables. Instead of storing multiple values in column p1...p5, store them as rows in a separate table. This would make the data handling really much easier.

Now what comes to the query, even though you said that you have the column name in PNAME I would believe that it would be easier to transform the columns to rows and then find the maximum.

A brute force solution would be to use union. Consider the following:
SQL
SELECT a.id, MAX(a.val)
FROM (
   SELECT sd.id, sd.p1 as val FROM sdata sd UNION ALL
   SELECT sd.id, sd.p2 as val FROM sdata sd UNION ALL
   SELECT sd.id, sd.p3 as val FROM sdata sd UNION ALL
   SELECT sd.id, sd.p4 as val FROM sdata sd UNION ALL
   SELECT sd.id, sd.p5 as val FROM sdata sd) AS a
GROUP BY a.id
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900