I have the following tables:
matters(matterid, mattername, refno)
mattersjuncstaff(junked, matterid, staffid, lead)
staff(staffid, staffname)
A matter may have a number of staff associated with it and a number of those staff will be marked as ‘leads’ i.e. they will have a ‘Y’ in the ‘lead’ field.
I wish to show a table that has a list of matters, the matter name and ref no and those staff marked as leads, ideally in a single row. So it would look something like:
reference | mattername | Lead Staff |
ABC1 | matter abc & Co | Fred Smith, Jane Doe, Naomi Watts |
etc
I am using the code below but this only displays one person with the lead field marked Y.
SELECT refno, mattername, matters.matterid, staffname
FROM matters
INNER JOIN matterjuncstaff
USING (matterid)
Inner join staff
using (staffid)
Inner join matterjuncactions
On matterjuncactions.matterid = matters.matterid
WHERE lead = 'Y'
GROUP BY matters.matterid, nickname
Can anyone tell me how I can I get round this?
You want to concatenate values from a join and represent that as a field in the result set. GROUP_CONCAT function is suited for such queries:
SELECT m.matterid, m.refno, m.mattername, GROUP_CONCAT(s.staffname) AS LeadStaff
FROM matters m
LEFT JOIN matterjuncstaff mjs ON mjs.matterid = m.matterid AND lead = 'Y'
LEFT JOIN staff s ON s.staffid = mjs.staffid
GROUP BY m.matterid, m.refno, m.mattername
The join changed to LEFT and lead = 'Y' moved there, otherwise you will lose matters with no lead staffs.
Use INNER JOIN if you only want matters having some lead staff.
I have removed matterjuncactions as you did not give its info.
Use the GROUP_CONCAT() function in mysql to concatenate values from a query into a single string.
For example you could select a row for each matter and append a column with all the concatenated lead staff names as follows:
SELECT m.refno,
m.mattername,
(Select GROUP_CONCAT(distinct staffname SEPARATOR ', ')
from mattersjuncstaff js
join staff s
on s.staffid = js.staffid
where js.lead = 'Y'
and js.matterid = m.matterid) as LeadStaffMembers
FROM matters m
Update
Here is the same example, but with an added column showing staff members that are not the lead.
SELECT m.refno,
m.mattername,
(Select GROUP_CONCAT(distinct staffname SEPARATOR ', ')
from mattersjuncstaff js
join staff s
on s.staffid = js.staffid
where js.lead = 'Y'
and js.matterid = m.matterid) as LeadStaffMembers,
(Select GROUP_CONCAT(distinct staffname SEPARATOR ', ')
from mattersjuncstaff js
join staff s
on s.staffid = js.staffid
where js.lead <> 'Y'
and js.matterid = m.matterid) as NonLeadStaffMembers
FROM matters m
Related
Hi I have a table called Engineers and a table called Post_Codes
When I use the following sql I get a list of engineers and the postcodes associated with them by using the Group Concat statement but I cannot figure out how to also include in another Group Concat (if indeed I need one) to also list in another field called Secondary_Post_Codes_Assigned those post codes linked to the same engineer via the Secondary_Engineer_id field.
SELECT
Engineer.Engineer,GROUP_CONCAT(Post_Code SEPARATOR ', ') as Post_Codes_Assigned,
Engineer.Region,
Engineer.active,
Engineer.Engineer_id
FROM Engineer INNER JOIN Post_Code ON Engineer.Engineer_id = Post_Code.Engineer_id
GROUP BY Engineer_id
What I need is output similar to this.
Engineer_id | Post_Codes_Assigned | Secondary_Post_Codes_Assigned
----------
1 | AW, AW3 | B12 |
2 | B12 | AW, CV12 |
I hope this is clear as I am pretty new to mysql.
Regards
Alan
You are already joining the primary post codes and list them, now do the same with the secondary ones.
SELECT
e.Engineer,
GROUP_CONCAT(DISTINCT pc1.Post_Code) AS Primary_Post_Codes_Assigned,
GROUP_CONCAT(DISTINCT pc2.Post_Code) AS Secondary_Post_Codes_Assigned,
e.Region,
e.active,
e.Engineer_id
FROM Engineer e
JOIN Post_Code pc1 ON e.Engineer_id = pc1.Engineer_id
JOIN Post_Code pc2 ON e.Engineer_id = pc2.Secondary_Engineer_id
GROUP BY e.Engineer_id;
As you see, you need DISTINCT because when selecting all primary and all secondary postcodes, you are getting rows for all combinations of them in the intermediate result. So you must get rid of duplicates. For this reason ist is better to aggregate before joining. (Which I generally consider a good idea, so you may want to make this a habit when working with aggregates.)
SELECT
e.Engineer,
pc1.Post_Codes AS Primary_Post_Codes_Assigned,
pc2.Post_Codes AS Secondary_Post_Codes_Assigned,
e.Region,
e.active,
e.Engineer_id
FROM Engineer e
JOIN
(
SELECT Engineer_id, GROUP_CONCAT(Post_Code) AS Post_Codes
FROM Post_Code
GROUP BY Engineer_id
) pc1 ON e.Engineer_id = pc1.Engineer_id
JOIN
(
SELECT Secondary_Engineer_id, GROUP_CONCAT(Post_Code) AS Post_Codes
FROM Post_Code
GROUP BY Secondary_Engineer_id
) pc2 ON e.Engineer_id = pc2.Secondary_Engineer_id;
A third option would be subqueries in the SELECT clause. I usually prefer them to be in the FROM clause as shown, because then it is easy to add more columns to the subqueries, which is not possible in the SELECT clause.
SELECT
e.Engineer,
(
SELECT GROUP_CONCAT(pc1.Post_Code)
FROM Post_Code pc1
WHERE pc1.Engineer_id = e.Engineer_id
) AS Primary_Post_Codes_Assigned,
(
SELECT GROUP_CONCAT(pc2.Post_Code)
FROM Post_Code pc2
WHERE pc2.Secondary_Engineer_id = e.Engineer_id
) AS Secondary_Post_Codes_Assigned,
e.Region,
e.active,
e.Engineer_id
FROM Engineer e;
I am using mysql to perform queries. have the following 7 tables.
appointment //non-atomic, eg. values -> 1,7,3
gender //atomic value
module //non-atomic, eg. values -> 12,33
program
rank
staff
student
I have tried 'concat', 'find_in_set' & 'in' functions but cannot get it to work. How may I display multiple values # relations 'appointment' & 'module'?
The following statement is the closest i can get. Please let me know if additional details are required, thank you.
SELECT sta.staName
, r.rank
, sta.appointmentID
, a.appointment
, m.moduleCode
FROM staff AS sta
JOIN rank AS r
ON (sta.rankID = r.rankID)
JOIN appointment AS a
ON (sta.appointmentID = a.appointmentID)
JOIN module AS m
ON (sta.teachModuleID = m.moduleID)
WHERE sta.genderID = 1;
SELECT sta.staName, r.rank, sta.appointmentID,
group_concat(distinct a.appointment) as appointments,
group_concat(distinct m.moduleCode) as moduleCodes
FROM staff AS sta
INNER JOIN rank AS r ON sta.rankID = r.rankID
INNER JOIN appointment AS a ON find_in_set(sta.appointmentID, a.appointmentID) > 0
INNER JOIN module AS m ON find_in_set(sta.teachModuleID, m.moduleID) > 0
WHERE sta.genderID = 1
GROUP BY sta.staName, r.rank, sta.appointmentID
I want to get members and their photos. Every member has 2 photos. (I am not talking about profile image)
There are 2 tables named as Members and MemberPhotos.
Here is my query which doesn't work(expectedly):
SELECT
M.Name as MemberName,
M.LastName as MemberLastName,
(
SELECT
TOP 1
MP.PhotoName
FROM
MemberPhotos MP
WHERE
MP.MemberID = M.ID
AND
MP.IsFirst = 1
) as MemberFirstPhoto,
(
SELECT
TOP 1
MP.PhotoName
FROM
MemberPhotos MP
WHERE
MP.MemberID = M.ID
AND
MP.IsFirst = 0
) as MemberSecondPhoto,
FROM
Members M
Maybe somebody going to say that I should use inner join instead, I don't want to use inner join, if I use it I get data multiple like:
Name Surname PhotoName
Bill Gates bill.png
Bill Gates bill2.png
Steve Jobs steve.jpg
Steve Jobs steve2.jpg
What do you recommend me about query?
Thanks.
EDIT:
Here is the output I want to get:
Name Surname FirstPhoto SecondPhoto
Bill Gates bill.png bill2.png
Steve Jobs steve.jpg steve2.png
The only issue with your example query is that you have an extra comma after
as MemberSecondPhoto
If you remove this it works fine.
SQL Fiddle with demo.
However, while that query is working now, because you know that each member only has two photos, you can use a much simpler query:
SELECT
M.Name as MemberName,
M.LastName as MemberLastName,
MPF.PhotoName as MemberFirstPhoto,
MPS.PhotoName as MemberSecondPhoto
FROM Members M
LEFT JOIN MemberPhotos MPF ON M.ID = MPF.MemberID AND MPF.IsFirst = 1
LEFT JOIN MemberPhotos MPS ON M.ID = MPS.MemberID AND MPS.IsFirst = 0
SQL Fiddle with demo.
I have a syntax issue with my use of GROUP_CONTACT.
With a sql statement that looks like this:
SELECT
s.school_code
, s.school_name
,st.subject
,sg.subgroup
,GROUP_CONCAT(IF(r.year=2012,a.proficiency_index,NULL)) AS pi_2012
,GROUP_CONCAT(IF(r.year=2013,a.proficiency_index,NULL)) AS pi_2013
FROM
ayp_data a
INNER JOIN
report_year r ON
a.report_year_id = r.id
INNER JOIN
school s ON
a.school_code_id = s.id
INNER JOIN
sub_group sg ON
a.subgroup_id = sg.id
INNER JOIN
`subject` st ON
a.subject_id = st.id
GROUP BY
report_year_id,
s.school_code
, s.school_name
,st.subject
,sg.subgroup
HAVING
s.school_name = 'Moody Elementary School' AND
`subject` = 'Mathematics' AND
`subgroup` = 'All Students'
I am getting results like this:
SCHOOL_CODE SCHOOL_NAME SUBJECT SUBGROUP PI_2012 PI_2013
0065 Moody Elementary School Mathematics All Students 9.640000343322754 (null)
0065 Moody Elementary School Mathematics All Students (null) 10.920000076293945
I want to merge the two rows into one and put non-null field values PI_2012 and PI_2013 on the same line.
I thought I could do that with GROUP_CONTACT; but it's not doing as I thought it would.
How could I use GROUP_CONCAT to merge these fields?
Or, is there an even smarter way to do this?
I have the full schema and query here on SQL Fiddle.
If you don't want separate years to appear in separate rows, then you need to remove report_year_id from the GROUP BY clause. That is — you need to change this:
GROUP BY
report_year_id,
s.school_code
, s.school_name
,st.subject
,sg.subgroup
to this:
GROUP BY
s.school_code
, s.school_name
,st.subject
,sg.subgroup
I have 3 tables
person (id, name)
area (id, number)
history (id, person_id, area_id, type, datetime)
In this tables I store the info which person had which area at a specific time. It is like a salesman travels in an area for a while and then he gets another area. He can also have multiple areas at a time.
history type = 'I' for CheckIn or 'O' for Checkout.
Example:
id person_id area_id type datetime
1 2 5 'O' '2011-12-01'
2 2 5 'I' '2011-12-31'
A person started traveling in area 5 at 2011-12-01 and gave it back on 2011-12-31.
Now I want to have a list of all the areas all persons have right now.
person1.name, area1.number, area2.number, area6.name
person2.name, area5.number, area9.number
....
The output could be like this too (it doesn't matter):
person1.name, area1.number
person1.name, area2.number
person1.name, area6.number
person2.name, area5.number
....
How can I do that?
This question is, indeed, quite tricky. You need a list of the entries in history where, for a given user and area, there is an 'O' record with no subsequent 'I' record. Working with just the history table, that translates to:
SELECT ho.person_id, ho.area_id, ho.type, MAX(ho.datetime)
FROM History AS ho
WHERE ho.type = 'O'
AND NOT EXISTS(SELECT *
FROM History AS hi
WHERE hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
)
GROUP BY ho.person_id, ho.area_id, ho.type;
Then, since you're really only after the person's name and the area's number (though why the area number can't be the same as its ID I am not sure), you need to adapt slightly, joining with the extra two tables:
SELECT p.name, a.number
FROM History AS ho
JOIN Person AS p ON ho.person_id = p.id
JOIN Area AS a ON ho.area_id = a.id
WHERE ho.type = 'O'
AND NOT EXISTS(SELECT *
FROM History AS hi
WHERE hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
);
The NOT EXISTS clause is a correlated sub-query; that tends to be inefficient. You might be able to recast it as a LEFT OUTER JOIN with appropriate join and filter conditions:
SELECT p.name, a.number
FROM History AS ho
JOIN Person AS p ON ho.person_id = p.id
JOIN Area AS a ON ho.area_id = a.id
LEFT OUTER JOIN History AS hi
ON hi.person_id = ho.person_id
AND hi.area_id = ho.area_id
AND hi.type = 'I'
AND hi.datetime > ho.datetime
WHERE ho.type = 'O'
AND hi.person_id IS NULL;
All SQL unverified.
You're looking for results where each row may have a different number of columns? I think you may want to look into GROUP_CONCAT()
SELECT p.`id`, GROUP_CONCAT(a.`number`, ',') AS `areas` FROM `person` a LEFT JOIN `history` h ON h.`person_id` = p.`id` LEFT JOIN `area` a ON a.`id` = h.`area_id`
I haven't tested this query, but I have used group concat in similar ways before. Naturally, you will want to tailor this to fit your needs. Of course, group concat will return a string so it will require post processing to use the data.
EDIT I thikn your question has been edited since I began responding. My query does not really fit your request anymore...
Try this:
select *
from person p
inner join history h on h.person_id = p.id
left outer join history h2 on h2.person_id = p.id and h2.area_id = h.area_id and h2.type = 'O'
inner join areas on a.id = h.area_id
where h2.person_id is null and h.type = 'I'