SQL script of joining multiple tables shows duplicated record - sql

The McLean family is challenging their total condo fees. Retrieve all invoice data related to condo fees (including details) for the McLean family for invoice 20065.  Selecting appropriate data to calculate the total condo fees for invoice number 20065. 
Tips: guest# is 'G5'.
startdate is '2019-08-03'
And they stayed in the condo for a week.
I write a script. But always shows duplicated output (two duplicated records). How can I do this without using the keyword "distinct"?
The expected output only shows one row of record.
select i.inv#, i.condo#, i.guest#, g.rlname, cs.startdate, cs.enddate, c.WeeklyFee
from guests g join reservations r
on g.guest# = r.guest#
join invoicedetails id
on r.rid = id.rid
join invoice i
on id.inv# = i.inv#
join condostays cs
on i.guest# = cs.guest# and i.condo# = cs.condo#
join condos c
on cs.condo# = c.condo#
where i.guest# = 'g5'
and i.inv# in (20065)
and startdate = '2019-08-03';
My output of showing duplicated records
Schema:
ERD:
Expected output (only one row of record output):

Related

SQL Inner Join Combining Rows in Results - Too Few Results

I'm trying to create a report from four tables: Master, Details, Labor, Costs. Currently I have a working report pulling columns from Jobs, Details, and Costs. Shared key for all tables is JobNumber. I'm looking to get a sum of the costs and a sum of the hours for each job. Here is my code that works with three tables:
SELECT
JC_JobMaster.JobNumber,
JC_JobMaster.JobDescription1 AS Customer_Name,
JC_JobMaster.JobDescription2 AS Work,
JC_JobSortCategories.SortCategory2 AS Work_Type,
JC_JobMaster.CustomerCode,
JC_JobMaster.ContractValue,
SUM(JC_JobBalancesCostDollars.CurrentPeriodAmount*-1) AS Gross_profit,
JC_JobSortCategories.SortCategory1 AS City,
JC_JobSortCategories.SortCategory4 AS Salesman
FROM
JC_JobMaster INNER JOIN
JC_JobSortCategories ON JC_JobMaster.JobNumber = JC_JobSortCategories.JobNumber INNER JOIN
JC_JobBalancesCostDollars ON JC_JobMaster.JobNumber = JC_JobBalancesCostDollars.JobNumber
WHERE
JC_JobMaster.JobNumber between '11566' and '13441' and
JC_JobSortCategories.SortCategory5 = 'AWARDED' and
JC_JobSortCategories.SortCategory2 = 'FPR' and
JC_JobSortCategories.SortCategory1 in ('1')
Group By
JC_JobMaster.JobNumber,
JC_JobMaster.JobDescription1,
JC_JobMaster.JobDescription2,
JC_JobSortCategories.SortCategory2,
JC_JobMaster.CustomerCode,
JC_JobMaster.ContractValue,
JC_JobSortCategories.SortCategory1,
JC_JobSortCategories.SortCategory4
Order by
JC_JobMaster.JobNumber
Everything works fine - this query returns 45 rows with easily-verified data. However, adding in a fourth table using an inner join INNER JOIN JC_JobCostDetailLabourHours ON JC_JobMaster.JobNumber = JC_JobCostDetailLabourHours.JobNumber only returns 7 rows, and the summed column Gross_profit is incorrect. Using a LEFT JOIN as opposed to INNER JOIN gives me the proper 45 rows, but the summed column is still incorrect. The LabourHours and BalancesCostDollars tables have multiple entries for each job number that I'm wanting summed. What am I doing wrong with adding the fourth table, or did I just happen to get the right result by accident with the first summed column?

Expand Join to not limit data

I have a weird question - I understand that Joins return matching data based on the 'ON' stipulation, however the problem I am facing is I need the Business date back for both tables but at the same time i need to join on the date in order to get the totals correct
See below code:
Select
o.Resort,
o.Business_Date,
Occupied,
Comps,
House,
ADR,
Room_Revenue,
Occupied-(Comps+House) AS DandT,
Coalesce(gd.Projected_Occ1,0) AS Projected_Occ1,
Occupied-(Comps+House)+Coalesce(gd.Projected_Occ1,0) as Total
from Occupancy o
left join Group_Details_HF gd
on o.Business_Date = gd.Business_Date
and o.Resort = gd.resort
UNION ALL
select
o.Resort,
o.Business_Date,
Occupied,
Comps,
House,
ADR,
Room_Revenue,
Occupied-(Comps+House) AS DandT,
Coalesce(gd.Projected_Occ1,0) AS Projected_Occ1,
Coalesce(Occupied-(Comps+House),0)+Coalesce(gd.Projected_Occ1,0) as Total
from Occupancy_Forecast o
FULL OUTER JOIN Group_Details_HF gd
on o.Business_Date = gd.Business_Date
and o.Resort = gd.resort
Currently, this gives me the desired results from the Occupancy and Occupancy forecast table however when the business date does not exist in the occupancy forecast table it ignores the group_details table, I need the results to combine the dates when they exist in both or give the unique results for each when there is no match
I have decided to create another pivot table storing the details from Group_Details_HF and then Union together the two tables which has given me the desired result rather than fiddling with the join :)

SQL query date column sorting issue

I am writing a SQL query which will return data of customer bills payments.
We have these payments in two different tables, one is "Bills" and other is "receipts". When my query data it shows that "receipts data" (from receipts table) in ascending order. I have two more date columns to show in result set which are "bill month" and "due date" (from bills table). When I try to apply order by on any of these mentioned columns it shows wrong data. Please help.
My query is attached below. thank you.
select distinct
bil.bill_id as Bill#, --(bill), this table has bill month and due date column
rec.receiptid as IDs, --(receipts),this table has receipt payment date,amount
sp.spaceno as spaceno,-- (space), this table has property names
lo.description as locaiton,-- (location),this table has details of property
one.name as owner_name,-- (owner), this table has owners information
bt.billtype as Particular,--(billtype),where bill types are saved
rec.rdate as Date,-- this column of receipt table showing wrong date data
dc.dr as opening,-- (DCnotes), this table has total payable amount column
rec.amount as dr,-- this column tells the paid amount
bil.amount as cr,-- this columen tell the payable amount
bil.balamount as balance,-- this column tells the net total of dr-cr columns
bil.billmonth as BillMonth,-- bill month column from bill table
bil.duedate as DueDate -- bill due date column from bill table
from
bills bil
inner join
Owners one on bil.ownerid = one.ownerid
inner join
Receipts rec on bil.spaceid = rec.propertyid
inner join
DCnotes dc on bil.spaceid = dc.property
inner join
BillTypes bt on bil.billtypeid = bt.billtypeid
inner join
Spaces sp on bil.spaceid = sp.spaceid
inner join
Locations lo on sp.locationid = lo.locationid
where
bil.siteid = '15'
This is the image of SQL query result:
This is the image of required data in report:
Please check attached images of required data and SQL query result

Several inner joins producing too many rows

I'm working on a field trip request software for school districts.
Each field trip has an account attached to it that will be billed. It will also have one or more driver/vehicle combinations and mileage and driver rates associated with each driver/vehicle combination.
I'm working on an accounting report that will show, by account, a count of the trips that are assigned to that account, the total number of miles driven on that account times a certain charge basis, and a total number of hours each driver has driven on that trip multiplied by their payrate.
I have a field trip (tripid=1) with two vehicles and two drivers and I expect two rows of output. However, I am getting 4 rows; Two rows for vehicle 81 and two rows for vehicle 56. Is there something in my joins that's causing too many rows to be outputted?
What's weird is Mister Driver is on both vehicles in the output of my query and so is Generic Person.
select distinct
tdv.tripid as tripid,
ta.name as account,
cb.chargebasisname as trip_type,
cb.defaultdistancerate as distance_rate,
(tc.odometerreturn-tc.odometerstart) as total_miles,
datediff(hour, tc.actualoriginstarttime,tc.actualoriginreturntime) as total_hours,
v.vehicle,
pr.hourlyrate as driver_rate,
e.firstname+' '+e.lastname as driver
from trip_tripdrivervehicle tdv
join trip_tripinformation ti
on ti.recordid = tdv.tripid
join trip_transportationaccounts ta
on ta.recordid = ti.accountid
join trip_invoicechargebasis cb
on cb.recordid = ta.defaultchargebasisid
join trip_tripcompletion tc
on tc.tripid = ti.recordid
join vehicles v
on v.recordid = tc.vehicleid
join trip_employeejobcategorypayrate pr
on pr.employeeid = tdv.driverid
join employees e
on e.recordid = tdv.driverid
where ti.triprequeststatusid = 7 and ti.recordid = 1
Here is my output:
https://lh6.googleusercontent.com/_Bbr20KcwLyw/TX5cwDhr7BI/AAAAAAAAbYE/qCfQtk6Xmeg/s800/sql_results.jpg
Looks like you also have two matches for the JOIN with table trip_tripcompletion - one that gives rows with total miles of 10 and another that gives rows with total miles of 50.
So each driver shows up with each total_miles option.
The JOIN condition for this table may need to be changed, or you can use GROUP BY along with MAX/MIN to show only the shortest/longest trip (depending on the need).

outer query to list only if its rowcount equates to inner subquery

Need help on a query using sql server 2005
I am having two tables
code
chargecode
chargeid
orgid
entry
chargeid
itemNo
rate
I need to list all the chargeids in entry table if it contains multiple entries having different chargeids
which got listed in code table having the same charge code.
data :
code
100,1,100
100,2,100
100,3,100
101,11,100
101,12,100
entry
1,x1,1
1,x2,2
2,x3,2
11,x4,1
11,x5,1
using the above data , it query should list chargeids 1 and 2 and not 11.
I got the way to know how many rows in entry satisfies the criteria, but m failing to get the chargeids
select count (distinct chargeId)
from entry where chargeid in (select chargeid from code where chargecode = (SELECT A.chargecode
from code as A join code as B
ON A.chargecode = B.chargeCode and A.chargetype = B.chargetype and A.orgId = B.orgId AND A.CHARGEID = b.CHARGEid
group by A.chargecode,A.orgid
having count(A.chargecode) > 1)
)
First off: I apologise for my completely inaccurate original answer.
The solution to your problem is a self-join. Self-joins are used when you want to select more than one row from the same table. In our case we want to select two charge IDs that have the same charge code:
SELECT DISTINCT c1.chargeid, c2.chargeid FROM code c1
JOIN code c2 ON c1.chargeid != c2.chargeid AND c1.chargecode = c2.chargecode
JOIN entry e1 ON e1.chargeid = c1.chargeid
JOIN entry e2 ON e2.chargeid = c2.chargeid
WHERE c1.chargeid < c2.chargeid
Explanation of this:
First we pick any two charge IDs from 'code'. The DISTINCT avoids duplicates. We make sure they're two different IDs and that they map to the same chargecode.
Then we join on 'entry' (twice) to make sure they both appear in the entry table.
This approach gives (for your example) the pairs (1,2) and (2,1). So we also insist on an ordering; this cuts to result set down to just (1,2), as you described.