0

I have two tables Patients and Treatment type. For the past hour ive been trying to make a query to see the treatment type name each patient has had and groups Patient id 1 in one column and 2 in another column but instead of their id it will be their first name and last name.

I have posted an image mockup from excel of what i want the query to do below.

The name of the patients table is patients and the name of the treatment table is treatment_type

idPatients PatientFName PatientLName PatientDOB PatientsCounty PatieritsCity PatientsOccupation Specalist_idSpecialist
         1 Roger        James        16/05/1992 Hampshire      Portsmouth    Student            2
         2 James        Murray       08/02/1960 Middlesex      Harrow        Business Owner     1

https://i.stack.imgur.com/MKKBd.png

I hope someone can help me.

Strawberry
  • 33,750
  • 13
  • 40
  • 57

1 Answers1

0

I don't think you'll get exactly what you're wanting here, you can't create new columns for each patient the way you're thinking of.

You can however get a row for every condition that each patient has and include their name and id for each row. Then use your prepossessing language to detect when the ID is the same and list all conditions under that name in the format you're looking for. To do that you need a LEFT JOIN. Here's a great link to visualize what these can do for you:

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

With what you're looking to do the statement will look something like this:

SELECT p.ID
       , CONCAT(p.FirstName, " ", p.LastName) AS PatientName 
       , t.TreatmentName
FROM   patients p
       LEFT JOIN treatment_type t ON p.ID = t.PatientID;

Here's an sqlfiddle to show that. The tables are named exactly like yours so you'll need to adjust them to fit your database. If you're just making this database you should really think about developing some kind of consistent naming convention, yours seem a bit scattered at the moment.

EDIT: As per carlosh12's comment on OP, you CAN do this kind of thing with a pivot table, but I'm not sure it's what you'd need for this situation. It's much faster and easier to just do it outside SQL as detailed here.

EDIT 2 Sorry, forgot to link to my SQLfiddle. It's there now. Here is an edit where I included an ORDER BY statement to answer your comment.

OneHoopyFrood
  • 3,829
  • 3
  • 24
  • 39