MS-SQL 2008 issues with multiple tables query - sql

I need help with writing a SQL query. My tables are:
Contribution:
contribution_id | amount | person_id | currency_type
Person
Person_id | firstname | lastname
related related_id | person_id | related_personID
Currency Type CurrencyTypeID | CurrencyName
There are other tables and fields, but these are the ones I need.
Here is the problem I am having..
When a person contributes the first and last name is easy, but when a Brokerage firm contributes, I need to include the real person first name and last name (not the Brokerage Account).
The Brokerage is on the same table as the person.
So far, i have if the contribution.currencyType = '12492' then i need to get the information from related table to find the real person_id.
What I do get when I run the code below is all the data, except when the currencytype = 12492 then I get null for first and last name.
Here is my code so far:
`
declare #fund int = 165
declare #payment_luid int = 58
DECLARE #report_information TABLE(
ContributionID varchar(20),
ContributionDate date,
firstname varchar(50),
lastname varchar(50),
memberID varchar(20),
Pledge money,
cash money,
non_cash money,
fund_name VARCHAR(50))
INSERT INTO #report_information
SELECT c.contribution_id,
c.contribution_date,
case when c.currency_type = '12492' then t3.first_name else t1.first_name end,
case when c.currency_type = '12492' then t3.last_name else t1.last_name end,
case when c.currency_type = '12492' THEN t3.person_id else c.person_id end as MemberID,
case when c.currency_type = '12492' then (select amount From ctrb_pledge where ctrb_pledge.person_id = t3.person_id and fund_id = #fund) else (select amount from ctrb_pledge where ctrb_pledge.person_id = c.person_id and fund_id =#fund) END,
CASE WHEN C.currency_type_luid NOT IN (SELECT lookup_id FROM core_lookup WHERE lookup_type_id=#payment_luid AND lookup_qualifier2 ='1') THEN CCF.amount ELSE 0 END,
CASE WHEN CCF.non_cash = 1 OR C.currency_type IN (SELECT lookup_id FROM core_lookup WHERE lookup_type_id=#payment_luid AND lookup_qualifier2 ='1') THEN CCF.amount ELSE 0 END,
f.fund_name
FROM contribution as c
left join core_person as t1
on t1.person_id = c.person_id
left join relationship as t2
on t2.person_id = c.person_id
left join person as t3
on related_person_id = c.person_id
JOIN ctrb_contribution_fund CCF ON CCF.contribution_id=C.contribution_id
JOIN ctrb_fund F ON F.fund_id = CCF.fund_id
where f.fund_id = #fund
order by contribution_id
SELECT lastname
,firstname
,memberID
,coalesce(SUM(pledge),0) as Pledge
,SUM(cash) AS cash_gifts
,SUM(non_cash) AS non_cash_gifts
,SUM(cash + non_cash) as TotalGiving
,coalesce(SUM(pledge)-(SUM(cash)+SUM(non_cash)),0) as Balance
,fund_name
FROM #report_information
GROUP BY memberid, lastname, firstname, fund_name
ORDER BY lastname asc
`

I figured this problem out. By changing the join statements to FULL JOIN OUTER my missing records appeared.
join core_person as cp
on cp.person_id = c.person_id
full outer join core_relationship as rel
on rel.person_id = c.person_id
full outer join core_person as newCp
on rel.related_person_id = newcp.person_id
I did change my table to something I can remember. t1 = cp,t2 = rel,t3 = newcp.

Related

SQL Where in for Many to Many Join Table

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?

Remove duplicate address_id from sql data set

I need to get only distinct address_id in result no duplication. Here is my query.
SELECT DISTINCT address.address_id, address.address1, address.streetcity, state.stateabbrev, rtrim(ltrim(case when address.streetzipcode is not null and address.streetzipcode != 'NULL' then address.streetzipcode else '' end))+case when len(address.streetzipplus4)>0 then '-'+rtrim(ltrim(address.streetzipplus4)) else '' end as streetzipcode, address.homephone,
dbo.f_addressstudent (student.address_id) as Students,
dbo.f_addresspeople (student.address_id) as Adults,
case
when #classif_id IS NULL then 0
else
student.classif_id
end classif,
classifctn
FROM district WITH(NOLOCK)
JOIN dbo.building ON building.district_id = district.district_id
JOIN dbo.studbldg_bridge WITH(NOLOCK) ON studbldg_bridge.bldg_id=building.bldg_id
JOIN dbo.student WITH(NOLOCK) ON student.student_id = studbldg_bridge.student_id
JOIN classif with(nolock) on student.classif_id = classif.classif_id
LEFT JOIN dbo.address WITH(NOLOCK) ON student.address_id = address.address_id
LEFT JOIN dbo.state WITH(NOLOCK) ON address.streetstate_id = state.state_id
LEFT JOIN dbo.state AS mailstate WITH(NOLOCK) ON address.state_id = mailstate.state_id
WHERE district.district_id = (SELECT district_id FROM dbo.building WITH(NOLOCK) WHERE bldg_id = #bldg_id)
ORDER BY classif,Adults, Students
Here is result of query
Query result with error in data
I have tried to group by and use aggregate function with address_id but I also have non-aggregate columns so it didn't worked for me.
After that I also tried using OVER(partition by address.address_id) but it also didn't worked.
Any help will be appreciated in advance.
Thank you
**UPDATE on Business logic/Requirements **
I need to get unique addresses for parents of students. As parent can have two or more children living in same address, it causes duplication. I need to get only one child per parent in other words.
From your image of the results it looks like the classifctn column has more than 1 value so it is repeating your row by that. In order to get 1 distinct address_id and rest of the columns either remove it from your query or you can set a precedence that will only return 1 record per address_id
further please tag only the RDBMs you ware actually using. MySQL for example doesn't have window functions yet you tagged it yet referenced using OVER(partition.... which would not be possible in mysql
;WITH cte (
SELECT DISTINCT address.address_id, address.address1, address.streetcity, state.stateabbrev, rtrim(ltrim(case when address.streetzipcode is not null and address.streetzipcode != 'NULL' then address.streetzipcode else '' end))+case when len(address.streetzipplus4)>0 then '-'+rtrim(ltrim(address.streetzipplus4)) else '' end as streetzipcode, address.homephone,
dbo.f_addressstudent (student.address_id) as Students,
dbo.f_addresspeople (student.address_id) as Adults,
case
when #classif_id IS NULL then 0
else
student.classif_id
end classif,
classifctn,
ROW_NUMBER() OVER (PARTITION BY address.address_id ORDER BY HOW WILL YOU CHOOSE?) AS RowNum
FROM district WITH(NOLOCK)
JOIN dbo.building ON building.district_id = district.district_id
JOIN dbo.studbldg_bridge WITH(NOLOCK) ON studbldg_bridge.bldg_id=building.bldg_id
JOIN dbo.student WITH(NOLOCK) ON student.student_id = studbldg_bridge.student_id
JOIN classif with(nolock) on student.classif_id = classif.classif_id
LEFT JOIN dbo.address WITH(NOLOCK) ON student.address_id = address.address_id
LEFT JOIN dbo.state WITH(NOLOCK) ON address.streetstate_id = state.state_id
LEFT JOIN dbo.state AS mailstate WITH(NOLOCK) ON address.state_id = mailstate.state_id
WHERE district.district_id = (SELECT district_id FROM dbo.building WITH(NOLOCK) WHERE bldg_id = #bldg_id)
)
SELECT *
FROM
cte
WHERE
RowNum = 1
ORDER BY
classif
,Adults
,Students
Alternatively you could nest your select query. note though this solution is somewhat useless as it will only return 1 grade/classifctn when more than 1 exists in a household if you really don't care about the column then you should just remove it from your query.
Actually both your classifctn and classif columns will cause you multiple rows when more than 1 student is at the same address. here is a way to concatenate those values to a single row. You should spend some more time on your business case and defining it for us. But here is one example for you:
SELECT DISTINCT
address.address_id
,address.address1
,address.streetcity
,state.stateabbrev
,LTRIM(RTRIM(ISNULL(NULLIF(address.streetzipcode,'NULL'),'')))
+ CASE WHEN LEN(address.streetzipplus4) > 0 THEN '-' ELSE '' END
+ LTRIM(RTRIM(ISNULL(address.streetzipplus4,''))) AS streetzipcode
,address.homephone
,dbo.f_addressstudent (student.address_id) as Students
,dbo.f_addresspeople (student.address_id) as Adults
, case
when #classif_id IS NULL then 0
else student.classif_id
end classif
,STUFF(
(SELECT ',' + CAST(classif_id AS VARCHAR(100))
FROM
classif c
WHERE c.classif = student.classif
FOR XML PATH(''))
,1,1,'') AS classifs
,STUFF(
(SELECT ',' + CAST(classifctn AS VARCHAR(100))
FROM
classif c
WHERE c.classif = student.classif
FOR XML PATH(''))
,1,1,'') AS classifctns
FROM
district WITH(NOLOCK)
INNER JOIN dbo.building
ON building.district_id = district.district_id
AND building.bldg_id = #bldg_id
INNER JOIN dbo.student WITH(NOLOCK)
ON student.student_id = studbldg_bridge.student_id
INNER JOIN dbo.address WITH(NOLOCK)
ON student.address_id = address.address_id
LEFT JOIN dbo.state WITH(NOLOCK)
ON address.streetstate_id = state.state_id
Note I when ahead and changed the zip code logic to show you some use of ISNULL() and NULLIF() that are helpful in cases like that. I also removed 3 tables because 2 are not used and the third ends up being used in a subselect to concatenate the values. Also address table was changed to an INNER JOIN because if an address doesn't exist all of the other information becomes blank/useless....
INNER JOIN dbo.studbldg_bridge WITH(NOLOCK) ON studbldg_bridge.bldg_id=building.bldg_id
LEFT JOIN dbo.state AS mailstate WITH(NOLOCK) ON address.state_id = mailstate.state_id
INNER JOIN classif with(nolock) on student.classif_id = classif.classif_id

Understanding nested select queries

Have a question in regards to what was a select into query that I am changing into an insert into query with a select and I just wanted somebody to help me understand the query and know why the only fields in the select it wants are only certain fields.
Ok so below is a create table statement I have written for the temp tables '#Infants' and '#MobileBookings'.
create table #MobileBookings
(
Reference nvarchar(50),
CreatedDate datetime,
FirstName nvarchar(50),
Surname nvarchar(50),
PersonTypeId int,
PackageId int,
PersonId int,
ProductId int,
StatusId smallint
)
create table #Infants
(
Reference nvarchar(50),
CreatedDate datetime,
FirstName nvarchar(50),
Surname nvarchar(50),
PersonTypeId int,
ProductPersonId int,
StatusId smallint,
FlightNumber nvarchar(50),
DepartureDateTime datetime,
SectorName nvarchar(50),
BoundID varchar(8)
)
Now what I have in the existing code (that I didn't write but trying to manipulate by including insert into instead of what previously was select into to remove certain warnings.
insert into #Infants (
Reference, CreatedDate, FirstName, Surname,
PersonTypeId, ProductPersonId, StatusId, FlightNumber,
DepartureDateTime, SectorName, BoundID
)
select * from
(
select
x.Reference, x.CreatedDate, x.FirstName, x.Surname,
x.PersonTypeId, pp.ProductPersonId, pp.StatusId as 'ProductPersonStatusID', null as 'DependantPPID',
fl.FlightNumber,
fl.DepartureDateTime, fs.SectorName, iif(fr.BoundID=0,'OutBound','InBound') as 'FlightBound'
from #MobileBookings as x
inner join Reservations_Live.dbo.ProductPerson as pp with (nolock) on pp.ProductID = x.ProductId and pp.PersonId = x.PersonId
inner join Reservations_Live.dbo.FlightReservation as fr with (nolock) on fr.ProductId = x.ProductId
inner join Reservations_Live.dbo.Flight as fl with (nolock) on fl.FlightId = fr.FlightId
inner join Reservations_Live.dbo.FlightSector as fs with (nolock) on fs.FlightSectorId = fl.FlightSectorId
INNER join
(
select x.PackageId as 'PKID', frp.DependantProductPersonId as 'DepPPID', frp.ProductPersonID as 'CarerPPID',
pp.StatusId as 'CarerPPST'
from #MobileBookings as x
inner join Reservations_Live.dbo.ProductPerson as pp with (nolock) on pp.ProductID = x.ProductId and pp.PersonId = x.PersonId
inner join Reservations_Live.dbo.FlightReservationPassenger as frp with (nolock) on frp.ProductPersonID = pp.ProductPersonId
where x.PersonTypeId = 1
and pp.StatusId = 3
and frp.DependantProductPersonId is not null
)
as car on car.PKID = x.PackageId and car.DepPPID = pp.ProductPersonId
where x.StatusId < 7
and x.PersonTypeId = 3
and pp.StatusId = 2
and fl.FlightStatusId < 3
and fl.DepartureDateTime > GETUTCDATE()
) as inf;
set #ActualRowCount = ##rowcount;
Ok so in visual studio, if I hover over the * in the select statement, it displays a hover box that shows the only fields it requires to select:
Reference (nvarchar, null),
CreatedDate (datetime, null),
FirstName (nvarchar, null),
Surname (nvarchar, null),
PersonTypeId (int, null),
ProductPersonStatusID(, null),
DependantPPID(void, not null),
FlightBound (, null)
I'm assuming I need to change my create table and insert into to only include these relevant fields above but what I want to know is how come it only wants to select these fields and not include any other relevant fields?
Also in regards to the ProductPersonStatusID and DependantPPID which is based on the 'StatusID', are they actually displayed as two columns in the final output, meaning the create table will need to include both these columns and they both also need to be included in the insert into? StatusId is an int so if this is the case, I'm assuming 'ProductPersonStatusID' should be set as an int but DependantPPID should be set as a null in the CREATE statement?
UPDATE:
Hopefully I'm in the right section but included the subquery for inf as stated in the comment:
update pp
set pp.StatusId = 3
output 'ProductPerson', 'ProductPersonId', inserted.ProductPersonId,
Core.updXMLFragment('StatusId',inserted.StatusId,deleted.StatusId)
into #OutputList
from Reservations_Live.dbo.ProductPerson as pp
inner join #Infants as inf on inf.ProductPersonId = pp.ProductPersonId;
set #UpdateRowCount = ##Rowcount;
Just to make sure, I have changed the create table and the insert into statement to the follow, which I hope is correct:
create table #Infants
(
Reference nvarchar(50),
CreatedDate datetime,
FirstName nvarchar(50),
Surname nvarchar(50),
PersonTypeId int,
ProductPersonStatusID int,
DependantPPID int,
FlightBound varchar(8)
);
--
insert into #Infants (Reference, CreatedDate, FirstName, Surname, PersonTypeId, ProductPersonStatusID, DependantPPID, FlightBound)
select * from...
I suggest you remove the select * altogether. This is bad practice. There is rarely a good reason to use SELECT * As it was you had a couple of fields mismatched.
Note how the order of fields in the INSERT needs to match the order of fields in the SELECT. That's why I like to spread them across a few lines so I can match them up.
Also WITH (NOLOCK) is not magic go fast switch but that's for another post....
insert into #Infants (
Reference, CreatedDate,
FirstName, Surname,
PersonTypeId, ProductPersonId,
StatusId, FlightNumber,
DepartureDateTime, SectorName,
BoundID
)
select
x.Reference, x.CreatedDate,
x.FirstName, x.Surname,
x.PersonTypeId, pp.ProductPersonId,
pp.StatusId as [ProductPersonStatusID], fl.FlightNumber,
fl.DepartureDateTime, fs.SectorName,
iif(fr.BoundID=0,'OutBound','InBound') as [FlightBound]
from #MobileBookings as x
inner join Reservations_Live.dbo.ProductPerson as pp with (nolock) on pp.ProductID = x.ProductId and pp.PersonId = x.PersonId
inner join Reservations_Live.dbo.FlightReservation as fr with (nolock) on fr.ProductId = x.ProductId
inner join Reservations_Live.dbo.Flight as fl with (nolock) on fl.FlightId = fr.FlightId
inner join Reservations_Live.dbo.FlightSector as fs with (nolock) on fs.FlightSectorId = fl.FlightSectorId
INNER join
(
select x.PackageId as 'PKID', frp.DependantProductPersonId as 'DepPPID', frp.ProductPersonID as 'CarerPPID',
pp.StatusId as 'CarerPPST'
from #MobileBookings as x
inner join Reservations_Live.dbo.ProductPerson as pp with (nolock) on pp.ProductID = x.ProductId and pp.PersonId = x.PersonId
inner join Reservations_Live.dbo.FlightReservationPassenger as frp with (nolock) on frp.ProductPersonID = pp.ProductPersonId
where x.PersonTypeId = 1
and pp.StatusId = 3
and frp.DependantProductPersonId is not null
)
as car on car.PKID = x.PackageId and car.DepPPID = pp.ProductPersonId
where x.StatusId < 7
and x.PersonTypeId = 3
and pp.StatusId = 2
and fl.FlightStatusId < 3
and fl.DepartureDateTime > GETUTCDATE()

Joining Two Temp Tables

I would like to join two temp tables into one big temp table. I want all of the records from my first temp table and want the records from my second temp table ONLY if the ProductID doesn't exist in my first temp table.
First temp table:
--define temporary table
declare #tmp table (
ManagerID int null,
ManagerName varchar(250),
ProductID int null,
ProductName varchar(250),
RFIFixedIncomeAttributionID int null,
Value decimal(8,4) null,
Name varchar(250),
Sector varchar(250)
)
--populate temp table
insert into #tmp
select
m.ManagerID, m.ManagerName, p.ID as 'ProductID', p.ProductName, sa.RFIFixedIncomeAttributionID, sa.Value, sc.Name,
case when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 39 then 'Core'
when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 38 then 'Intermediate'
end as 'Sector'
from Products p
join Managers m on m.ManagerID = p.ManagerID
left join RFIFixedIncomeAttribution fia on fia.ParentID = p.ID and fia.ParentTypeID = 26
left join RFIFixedIncomeSectorAllocation sa on sa.RFIFixedIncomeAttributionID = fia.ID
and sa.RFIFixedIncomeDataTypeID = 1
join RFIFixedIncomeSectorCategories sc on sc.ID = sa.RFIFixedIncomeSectorCategoryID
join SubType1 s1 on s1.SubType1ID = p.SubType1ID
join SubType2 s2 on s2.SubType2ID = p.SubType2ID
join GeographicMandates gm on gm.GeographicMandateID = p.GeographicMandateID
where p.prodclasscategoryid = 4
and fia.year = 2014
and fia.quarter = 6/3
and p.Rank = 1
order by m.ManagerName, p.ProductName
--get filtered dataset
select * from #tmp
where
Sector in ('Core')
Second temp table:
--define temporary table
declare #tmp2 table (
ManagerID int null,
ManagerName varchar(250),
ProductID int null,
ProductName varchar(250),
RFIFixedIncomeAttributionID int null,
Value decimal(8,4) null,
Name varchar(250),
Sector varchar(250)
)
--populate temp table
insert into #tmp2
select
m.ManagerID, m.ManagerName, p.ID as 'ProductID', p.ProductName, sa.RFIFixedIncomeAttributionID, sa.Value, sc.Name,
case when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 39 then 'Core'
when gm.GeographicMandateID = 2 and s1.SubType1ID = 10 and s2.SubType2ID = 38 then 'Intermediate'
end as 'Sector'
from Products p
join Managers m on m.ManagerID = p.ManagerID
join Vehicles v on v.ProductID = p.ID
join ManagerAccounts ma on ma.VehicleID = v.ID
join Accounts a on a.MgrAccountID = ma.MgrAccountID
left join RFIFixedIncomeAttribution fia on fia.ParentID = a.AccountID and fia.ParentTypeID = 6
left join RFIFixedIncomeSectorAllocation sa on sa.RFIFixedIncomeAttributionID = fia.ID
and sa.RFIFixedIncomeDataTypeID = 1
join RFIFixedIncomeSectorCategories sc on sc.ID = sa.RFIFixedIncomeSectorCategoryID
join SubType1 s1 on s1.SubType1ID = p.SubType1ID
join SubType2 s2 on s2.SubType2ID = p.SubType2ID
join GeographicMandates gm on gm.GeographicMandateID = p.GeographicMandateID
where p.prodclasscategoryid = 4
and fia.year = 2014
and fia.quarter = 6/3
and p.Rank = 1
order by m.ManagerName, p.ProductName
--get filtered dataset
select * from #tmp2
where
Sector in ('Core')
Few points that have already brought up
Union is the term you want, join is something quite different.
You are not working with temp tables, you are working with table variables. Not quite the same thing
mysql and mssql are not the same thing, tag your questions as one or the other, not both.
select * from #tmp
union all
select * from #tmp2 where productID not in (select productID from #tmp)
Not sure if I'd rely on this query in MySQL as it'll struggle with the not in clause...you can use the join syntax in Jasmine's answer for the second half of the union clause.
This is a case of "find all rows with NO MATCH in the other table" and we have a pattern for that. First, swap your tables - the table where you expect to be missing rows will be the second or RIGHT table, the other is the LEFT table.
select <columns>
from table1
LEFT OUTER JOIN table1.ID = table2.ID
where table2.ID IS NULL
OR... don't swap the tables and use RIGHT OUTER JOIN - but that's non-standard.
In your code, there's a problem...
and fia.quarter = 6/3
is equivalent to:
and fia.quarter = 2
I think you need some quotation marks there.

How could I form a tsql query with 'and' and 'not' for a result

I have the following question:
For each city display the number of clients who only rented cars of type 'Toyota' or 'BMW' and never rented 'Mercedes'
The tables are as follows:
Car [CarId int, type varchar(30)]
Client [ClientId int, CityId int, Name varchar(30)]
City [CityId int, CityName varchar(30)]
Rent [CarId int, ClientId int, days_number int]
I don't know how would I formulate this query I tried hard but nothing worked until now.
select city.cityname, count(*) as cnt
from client
join city
on client.cityId = city.cityId
where exists(select * from rent join car on rent.carid = car.carid
where client.clientid = rent.clientid
and car.[type] in ('Toyota', 'BMW'))
and not exists(select * from rent join car on rent.carid = car.carid
where client.clientid = rent.clientid
and car.[type] = 'Mercedes')
group by city.cityname
Please take a look at this query:
select
City.CityName,
count(1) as NumberOfClients
from
City
inner join Client on City.CityID = Client.CityID
inner join
(
select Rent.ClientID
from
Rent
inner join Car on Rent.CarID = Car.CarID
and Car.type in ('Toyota','BMW','Mercedes')
group by Rent.ClientID
having sum(case when Car.type in ('Toyota','BMW') then 1 else 0 end) > 0
and sum(case when Car.type in ('Mercedes') then 1 else 0 end) = 0
) as Summary
on Client.ClientID = Summary.ClientID
group by
City.CityID,
City.CityName
What it does is:
In subquery (named Summary) all distinct clients are selected, basing on a condition that those clients have rented 'Toyota' or 'BMW' at least once, while never have rented 'Mercedes'.
The outer query takes the results of the subquery and calculates totals for each city.
This can probably be done more efficiently - but this is first that comes to my mind.
Declare #count1 int, #count2 int
Select #count1 = Count(*)
From Client inner join Rent
on Client.ClientId = Rent.ClientId
inner join Car
on Car.CarId = Rent.CarId
Where Car.type In( 'Toyota','BMW')
--except
Select #count2 = Count(*)
From Client inner join Rent
on Client.ClientId = Rent.ClientId
inner join Car
on Car.CarId = Rent.CarId
Where Car.type = 'Merccedes'
Select (#count1 - #count2)