How to use ISNULL in a Query within a query? - sql

My SQL Query below is now Returning the RoomsAvailable field correctly except when theres 0 rooms taken, in which the SQL command subtracts number_of_rooms with NULL and outputs NULL to the Column. I have tried numerous ISNULL variations and found that it doesnt work; anyone know how I should be doing this?
SQL :
SELECT
Hotel_2.hotel_code,
Hotel_2.hotel_country,
Room_type_rates_2.room_type_code,
Room_type_rates_2.number_of_rooms,
Types_2.room_type,
Room_type_rates_2.rates,
Room_type_rates_2.number_of_rooms -
(SELECT
DISTINCT (SELECT
COUNT(dbo.Hotel.hotel_code) AS RoomsTake
FROM
dbo.Hotel
INNER JOIN dbo.Hotel_Reservation
ON dbo.Hotel.hotel_code = dbo.Hotel_Reservation.hotel_code
INNER JOIN dbo.Room_type_rates
ON dbo.Hotel.hotel_code = dbo.Room_type_rates.hotel_code
INNER JOIN dbo.Types
ON dbo.Hotel_Reservation.room_type_code = dbo.Types.room_type_code
AND dbo.Room_type_rates.room_type_code = dbo.Types.room_type_code
WHERE
(dbo.Room_type_rates.room_type_code = Room_type_rates_1.room_type_code)
AND (dbo.Hotel.hotel_code = Hotel_1.hotel_code)
AND (dbo.Hotel_Reservation.checkin_date >= Hotel_Reservation_1.checkin_date)
AND (dbo.Hotel_Reservation.checkout_date <= Hotel_Reservation_1.checkout_date)
) AS RoomsTaken
FROM
dbo.Hotel AS Hotel_1
INNER JOIN dbo.Hotel_Reservation AS Hotel_Reservation_1
ON Hotel_1.hotel_code = Hotel_Reservation_1.hotel_code
INNER JOIN dbo.Room_type_rates AS Room_type_rates_1
ON Hotel_1.hotel_code = Room_type_rates_1.hotel_code
INNER JOIN dbo.Types AS Types_1
ON Hotel_Reservation_1.room_type_code = Types_1.room_type_code
AND Room_type_rates_1.room_type_code = Types_1.room_type_code
WHERE
(Hotel_Reservation_1.checkin_date >= '11/19/2011')
AND (Hotel_Reservation_1.checkout_date <= '12/01/2011')
AND (Hotel_1.hotel_country = 'Adelaide')
AND (Types_1.room_type_code = Types_2.room_type_code)
) AS RoomsAvailable
FROM
dbo.Hotel AS Hotel_2
INNER JOIN dbo.Room_type_rates AS Room_type_rates_2
ON Hotel_2.hotel_code = Room_type_rates_2.hotel_code
INNER JOIN dbo.Types AS Types_2
ON Room_type_rates_2.room_type_code = Types_2.room_type_code
Current Output :
ADL20 Adelaide CPL 6 Couple Suite 514.0000 3
ADL20 Adelaide FYU 3 Family Suite 533.0000 2
ADL20 Adelaide KNG 2 King's Bedroom 556.0000 NULL

Do you mean this?:
...ISNULL(COUNT(dbo.Hotel.*),0)...
Or is the problem that you're getting NULL at all? In that case I would suspect your JOINs may have a problem.
You can wrap an ISNULL around any nested subquery or value.

Related

SQL Query with counts only returning equivalent counts

I have a query that consists of 1 table and 2 sub queries. The table being a listing of all customers, 1 sub query is a listing all of the quotes given over a period of time for customers and the other sub query is a listing of all of the orders booked for a customer over the same period of time. What I am trying to do is return a result set that is a customer, the number of quotes given, and the number of orders booked over a given period of time. However what I am returning is only a listening of customers over the period of time that have an equivalent quote and order count. I feel like I am missing something obvious within the context of the query but I am unable to figure it out. Any help would be appreciated. Thank you.
Result Set should look like this
Customer-------Quotes-------Orders Placed
aaa----------------4----------------4
bbb----------------9----------------18
ccc----------------18----------------9
select
[Customer2].[Name] as [Customer2_Name],
(count( Quotes.UD03_Key3 )) as [Calculated_CustomerQuotes],
(count( Customer_Bookings.OrderHed_OrderNum )) as [Calculated_CustomerBookings]
from Erp.Customer as Customer2
left join (select
[UD03].[Key3] as [UD03_Key3],
[UD03].[Key4] as [UD03_Key4],
[UD03].[Key1] as [UD03_Key1],
[UD03].[Date02] as [UD03_Date02]
from Ice.UD03 as UD03
inner join Ice.UD02 as UD02 on
UD03.Company = UD02.Company
And
CAST(CAST(UD03.Number09 AS INT) AS VARCHAR(30)) = UD02.Key1
left outer join Erp.Customer as Customer on
UD03.Company = Customer.Company
And
UD03.Key1 = Customer.Name
left outer join Erp.SalesTer as SalesTer on
Customer.Company = SalesTer.Company
And
Customer.TerritoryID = SalesTer.TerritoryID
left outer join Erp.CustGrup as CustGrup on
Customer.Company = CustGrup.Company
And
Customer.GroupCode = CustGrup.GroupCode
where (UD03.Key3 <> '0')) as Quotes on
Customer2.Name = Quotes.UD03_Key1
left join (select
[Customer1].[Name] as [Customer1_Name],
[OrderHed].[OrderNum] as [OrderHed_OrderNum],
[OrderDtl].[OrderLine] as [OrderDtl_OrderLine],
[OrderHed].[OrderDate] as [OrderHed_OrderDate]
from Erp.OrderHed as OrderHed
inner join Erp.Customer as Customer1 on
OrderHed.Company = Customer1.Company
And
OrderHed.BTCustNum = Customer1.CustNum
inner join Erp.OrderDtl as OrderDtl on
OrderHed.Company = OrderDtl.Company
And
OrderHed.OrderNum = OrderDtl.OrderNum) as Customer_Bookings on
Customer2.Name = Customer_Bookings.Customer1_Name
where Quotes.UD03_Date02 >= '5/15/2018' and Quotes.UD03_Date02 <= '5/15/2018' and Customer_Bookings.OrderHed_OrderDate >='5/15/2018' and Customer_Bookings.OrderHed_OrderDate <= '5/15/2018'
group by [Customer2].[Name]
You have several problems going on here. The first problem is your code is so poorly formatted it is user hostile to look at. Then you have left joins being logically treated an inner joins because of the where clause. You also have date literal strings in language specific format. This should always be the ANSI format YYYYMMDD. But in your case your two predicates are contradicting each other. You have where UD03_Date02 is simultaneously greater than and less than the same date. Thankfully you have =. But if your column is a datetime you have prevented any rows from being returned again (the first being your where clause). You have this same incorrect date logic and join in the second subquery as well.
Here is what your query might look like with some formatting so you can see what is going on. Please note I fixed the logical join issue. You still have the date problems because I don't know what you are trying to accomplish there.
select
[Customer2].[Name] as [Customer2_Name],
count(Quotes.UD03_Key3) as [Calculated_CustomerQuotes],
count(Customer_Bookings.OrderHed_OrderNum) as [Calculated_CustomerBookings]
from Erp.Customer as Customer2
left join
(
select
[UD03].[Key3] as [UD03_Key3],
[UD03].[Key4] as [UD03_Key4],
[UD03].[Key1] as [UD03_Key1],
[UD03].[Date02] as [UD03_Date02]
from Ice.UD03 as UD03
inner join Ice.UD02 as UD02 on UD03.Company = UD02.Company
And CAST(CAST(UD03.Number09 AS INT) AS VARCHAR(30)) = UD02.Key1
left outer join Erp.Customer as Customer on UD03.Company = Customer.Company
And UD03.Key1 = Customer.Name
left outer join Erp.SalesTer as SalesTer on Customer.Company = SalesTer.Company
And Customer.TerritoryID = SalesTer.TerritoryID
left outer join Erp.CustGrup as CustGrup on Customer.Company = CustGrup.Company
And Customer.GroupCode = CustGrup.GroupCode
where UD03.Key3 <> '0'
) as Quotes on Customer2.Name = Quotes.UD03_Key1
and Quotes.UD03_Date02 >= '20180515'
and Quotes.UD03_Date02 <= '20180515'
left join
(
select
[Customer1].[Name] as [Customer1_Name],
[OrderHed].[OrderNum] as [OrderHed_OrderNum],
[OrderDtl].[OrderLine] as [OrderDtl_OrderLine],
[OrderHed].[OrderDate] as [OrderHed_OrderDate]
from Erp.OrderHed as OrderHed
inner join Erp.Customer as Customer1 on OrderHed.Company = Customer1.Company
And OrderHed.BTCustNum = Customer1.CustNum
inner join Erp.OrderDtl as OrderDtl on OrderHed.Company = OrderDtl.Company
And OrderHed.OrderNum = OrderDtl.OrderNum
) as Customer_Bookings on Customer2.Name = Customer_Bookings.Customer1_Name
and Customer_Bookings.OrderHed_OrderDate >= '20180515'
and Customer_Bookings.OrderHed_OrderDate <= '20180515'
group by [Customer2].[Name]
COUNT() will just give you the number of records. You'd expect this two result columns to be equal. Try structuring it like this:
SUM(CASE WHEN Quote.UD03_Key1 IS NOT NULL THEN 1 ELSE 0 END) AS QuoteCount,
SUM(CASE WHEN Customer_Bookings.Customer1_Name IS NOT NULL THEN 1 ELSE 0 END) AS custBookingCount

postgresql count distinct on differect condition

I'm stuck on an exercise where I need to count the total amount of unique visits to planets, but if the planet is the moon (maan), then it should be counted twice. Also the client number should be 121
select case
when objectnaam = 'Maan' then count(objectnaam)
else count(distinct objectnaam)
end as aantal_bezoeken
from klanten inner join deelnames on klanten.klantnr = deelnames.klantnr
inner join reizen on deelnames.reisnr = reizen.reisnr
inner join bezoeken on reizen.reisnr = bezoeken.reisnr
where klanten.klantnr = 121
group by objectnaam
And it gives me this result
aantal_bezoeken
1
4
1
1
but the result should be
aantal_bezoeken
7
I just need to add all these values together but I don't know how to,
or maybe there's a better more simple solution. It should be without subqueries
Try this:
select sum(aantal_bezoeken) as aantal_bezoeken from
(select case
when objectnaam = 'Maan' then count(objectnaam)
else count(distinct objectnaam)
end as aantal_bezoeken
from klanten inner join deelnames on klanten.klantnr = deelnames.klantnr
inner join reizen on deelnames.reisnr = reizen.reisnr
inner join bezoeken on reizen.reisnr = bezoeken.reisnr
where klanten.klantnr = 121
group by objectnaam) as a

JOIN syntax and order for multiple tables

SQL Gurus,
I have a query that uses the "old" style of join syntax as follows using 7 tables (table and column names changed to protect the innocent), as shown below:
SELECT v1_col, p1_col
FROM p1_tbl, p_tbl, p2_tbl, p3_tbl, v1_tbl, v2_tbl, v3_tbl
WHERE p1_code = 1
AND v1_code = 1
AND p1_date >= v1_date
AND p_uid = p1_uid
AND p2_uid = p1_uid AND p2_id = v2_id
AND p3_uid = p1_uid AND p3_id = v3_id
AND v2_uid = v1_uid
AND v3_uid = v1_uid
The query works just fine and produces the results it is supposed to, but as an academic exercise, I tried to rewrite the query using the more standard JOIN syntax, for example, below is one version I tried:
SELECT V1.v1_col, P1.p1_col
FROM p1_tbl P1, v1_tbl V1
JOIN p_tbl P ON ( P.p_uid = P1.p1_uid )
JOIN p2_tbl P2 ON ( P2.p2_uid = P1.p1_uid AND P2.p2_id = V2.v2_id )
JOIN p3_tbl P3 ON ( P3.p3_uid = P1.p1_uid AND P3.p3_id = V3.v3_id )
JOIN v2_tbl V2 ON ( V2.v2_uid = V1.v1_uid )
JOIN v3_tbl V3 ON ( V3.v3_uid = V1.v1_uid )
WHERE P1.p1_code = 1
AND V1.v1_code = 1
AND P1.p1_date >= V1.v1_date
But, no matter how I arrange the JOINs (using MS SQL 2008 R2), I keep running into the error:
The Multi-part identifier "col-name" could not be bound,
where "col-name" varies depending on the order of the JOINs I am attempting...
Does anyone have any good examples on how use the JOIN syntax with this number of tables??
Thanks in advance!
When you use JOIN-syntax you can only access columns from tables in your current join or previous joins. In fact it's easier to write the old syntax, but it's more error-prone, e.g. you can easily forget a join-condition.
This should be what you want.
SELECT v1_col, p1_col
FROM p1_tbl
JOIN v1_tbl ON p1_date >= v1_date
JOIN v2_tbl ON v2_uid = v1_uid
JOIN v3_tbl ON v3_uid = v1_uid
JOIN p_tbl ON p_uid = p1_uid
JOIN p2_tbl ON p2_uid = p1_uid AND p2_id = v2_id
JOIN p3_tbl ON p3_uid = p1_uid AND p3_id = v3_id
WHERE p1_code = 1
AND v1_code = 1
You are not naming the tables in your join such that it doesn't know which column is from which table. Try something like:
SELECT a.v1_col, b.p1_col
FROM p1_tbl b
JOIN p_tbl a ON b.p_uid = a.p1_uid
WHERE b.p1_code = 1
From your query above, I am assuming a naming convention of p2_uid comes from p2_tbl. Below id my best interpretation of WHERE joins to using INNER joins.
SELECT
v1_col, p1_col
FROM
p1_tbl
INNER JOIN p1_tbl
ON p1_tbl.p1_date >= v1_tbl.v1_date
INNER JOIN p_tbl
ON p_tbl.p_uid = p1_tbl.p1_uid
INNER JOIN p2_tbl
ON p2_tbl.p2_uid = p1_tbl.p1_uid
INNER JOIN v2_tbl
ON p2_tbl.p2_id = v2_tbl.v2_id
INNER JOIN p3_tbl
ON p3_tbl.p3_uid = p1_tbl.p1_uid
INNER JOIN v3_tbl
ON p3_tbl.p3_id = v3_tbl.v3_id
INNER JOIN v1_tbl
ON v1_tbl.v1_uid = v2_tbl.v2_uid
AND v1_tbl.v1_uid = v3_tbl.v2_uid
WHERE
p1_code = 1
AND
v1_code = 1
Some general points I have found useful in SQL statements with many joins.
Always fully qualify the names. I.e dont use ID , rahter use
TableName.ID
Dont use aliases unless there is meaning. (I.e. joining a table to
its self where aliasing is needed.)

Avoiding NULL records on this LEFT JOIN

The query below works - EXCEPT - it is returning NULL values for vehicle_id. I do not want any records that have NULL for vehicle_id.
Since vehicle_id is tied to fund_series, this is complicated to me.
When I had the vehicle_id conditions underneath the WHERE, the query was not working. Any SQL geniuses that can help?
I put the MIN() aggregate functions in there just so I could get the GROUP BY to work.
SELECT DISTINCT
MIN(ml.pretty_file_name),
ml.filename,
MIN(ml.issued_date),
MIN(mr.rule_name),
MIN(mlob.line_of_business_name),
MIN(mt.media_type_name),
MAX(v.vehicle_name)
FROM Media_Live ml
JOIN Media_Type mt
ON mt.media_type_id = ml.media_type_id
JOIN Media_Rule mr
ON mr.rule_id = ml.rule_id
JOIN Media_Line_Of_Business mlob
ON mlob.line_of_business_id = ml.line_of_business_id
LEFT JOIN Fund_Class_Media fcm
ON fcm.media_id=ml.media_id
LEFT JOIN Fund_Class_Live fc
ON fc.fund_class_id = fcm.fund_class_id
LEFT JOIN Fund_Series fs
ON fs.fund_series_id = fc.fund_series_id
LEFT JOIN Vehicle AS v
ON v.vehicle_id=fs.vehicle_id AND /*THIS IS WHERE IM GETTING NULLS*/
(
v.vehicle_id = 1
OR v.vehicle_id = 2
OR v.vehicle_id = 5
)
LEFT JOIN Media_Media_Tag AS mmt ON mmt.media_id=ml.media_id
LEFT JOIN Media_Tag AS mtag ON mtag.tag_id=mmt.tag_id
WHERE
(/*people can search with terms for fc*/
--fc.fund_class_id LIKE '%'+replace(?,' ','%')+'%'
)
(
mt.media_type_id = 33
OR mt.media_type_id = 1
OR mt.media_type_id = 12
)
AND
(
mr.rule_id = 3
OR mr.rule_id = 9
)
AND
(
mtag.tag_name != 'exclude_web_lit_center'
)
GROUP BY ml.filename
This is what a left join does, allow nulls. Just take out the left join part making it an inner join.
JOIN Vehicle AS v ON v.vehicle_id=fs.vehicle_id AND v.vehicle_id IN (1,2,5)
You cold also do this, but I don't see why you would:
LEFT JOIN Vehicle AS v ON v.vehicle_id=fs.vehicle_id AND ISNULL(v.vehicle_id,0) IN (1,2,5)
In the WHERE clause, add:
AND v.Vehicl_Id IS NOT NULL
That should do it.

Oracle SQL - results from a subquery range

I will probably figure this out across the weekend, hard to focus late on a Friday...
Query 1 below returns a trip, with an arrive and depart value at a given location.
Query 2 below returns a trip, with an arrive and depart value at a 2nd location.
These 2 queries are straightforward.
I want to return only the results in query 2,when the query 2 depart times are exactly between any of query 1's arrive and depart times.
In essence, this will give me any instance of a trip departing 'BER2' before a trip already at 'BER3' has departed.
Query 1
SELECT RTDEV.TRIP_HEADERS.TRIP_NAME, RTDEV.TRIP_BODIES.ARRIVAL_TIME, RTDEV.TRIP_BODIES.DEPARTURE_TIME
FROM RTDEV.TRIP_HEADERS INNER JOIN
RTDEV.TRIP_BODIES ON RTDEV.TRIP_HEADERS.TME_ID = RTDEV.TRIP_BODIES.TME_ID AND
RTDEV.TRIP_HEADERS.THR_ID = RTDEV.TRIP_BODIES.THR_ID INNER JOIN
RTDEV.TNODED ON RTDEV.TNODED.NID = RTDEV.TRIP_BODIES.CURRENT_NODE
WHERE (RTDEV.TNODED.STRSHORTNAME = 'BER3') AND (RTDEV.TRIP_BODIES.TME_ID = 9860)
Query 2
SELECT TRIP_HEADERS_1.TRIP_NAME, TRIP_BODIES_1.ARRIVAL_TIME, TRIP_BODIES_1.DEPARTURE_TIME
FROM RTDEV.TRIP_HEADERS TRIP_HEADERS_1 INNER JOIN
RTDEV.TRIP_BODIES TRIP_BODIES_1 ON TRIP_HEADERS_1.TME_ID = TRIP_BODIES_1.TME_ID AND
TRIP_HEADERS_1.THR_ID = TRIP_BODIES_1.THR_ID INNER JOIN
RTDEV.TNODED TNODED_1 ON TNODED_1.NID = TRIP_BODIES_1.CURRENT_NODE
WHERE (TNODED_1.STRSHORTNAME = 'BER2') AND (TRIP_BODIES_1.TME_ID = 9860)
Any suggestions?
It's simple - you can put the query2 inside an inline view (a view in the FROM clause) like this:
SELECT TRIP_HEADERS_1.TRIP_NAME, TRIP_BODIES_1.ARRIVAL_TIME, TRIP_BODIES_1.DEPARTURE_TIME
FROM RTDEV.TRIP_HEADERS TRIP_HEADERS_1 INNER JOIN
RTDEV.TRIP_BODIES TRIP_BODIES_1 ON TRIP_HEADERS_1.TME_ID = TRIP_BODIES_1.TME_ID AND
TRIP_HEADERS_1.THR_ID = TRIP_BODIES_1.THR_ID INNER JOIN
RTDEV.TNODED TNODED_1 ON TNODED_1.NID = TRIP_BODIES_1.CURRENT_NODE
-- PUT YOUR QUERY 2 HERE --
JOIN (SELECT RTDEV.TRIP_HEADERS.TRIP_NAME, RTDEV.TRIP_BODIES.ARRIVAL_TIME, RTDEV.TRIP_BODIES.DEPARTURE_TIME
FROM RTDEV.TRIP_HEADERS INNER JOIN
RTDEV.TRIP_BODIES ON RTDEV.TRIP_HEADERS.TME_ID = RTDEV.TRIP_BODIES.TME_ID AND
RTDEV.TRIP_HEADERS.THR_ID = RTDEV.TRIP_BODIES.THR_ID INNER JOIN
RTDEV.TNODED ON RTDEV.TNODED.NID = RTDEV.TRIP_BODIES.CURRENT_NODE
WHERE (RTDEV.TNODED.STRSHORTNAME = 'BER3') AND (RTDEV.TRIP_BODIES.TME_ID = 9860)) query2
-- AND PUT A JOIN CONDITION --
ON TRIP_BODIES_1.DEPARTURE_TIME BETWEEN query2.ARRIVAL_TIME AND query2.DEPARTURE_TIME
WHERE (TNODED_1.STRSHORTNAME = 'BER2') AND (TRIP_BODIES_1.TME_ID = 9860)