How to get the TeamCount and TeamLead Name currectly
Teams | TeamCount | TeamLead Name
-------------------------------------
| Team1 | 2 | NULL
| Team2 | 2 | NULL
| Team1 | 1 | Prashanth
Some times Team may or may not have the team lead.
So we just have to show the TeamLead name as null,
if team lead is not found for the team
I need some help to get the out as below
Teams | TeamCount | TeamLead Name
---------------------------------
Team1 | 3 | Prashanth
Team2 | 2 | NULL
Here you are:
MySQL:
select team as teamId, sum(teamcount) as teamcount,
(select teamleadname from teams
where teamId = teams.team and teamleadname is not null
limit 1) as teamleadname
from teams
group by team
http://sqlfiddle.com/#!9/5889d/39
SQl Server:
declare #teams TABLE(Team varchar(20), TeamCount int, TeamLeadName varchar(20));
INSERT INTO #teams
VALUES
('Team1', 2, null),
('Team2', 2, null),
('Team1', 1, 'Prashanth')
select l.Team, l.TeamCount, r.TeamLeadName
from
(select Team , sum(TeamCount) as TeamCount from #teams group by Team) as l
left outer join
(select Team, TeamLeadName
from
(select Team, TeamLeadName, row_number() over(partition by Team order by TeamLeadName desc) as roworder
from #teams) as o where o.roworder = 1
) as r
on l.Team = r.Team
Hope this help.
...and here you go!
create table test2 as
select distinct c.teams,sum(c.TeamCount) as SUM,c.TeamName
from
(select a.Teams,a.TeamCount,b.TeamName from team as a
left outer join
(select * from team where TeamName ne "") as b
on a.Teams = B.Teams) as c
group by c.Teams;
You should try to develop these solutions by working from the inside out and build the query in steps
You can do this with a LEFT OUTER join between Team and TeamMembers, and including the IsLead into the join criterion, before grouping by the Team name - this will exclude non-leads:
SELECT T.Name, MIN(TM.TName) AS Lead
FROM Teams T
LEFT OUTER JOIN TeamMembers TM
ON TM.TeamId = T.Id AND TM.IsLead = 1
GROUP BY T.Name;
SqlFiddle here
The TeamCount doesn't seem to make sense here - if you can elaborate on how you intend deriving it, perhaps we can help here
PS : You've tagged both MySql and Oracle - don't do this please.
Related
I've got three tables as shown below - ideally it wouldn't be laid out like this but currently no power change it.
Team User Member
ID | Name ID | TeamId | Email ID | TeamId | Email
----------
1 | Team A 1 | 1 | a#email.com 1 | 1 | a#email.com
2 | Team B 2 | 1 | b#email.com 2 | 1 | b#email.com
3 | Team C 3 | 1 | c#email.com
I need to be able to get the combined count of users and members in each team, uniquely based on their email address.
So for example, Team A would have a unique count of combined members and users of 3.
An entry may exist in either the user table OR the member table, or in both for each email.
The outcome of the query would be TeamName and TotalUsers.
Any help with this type of query would be greatly appreciated.
Use UNION to collect all the distinct combinations of team ids and emails from User and Member and do a LEFT join of Team to that resultset and aggregate:
SELECT t.id, t.name,
COUNT(email) count
FROM Team t
LEFT JOIN (
SELECT teamid, email FROM User
UNION
SELECT teamid, email FROM Member
) e ON e.teamid = t.id
GROUP BY t.id;
you can UNION members and User table, so that duplicates would be removed
And then join it to the temas table
SELECT
t1.Name, COUNT(DISTINCT Email)
FROM
Team t1
JOIN
( SELECT TeamId , Email FROM User
UNION SELECT TeamId , Email FROM Member) t2 ON t2.TeamId = t1.ID
GROUP BY t1.Name
I'm currently new to queries and below I have a query that I have made
QUERY:
select TITLE_ID, TITLE,NAME, JOB_CATEGORY AS ROLE
FROM MOVIES
NATURAL JOIN NEW_NAMES
WHERE JOB_CATEGORY = 'writer'
OR JOB_CATEGORY = 'director'
ORDER BY TITLE_ID ASC;
Which Displays:
TITLE_ID | TITLE | NAME | ROLE |
753595 | 2F2F | ROB | WRITER |
753595 | 2F2F | YAS | DIRECTOR|
However I would like it to display in this format below:
TITLE_ID | TITLE | WRITER | DIRECTOR|
753595 | 2F2F | ROB | YAS |
You join your NEW_NAMES table in twice. Once for director, once for writer. When you join a table more than once it's necessary that you give the table an Alias, here we use writer and director.
select TITLE_ID, TITLE,writer.NAME as writer_name, director.NAME as director_name
FROM MOVIES
LEFT OUTER JOIN NEW_NAMES as writer
ON MOVIES.TITLE_ID = writer.TITLE_ID
AND writer.JOB_CATEGORY = 'writer'
LEFT OUTER JOIN NEW_NAMES as director
ON MOVIES.TITLE_ID = director.TITLE_ID
AND director.JOB_CATEGORY = 'director'
ORDER BY TITLE_ID ASC;
I've made some assumptions in those ON clauses about which columns in your tables you are joining on. You may need to edit that.
According to error message you got, it is about Oracle, not MySQL.
Anyway, such a (classic?) principle should work: aggregate!
SQL> with
2 -- sample data
3 movies (title_id, title_name) as
4 (select 753595, '2F2F' from dual union all
5 select 123456, '1Z1Z' from dual
6 ),
7 new_names (title_id, job_category, name) as
8 (select 753595, 'writer', 'ROB' from dual union all
9 select 753595, 'director', 'YAS' from dual
10 )
11 -- query you need
12 select m.title_id,
13 m.title_name,
14 max(case when n.job_category = 'writer' then n.name end) as writer,
15 max(case when n.job_category = 'director' then n.name end) as director
16 from movies m left join new_names n on m.title_id = n.title_id
17 group by m.title_id, m.title_name
18 order by m.title_id;
TITLE_ID TITL WRI DIR
---------- ---- --- ---
123456 1Z1Z
753595 2F2F ROB YAS
SQL>
I am trying to write a simple query that will display all projects and their total number of team members, sorted alphabetically by project. If a project does not have assigned team members, that project should still be included in the output.
CREATE TABLE Project ( ID INT IDENTITY(1,1), ProjectName VARCHAR(50), DueDate
DATE)
CREATE TABLE Employee ( ID INT IDENTITY(1,1), EmployeeName VARCHAR(50) )
CREATE TABLE ProjectAssignment ( ID INT IDENTITY(1,1), ProjectID INT,
EmployeeID INT)
INSERT INTO Project VALUES ('Alpha', '1/1/2040'), ('Bravo', '3/1/2030'),
('Charlie', '2/1/2017'), ('Delta', '4/1/2017')
INSERT INTO Employee VALUES ('John'), ('Beth'), ('Tom'), ('Kim'), ('Jack')
INSERT INTO ProjectAssignment VALUES (1, 1), (1, 2), (2, 2), (2, 3), (3,
3), (3, 4), (1, 3)
--TABLE Project:
ID ProjectName DueDate
1 Alpha 2040-01-01
2 Bravo 2030-03-01
3 Charlie 2017-02-01
4 Delta 2017-04-01
--TABLE Employee:
ID EmployeeName
1 John
2 Beth
3 Tom
4 Kim
5 Jack
--TABLE ProjectAssignment:
ID ProjectID EmployeeID
1 1 1
2 1 2
3 2 2
4 2 3
5 3 3
6 3 4
7 1 3
Here is my wrong query:
SELECT n.ProjectName, Count(t.ProjectID) as NumMembers
FROM Project p
LEFT JOIN ProjectAssignment t ON p.EmployeeID = t.EmployeeID
LEFT JOIN employee e ON e.ProjectID = t.ProjectID
GROUP BY n.Project
ORDER BY n.Project
Desired Result:
| ProjectName | NumMembers |
+-------------+-------------+
| Alpha | 3 |
| Bravo | 2 |
| Charlie | 2 |
| Delta | null |
Please try this Mysql query. This will resolve your issue. We dont' require employee table join. If you are not taking any data from employee table then don't add employee table in join.
SELECT
p.name AS ProjectName,
Count( t.employeeID ) AS NumMembers
FROM
Project p
LEFT JOIN ProjectAssignment t ON p.id = t.projectID
GROUP BY
p.name
Output:
Project name NumMembers
Alpha 3
Bravo 2
Charlie 2
Delta 0
Few things
LEFT JOIN ProjectAssignment t ON p.EmployeeID = t.EmployeeID
is wrong as you can see p.EmployeeID do not exists on table Project
your join to employee is not needed at all
also finally i do not know how your fields names are. you post Name in sample data and projectName is used in your query and ddl (changed to your DDL instead of your query)
SELECT p.ProjectName, Count(DISTINCT pa.EmployeeID) as NumMembers
FROM Project p
LEFT JOIN ProjectAssignment pa ON p.ID = pa.ProjectID
GROUP BY p.ID, p.ProjectName
ORDER BY p.ProjectName
http://sqlfiddle.com/#!18/36df5/1
SELECT n.ProjectName, Count(t.ProjectID) as NumMembers FROM Project n LEFT JOIN ProjectAssignment t ON n.id = t.ProjectID GROUP BY t.ProjectID ORDER BY n.ProjectName
run this query
Just use this ( it seems join conditions are mixed ):
SELECT p.ProjectName, Count(t.ProjectID) as NumMembers
FROM Project p
LEFT JOIN ProjectAssignment t ON p.ID = t.ProjectID
LEFT JOIN employee e ON t.EmployeeID = e.ID
GROUP BY p.ProjectName
ORDER BY p.ProjectName;
ProjectName NumMembers
Alpha 3
Bravo 2
Charlie 2
Delta 0
SQL Fiddle Demo
all! I'm taking database class and have couple of questions that is so confusing to me. down below is my table
Student(S_ID, S_FIRST_NAME, S_LAST_NAME, S_MAJOR)
Course(C_ID, C_NAME, C_INST_NAME, C_ROOM)
takes(S_ID,C_ID)
Q-1.i want to select all the student_id who takes all courses taught by Davidson. I tried with this code
select s.S_ID from student s inner join (select t.S_ID from takes t inner join
course c on t.C_ID = c.C_ID group by t.S_ID having sum(case when c.C_INST_NAME
= 'Davidson' then 1 else 0 end) = 3) t on s.S_ID = t.S_ID;
it works because i know how many classes Davidson teaches(in my case 3). how do we write the query if we don't know how many classes he teaches?
Q-2. i want to select all the instructors who teach atleast 3 classes. For this question i did following
select distinct C_INST_NAME from course where C_ID >= 3;
+-------------+
| C_INST_NAME |
+-------------+
| Peterson |
| Davidson |
| Jackson |
| Hanney |
+-------------+
But i got all the instructor, any help would be appreciated thank you!
Q1.
SELECT
S_ID, GROUP_CONCAT(C_ID ORDER BY C_ID ASC)
FROM
takes
WHERE
GROUP_CONCAT(C_ID ORDER BY C_ID ASC) = (
SELECT
GROUP_CONCAT(Course.C_ID ORDER BY C_ID ASC)
FROM
Course
WHERE
Course.C_INST_NAME = "Davidson"
)
GROUP BY
S_ID
Q2.
SELECT
COUNT(C_ID) AS "numClassesTaught", Course.C_INST_NAME
FROM
Course
GROUP BY
Course.C_INST_NAME
HAVING
numClassesTaught >= 3
Those should both work.
I have these two tables:
popular_song
song_name | rate | country_id
------------------------------
Tic Tac | 10 | 1
Titanic | 2 | 1
Love Boat | 8 | 2
Battery | 9 | 2
country
conutry_id | country
--------------------------
1 | United States
2 | Germany
What I'd like to achieve is to get the most poular song in each country, e.g.:
song_name | rate | country
--------------------------
Tic Tac | 10 | United States
Battery | 9 | Germany
I've tried this query:
SELECT MAX(rate), song_name, country
FROM popular_song ps JOIN country cnt
ON ps.country_id = cnt.country_id
GROUP BY country
But this doesn't work. I've tried looking at questions like "Order by before group by" but didn't find an answer.
Which mysql query could achieve this result?
You can use another self join to popular songs table with the max rating
SELECT ps.*,cnt.country
FROM popular_song ps
JOIN (SELECT MAX(rate) rate, country_id FROM popular_song GROUP BY country_id) t1
ON(ps.country_id = t1.country_id and ps.rate= t1.rate)
JOIN country cnt
ON ps.country_id = cnt.conutry_id
See Demo
There is a trick that you can use with substring_index() and group_concat():
SELECT MAX(rate),
substring_index(group_concat(song_name order by rate desc separator '|'), '|', 1) as song,
country
FROM popular_song ps JOIN
country cnt
ON ps.country_id = cnt.country_id
GROUP BY country;
EDIT:
If you have big tables and lots of songs per country, I would suggest the not exists approach:
select rate, song country
from popular_song ps join
country cnt
on ps.country_id = cnt.country_id
where not exists (select 1
from popular_song ps2
where ps2.country_id = ps.country_id and ps2.rate > ps.rate
);
Along with an index on popular_song(country_id, rate). I recommended the group_concat() approach because the OP already had a query with a group by, so the trick is the easiest to plug into such a query.
Here is another way I'v learned from #Gordon Linoff. Here is that question you could learn too.
SELECT ps.*,cnt.country
FROM
(SELECT popular_song.*,
#rownum:= if (#c = country_id ,#rownum+1,if(#c := country_id, 1, 1) )as row_number
FROM popular_song ,
(SELECT #c := '', #rownum:=0) r
order by country_id, rate desc) as ps
LEFT JOIN country cnt
ON ps.country_id = cnt.conutry_id
WHERE ps.row_number = 1
This is the way of implementing row_number()(Partition by ...) window function in MySql.
You can do this with EXISTS like this:
SELECT rate, song_name, cnt.country_id
FROM popular_song ps JOIN country cnt
ON ps.country_id = cnt.country_id
WHERE NOT EXISTS
(SELECT * FROM popular_song
WHERE ps.country_id = country_id AND rate > ps.rate)
It is not specified in the question whether two songs can be returned per country if their rating is the same. Above query will return several records per country if ratings are not unique at country level.