I have 2 SQL queries. I have looked at some of the examples on the site and still confused about how to combine them. I would like both queries in one table.
Thank you for your help
Jeremy
SELECT DISTINCT
"exStudent"."Student_StudentID" AS StudentID,
"exPerson"."Person_FirstName" + ' ' + "exPerson"."Person_LastName" AS FirstLast,
"exPerson"."Person_LastName" AS LastName,
"exPerson"."Person_FirstName" AS FirstName,
"exPerson"."Person_Gender" AS Gender,
ISNULL("exStudentEnrollment"."StudentEnrollment_Building",'') AS Building,
"exStudentEnrollment"."StudentEnrollment_Grade" AS Grade,
ISNULL("exStudentEnrollment"."StudentEnrollment_Homeroom",'') AS Homeroom,
ISNULL("exStudentEnrollment"."StudentEnrollment_HomeroomTeacher",'') AS HRTeacher
FROM
"exStudent" "exStudent"
INNER JOIN
"exPerson" "exPerson" ON "exStudent"."ForeignKey" = "exPerson"."ForeignKey"
INNER JOIN
"exPersonMailing" "exPersonMailing" ON "exPerson"."ForeignKey" = "exPersonMailing"."ForeignKey"
INNER JOIN
"exStudentEnrollment" "exStudentEnrollment" ON "exStudent"."ForeignKey" = "exStudentEnrollment"."ForeignKey"
WHERE
"exStudentEnrollment"."StudentEnrollment_Current" = 1
AND "exStudentEnrollment"."StudentEnrollment_Homeroom" <> ''
AND "exStudentEnrollment"."StudentEnrollment_SchoolYear"= (DATENAME(YEAR, '07-01-' + CONVERT(VARCHAR, YEAR(DATEADD(MONTH, -6, GETDATE())))) + '-' + DATENAME(YEAR, '06-30-' + CONVERT(VARCHAR, YEAR(DATEADD(MONTH, +6, GETDATE())))))
ORDER BY
Homeroom, Gender, LastName, FirstName
This is the second query:
select *
from UserDefinedScreen --ID for "Lunch IDs" is 2
select *
from UserDefinedField
where UserDefinedScreen_ID = 2 --ID for "Lunch ID" field is 3
select s.StudentID, pudf.Value
from PersonUserDefinedField pudf
join PersonUserDefinedScreen puds on pudf.PersonUserDefinedScreen_ID = puds.ID
join Person p on puds.Person_ID = p.ID
join Student s on s.Person_ID = p.ID
where pudf.UserDefinedField_ID = 3
Related
I'm trying to run the following query:
select U1.userEmail, U1.firstname + ' ' + U1.surName as fullname
from tblUser as U1 inner join tblDriver as D on U1.userEmail= D.userEmail
inner join tblGetAsk as GA on GA.userEmail = D.userEmail
where not exists (select 1 from tblRideRating as R where R.userEmail = U1.userEmail)
and count(GA.userEmail) >= 3
But I'm getting the following error:
Error 1: could not prepare statement (1 misuse of aggregate function
COUNT())
What I'm actually want to do is: Select only users who are also a driver and have 0 records in tblRideRating, and have at least 3 records in tblGetAsk.
You can use aggregation.
Group by user and use a HAVING clause:
select U1.userEmail, U1.firstname + ' ' + U1.surName as fullname
from tblUser as U1
inner join tblDriver as D on D.userEmail= U1.userEmail
inner join tblGetAsk as GA on GA.userEmail = U1.userEmail
where not exists (select 1 from tblRideRating as R where R.userEmail = U1.userEmail)
group by U1.userEmail, U1.firstname + ' ' + U1.surName
having count(GA.userEmail) >= 3
If you have duplicate emails for each user in tblGetAsk, maybe you should change to:
having count(distinct GA.userEmail) >= 3
You could also aggregate in tblGetAsk and then join:
select U1.userEmail, U1.firstname + ' ' + U1.surName as fullname
from tblUser as U1
inner join tblDriver as D on D.userEmail= U1.userEmail
inner join (
select userEmail
from tblGetAsk
group by userEmail
having count(*) >= 3
) as GA on GA.userEmail = U1.userEmail
where not exists (select 1 from tblRideRating as R where R.userEmail = U1.userEmail)
I have this query
SELECT ID,
SUBSTRING(( SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id
FOR XML PATH('')),2,200000) AS CompanyIdList
FROM CompanyProducts NP
I would like to add the SELECT into an INNER JOIN which I will add to my select to check if the return is null or zero
it will be something like this
SELECT ID,
SUBSTRING(( SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id
FOR XML PATH('')),2,200000) AS CompanyIdList,
CompanyIdCount --this will be null or a real value
FROM cmp.CompanyProducts NP
INNER JOIN(SELECT DISTINCT A.CompanyProductsId,
(SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id ) AS CompanyIdCount
FROM cmp.CompanyProducts A
)E ON NP.CompanyNotificationId = E.CompanyNotificationId
How can I get the inner JOIN to incident null for no records or 1 record or more? THanks
I have the following (moderately epic query) which I have been writing
Select *
from
(Select
Salutation,
FirstName, LastName, FullName,
PhotoUrl, CountryCode, Email, Birthday,
Gender, HomePhone, M.MemberId, IDType, JoinDate,
HomeLocation, HomeLocationId,
Region.Name as RegionName,
M.MembershipId,
coalesce(case
when Package.PackageIsReoccuring = 1 then 'Recurring'
when Package.PackageIsSession = 1 then 'Paid In Full'
when membership.TotalPrice = 0 then 'Free'
when Package.PackagePayInFull = 1 then 'Paid In Full'
end, 'N/A') as PackageTerm,
coalesce(PackageType.Name, 'N/A') as PackageType,
coalesce(membershipstate.name, 'N/A') as MembershipState,
MembershipStartDate =
case
when membership.StartDate IS NULL
then ''
else CONVERT(varchar(50),membership.StartDate)
end,
MembershipEndDate =
case
when membership.EndDate IS NULL
then ''
else CONVERT(varchar(50),membership.EndDate)
end,
Region.Id as RegionId
from
(select
AspNetUsers.Salutation,
AspNetUsers.FirstName, AspNetUsers.LastName,
CONCAT (AspNetUsers.FirstName, ' ', AspNetUsers.LastName) as FullName,
AspNetUsers.PhotoUrl, AspNetUsers.CountryCode, AspNetUsers.Email,
AspNetUsers.Birthday, AspNetUsers.Gender,
AspNetUsers.HomePhone as HomePhone,
Member.Id as MemberId, Member.IDType, Member.JoinDate,
HomeLocation.Name as HomeLocation,
HomeLocation.Id as HomeLocationId,
(case when (select top 1 id from membership where membership.memberid = Member.id and (membership.membershipstateid = 1 or membership.membershipstateid = 6)) IS NULL Then (select top 1 id from membership where membership.memberid = Member.id order by membership.enddate desc) ELSE (select top 1 id from membership where membership.memberid = Member.id and (membership.membershipstateid = 1 or membership.membershipstateid = 6)) END) as MembershipId
from
AspNetUsers
join
Member on AspNetUsers.id = Member.aspnetuserid
join
Location as HomeLocation on Member.HomeLocationId = HomeLocation.id) as M
left join
Membership on M.MembershipId = Membership.Id
left join
Package on Membership.packageid = Package.Id
left join
PackageType on Package.packagetypeid = PackageType.Id
left join
MembershipState on Membership.membershipstateid = MembershipState.Id
left join
Region on Membership.RegionId = Region.Id) as Result
order by
Result.LastName desc
I have a final join table which I want to use which is a many-to-many relationship on Region. Region has a Join Table (RegionLocations) which is a join between Region and Locations.
With my query below I would like to get all results where the HomeLocationId = 2 OR he has a LocationId (from RegionLocations) which also contains 2. The RegionId is a nullable value and isn't always populated.
How can I get this? Do I need to return values into a CSV? This final hurdle is a battle..
Thanks
You could extend this:
left join
Region on Membership.RegionId = Region.Id) as Result
to this:
left join
Region on Membership.RegionId = Region.Id
where M.HomeLocationId = 2
or Region.Id in (select RegionId from RegionLocation where LocationId = 2)
) as Result
Some other remarks about your query:
The fields MembershipStartDate and MembershipEndDate can be evaluated more concisely as:
COALESCE(CONVERT(varchar(50),membership.StartDate), '') as MembershipStartDate,
COALESCE(CONVERT(varchar(50),membership.EndDate), '') as MembershipEndDate,
The inner field MembershipId is defined with three sub-queries in a case when, which can be shortened to just one query. It uses in instead of an or condition, and puts it in the order by clause in a way that gets the priority right:
(select top 1 id
from membership
where membership.memberid = Member.id
order by case when membership.membershipstateid in (1,6) then 0 else 1 end,
membership.enddate desc
) as MembershipId
Finally, if you just have an outer query that performs a select * from (...) order by, then why not skip that outer query and perform that order by on the inner query direcly?
I have a query that I am running to pull hours from a database. I'm using 2 tables Employee_TB and Payroll_Hours_TB. The query is working, however it's not displaying active employees with "0" hours. I would like the query to show those employees who are active Employee_Tb.Active_Flag = 1 with hours, and 0 hours for the date range.
SELECT
REPLACE(REPLACE(Employee_Tb.First_Name, '.', ''), ' ', '') AS FirstName,
REPLACE(REPLACE(Employee_Tb.Last_Name, '.', ''), ' ', '') AS LastName,
Employee_Tb.Home_Store_Id, Employee_Tb.Payroll_Id,
SUM(Payroll_Hours_Tb.Hours_Worked) AS RegHours
FROM Employee_Tb
LEFT OUTER JOIN Payroll_Hours_Tb ON Employee_Tb.Employee_Id = Payroll_Hours_Tb.Employee_Id
WHERE (Payroll_Hours_Tb.Work_Date BETWEEN #startdate AND #enddate)
AND (Employee_Tb.Active_Flag = 1)
GROUP BY Employee_Tb.Payroll_Id, Employee_Tb.First_Name, Employee_Tb.Last_Name, Employee_Tb.Home_Store_Id
Move the following condition from the where clause to the on clause:
(Payroll_Hours_Tb.Work_Date BETWEEN #startdate AND #enddate)
...like so:
-- simplified column list for demonstration
select
e.Employee_Id
,coalesce(sum(h.Hours_Worked), 0) as RegHours
from Employee_Tb as e
left join Payroll_Hours_Tb as h
on e.Employee_Id = h.Employee_Id
and h.Work_Date between #startdate and #enddate
where e.Active_Flag = 1
group by e.Employee_Id
Otherwise you're filtering the entire set after the join.
Is it showing null instead of 0?
Maybe you can try something like
ISNULL(SUM(Payroll_Hours_Tb.Hours_Worked), 0) AS RegHours
I need to limit the row number to one unique row in SQL query. Here's sample data to recognize what I'm talking about:
john doe 3000 fog horn drive , ky 40444
john doe 3001 merry lane , ky 40484
I want to return the first one in the list here's my query :
Select
DISTINCT p.personID, e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade, i.gender, p.studentNumber, e.citizenship, e.adult, i.birthdate,
e.disability1, e.disability2, ad.city, e.displacedHomemaker, e.homeSchooled,
e.localStudentNumber, e.migrant, e.modifiedDate, e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid, i.lastname, i.firstname, i.middlename, i.ssn,
ad.phone, ad.state, ad.zip, ad.addressLine1
FROM
Person p
LEFT join
Enrollment e ON e.personID = p.personID And isnull(e.noshow, 0) = 0
LEFT join
EnrollmentKY ky ON ky.enrollmentID = e.enrollmentID
LEFT join
[Identity] i ON i.identityID = p.currentIdentityID And i.personID = p.personID
INNER join
Calendar c ON c.calendarID = e.calendarID
INNER join
SchoolYear sy ON sy.endYear = c.endYear AND sy.active = 1
JOIN
staffMember Staff ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join
v_MailingAddress ad ON ad.personID = i.personID And ad.relatedBy = 'household'
And ad.endDate IS NULL And isnull(ad.secondary, 0) = 0
order by
i.lastname, i.firstname, i.middlename
edit: need to only pick first row in SQL code because I have a problem with people that have multiple addresses it puts two rows for them and i only need first row of data for the person that has multiple addresses.
If the personId is distinct for each of the records and they just have a different address, then you can add a field for the row_number() and then only select the records where the row_number = 1:
select *
from
(
Select p.personID,
e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade,
i.gender,
p.studentNumber,
e.citizenship,
e.adult,
i.birthdate,
e.disability1,
e.disability2,
ad.city,
e.displacedHomemaker,
e.homeSchooled,
e.localStudentNumber,
e.migrant,
e.modifiedDate,
e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid,
i.lastname,
i.firstname,
i.middlename,
i.ssn,
ad.phone,
ad.state,
ad.zip,
ad.addressLine1,
row_number() over(partition by p.personid order by p.personid) rn -- add this field
FROM Person p
LEFT join Enrollment e
ON e.personID = p.personID
And isnull(e.noshow,0)=0
LEFT join EnrollmentKY ky
ON ky.enrollmentID = e.enrollmentID
LEFT join [Identity] i
ON i.identityID = p.currentIdentityID
And i.personID = p.personID
INNER join Calendar c
ON c.calendarID = e.calendarID
INNER join SchoolYear sy
ON sy.endYear = c.endYear
AND sy.active = 1
JOIN staffMember Staff
ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join v_MailingAddress ad
ON ad.personID = i.personID
And ad.relatedBy = 'household'
And ad.endDate IS NULL
And isnull(ad.secondary,0)=0
) x
where x.rn = 1
order by x.lastname, x.firstname, x.middlename
Try using the LIMIT to limit the no. of outputs.
Eg:
SELECT COLUMN_NAME
FROM TABLE
ORDER BY CONDITION
LIMIT NO_OF_ROWS;
Have you tried using a "GROUP BY" clause instead of the DISTINCT keyword?
Also, what about a Sub-Query? If I were writing this type of thing I'd use a sproc and create a temporary table.
Edit: Deleted original answer as question was changed and original answer is not the way to go with changed question.
Suggest GROUP BY clause per Neil Hoskins.