Select one record from a nested sql select - sql

Help - I have puzzeled on this for some time and am going bats.
In this cutdown query I want to select a single Email address from a contacts list that may contain multiple contacts for that customer.
My problem is that it does not find the Contacts email if I specify TOP 1
(showing NULL for CC.Email)
Note: it returns two records with Contact emails if I specify TOP 5
I think the TOP 1 must be restricting the records to 1 before determining a match?
SELECT C.Code as Customer, C.Name as CustomerName, C. Email, CC.Email, IIF(CC.Email<>'',CC.Email,C.Email) as Email
FROM [dr].[Customer] C
LEFT OUTER JOIN (Select TOP 1 CustomerId, Email
from dr.Contact CC
INNER JOIN dr.ContactDocumentOption CDO
on CDO.TransactionTypeId = 102
AND CDO.ContactId = CC.ContactId
Order by CC.ContactId) CC
on CC.CustomerId = C.CustomerId
WHERE C.Code = 'B82'

Well, it's a bit hard to understand your question, but i guess you have multiple rows of the same customer, but not every row has values in the email column, am I right?
For this you should try including WHERE Email IS NOT NULL in your SQL string, the part with TOP 1 is good, but try to make the SQL statement return values only if it finds an email, using Email IS NOT NULL.
I hope I understood your question and that this helps you.

Have you tried to LEFT JOIN directly the second request instead of using a nested request? And then you take TOP 1 on the main request?
It would be easier to help if you had a SQL fiddle.

You can combine the data from Contacts with [SQL Row_Number() function][1] and additional Partition By clause as follows
Please note instead of TOP, I used Row_number function and used the result in WHERE clause with rn=1 for choosing the top 1
;with cte as (
select
c.Code as Customer, c.Name as CustomerName, c.Email CustomerEmail, cc.Email ContactEmail,
rn = ROW_NUMBER() over (partition by c.CustomerId order by cc.Email desc)
from Customer c
left join Contact cc on c.CustomerId = cc.CustomerId
left join ContactDocumentOption o on o.TransactionTypeId = 102
and o.ContactId = cc.ContactId
where c.Code = 'B82'
)
select Customer, CustomerName, ISNULL(ContactEmail,CustomerEmail) Email
from cte where rn = 1
ISNULL() function is a better way to compare two fields according to one of the field's nullable case
Output is as follows

Related

I need to match special character, how can I write query to get the required output?

I want mail which is common at supplier's and customer's tables only, I don't
want emails that don't match in customer's table with the supplier's mail. Unfortunately,
we don't have similar IDs to join so if possible can we join with the mail only,
if not then we can consider common IDs and join them.
following tables for your reference and output that I want
The proper solution is to normalize your database design to not store multiple values in the same column. However, I expect that is water under the bridge.
Given the data that you have, you can use STRING_SPLIT() to separate the emails from the SUPPLIERS table and then join with CUSTOMERS.
SELECT S.ID, C.EMAIL
FROM SUPPLIERS S
CROSS APPLY (
SELECT value AS EMAIL
FROM STRING_SPLIT(S.EMAIL, ',')
) E
JOIN CUSTOMERS C ON C.EMAIL = E.EMAIL
See this db<>fiddle
If your data may have any spaces mixed in, you may need to add TRIM() to the STRING_SPLIT() result - SELECT TRIM(value) AS EMAIL.
Select CC.ID, CC.email from
(
SELECT ROW_NUMBER() OVER (ORDER BY ID ASC) AS AID,a.*
FROM Suppliers a
) as AA
left outer join
(
Select BB.* from
(
SELECT ROW_NUMBER() OVER (ORDER BY ID ASC) AS BID,b.*
FROM Customers b
) as BB
) as CC
on AA.AID = CC.BID

Can we select first row of data from column in sql?

I have a table with multiple data for same ID. I want to get the first row data for the ID.
I have added the below SQL that I have tried.
SELECT
"client"."id",
"client"."company_name",
"client_details"."address"
from Client
LEFT OUTER JOIN "client_details" ON ("client"."id" = "client_details"."client_id")
Since I have multiple address for the same ID, can we get only the first id?
Currently the output I get is 2 rows with different addresses.
You can add to your SQL LIMIT 1 and in case you want to be sure the order you can also add to your SQL ORDER BY...
You can use distinct on:
select distinct on (c.id) c.id, c.company_name, cd.address
from Client c left join
client_details cd
on c.id = cd.client_id
order by c.id, ?;
The ? is for the column that specifies the ordering (the definition of "first"). I am guessing that cd.id is what you want.
Note that this query removes the double quotes and introduces table aliases. This is easier on both the eyes (to read) and the fingers (to type).
use row_number()
select * from
(
SELECT
"client"."id",
"client"."company_name",
"client_details"."address",row_number() over(partition by "client"."id" order by "client_details"."address") as rn
from Client
LEFT OUTER JOIN "client_details" ON "client"."id" = "client_details"."client_id"
)A where rn=1
If there is a field you can order the results by you could use a lateral join e.g.
SELECT
"client"."id",
"client"."company_name",
"client_details"."address"
from Client
left join lateral (
select *
from client_details cd
where cd.client_id = client.id
order by [some_ordering_field]
limit 1
) "client_details" on true

Oracle sql query that returns customers who are coming for the first time in property

I have 3 tables: customer, property and stays. Table customer contains all the data about customers (customer_id, name, surname, email...). Table property contains the list of all the properties (property_id, property_name...) and table stays contains all the earlier stays of customers (customer_id, property_id, stay_id, arrival_date, departure_date...).
Some customers stayed multiple times in more than one properties and some customers are coming for the first time.
Can someone please explain oracle sql query which returns only the customers who are stying in any of the properties for the first time.
Sorry guys for answering late..
This is what I got so far.
Tables:
Customer $A$
Stays $B$
Property $C$
Customer_Fragments $D$
SELECT a.RIID_,
sub.CUSTOMER_ID_,
sub.PROPERTY_ID,
b.ARRIVAL_DATE,
c.PROPERTY_SEGMENT,
ROW_NUMBER() OVER (
PARTITION BY sub.CUSTOMER_ID_,
sub.PROPERTY_ID
ORDER BY
sub.CUSTOMER_ID_ asc
) RN
FROM
(
SELECT
b.CUSTOMER_ID_,
b.PROPERTY_ID
FROM
$B$ b
GROUP BY
b.CUSTOMER_ID_,
b.PROPERTY_ID
HAVING
COUNT(*)= 1
) sub
INNER JOIN $A$ a ON sub.CUSTOMER_ID_ = a.CUSTOMER_ID_
INNER JOIN $B$ b ON sub.CUSTOMER_ID_ = b.CUSTOMER_ID_
INNER JOIN $C$ c ON sub.PROPERTY_ID = c.PROPERTY_ID
LEFT JOIN $D$ d ON a.RIID_ = d.RIID_
WHERE
b.ARRIVAL_DATE = TRUNC(SYSDATE + 7)
AND c.PROPERTY_DESTINATION = 'Destination1'
AND lower(c.NAME_) NOT LIKE ('unknown%')
AND a.NWL_PERMISSION_STATUS = 'I'
AND a.EMAIL_DOMAIN_ NOT IN ('abuse.com', 'guest.booking.com')
AND (d.BLACKLISTED != 'Y'
or d.BLACKLISTED is null
)
I want to select all customers who will come to Destination1, 7days from today to inform them about some activities. Customers can book several
properties in Destination1 and have the same arrival date (example: I can book a room in property1 for me and my wife and also book a room in property2 for my friends.. and we all come to destination1 on the same arrival date).
When this is the case I want to send just one info email to a customer and not two emails. The above SQL query returns two rows when this is the case and I want it to return just one row (one row = one email).
It is always required to post a code you have already tried to write so that we can than help you with eventual mistakes.
After that being said, I'll try to help you nevertheless, writing the full code.
Try this:
select cus.*
from customers cus
join stays st
on st.customer_id = cus.customer_id
where st.arrival_date >= YOUR_DATE --for example SYSDATE or TRUNC(SYSDATE)
and 1 = (select count(*)
from stays st2
where st2.customer_id = cus.customer_id)
You haven't specified it, but I GUESS that you are interested in getting the first-time-customers whose arrival date will be at or after some specified date. I've written that into my code in WHERE clause, where you should input such a date.
If you remove that part of the WHERE clause, you'll get all the customers that stayed just once (even if that one and only stay was 10 years ago, for example). What's more, if you remove that part of the code, you can than also remove the join on stays st table from the query too, as the only reason for that join was the need to have access to arrival date.
If you need explanations for some other parts of the code too, ask in the comments for this answer.
I hope I helped!
WITH first_stays (customer_id, property_id, first_time_arrival_date, stay_no) AS
(
SELECT s.customer_id
, s.property_id
, s.arrival_date AS first_time_arrival_date
, ROW_NUMBER() OVER (PARTITION BY s.customer_id, s.property_id ORDER BY s.arrival_date) stay_no
FROM stays s
)
SELECT c.surname AS customer_surname
, c.name AS customer_name
, p.property_name
, s.first_time_arrival_date
FROM customer c
INNER
JOIN first_stays s
ON s.customer_id = c.customer_id
AND s.stay_no = 1
INNER
JOIN property p
ON p.property_id = s.property_id
The first part WITH first_stays is a CTE (Common Table Expression, called subquery factoring in Oracle) that will number the stays for each pair (customer_id, property_id) ordered by the arrival date using a window function ROW_NUMBER(). Then just join those values to the customer and property tables to get their names or whatever, and apply stay_no = 1 (first stay) condition.
If I understand the question correctly, this is not a complicated query:
select c.*
from c join
(select s.customer_id
from stays s
group by s.customer_id
having count(*) = 1
) s
on s.customer_id = c.customer_id;

Combine 2 SQL SELECT statements

** Evidently some people think my question is not worthy of their time. I whole heartedly appologise for this. However, rather than down voting why not use that time to do something positive and at least tell me what info you would require to make this not be a cr#p question in your eyes. **
I have a list of staff in table tblMembers and a list of clients in table tblClients.
One person may have several client.
The staff member associated with a client is identified by staffId against the client record.
Each staff member has a category Id for the type of clients they have catId.
I need to find all of the staff for a given client type and then sort them by the number of clients they have. Staff members without any clients should show a result of 0 rather than not showing.
A simplified table structure would be:
tblMembers:
Id | catId
tblClients:
Id | staffId
Any help would be greatly appreciated.
Thanks!
Try this:
SELECT m.Id 'Member Id', ISNULL(c.StaffCount, 0) 'StuffCount'
FROM tblMembers m
LEFT JOIN
(
SELECT staffId, COUNT(staffId) 'StaffCount'
FROM tblClients
GROUP BY staffId
) c ON m.Id = c.staffId
WHERE m.Cat = 'Some Id'
ORDER BY StuffCount
Its fairly simple to do a join/group and count
SELECT
s.id,
s.catid,
COUNT(c.id)
FROM
tblMembers s
LEFT JOIN tblClients c
ON s.id = c.staffid
WHERE
s.catid = #catID
GROUP BY
s.id,
s.catid
ORDER BY
COUNT(c.id) desc
However the one tricky bit is
show a result of 0 rather than not showing.
To do this you need to do a left join to make sure they show even if there are no matching records and you need to make sure to count a field on the table on the Right side of the join. Otherwise you'd get a count of 1
DEMO
Hope I correctly understood your case.
Try something like this:
SELECT T1.ID,
Count(*)
FROM MEMBERS T1
INNER JOIN CLIENTS T2
ON T1.ID = T2.STAFFID
WHERE T1.CATID = 2
GROUP BY T1.ID
UNION
SELECT DISTINCT ID,
0
FROM MEMBERS
WHERE CATID != 2
A working sample is available here.
try:
select tblMembers.id, count(tblClient.id)
from tblMembers left join tblCLient on staffId = tblMembers.id
where tblMembers.catId = ??
group by tblMembers.id
order by 2 desc

SQL query for join with condition

I have these two tables:
Customers: Id, Name
Orders: Id, CustomerId, Time, Status
I want to get a list of customers for which the LAST order does not have a status of 'Wrong'.
I know how to use a LEFT JOIN to get a count of orders for each customer, but I don't know how I can use this statement for what I want. Maybe a JOIN is not the right thing to use too, I'm not sure.
It's possible that customers do not have any order, and they should be returned.
I'm abstracting the real tables here, but the scenario is for a windows phone app sending notifications. I want to get all clients for which their last notification does not have a 'Dropped' status. I can sort their notifications (orders) by the 'Time' field. Thanks for the help, while I continue experimenting with subqueries in the where clause.
Select ...
From Customers As C
Where Not Exists (
Select 1
From Orders As O1
Join (
Select O2.CustomerId, Max( O2.Time ) As Time
From Orders As O2
Group By O2.CustomerId
) As LastOrderTime
On LastOrderTime.CustomerId = O1.CustomerId
And LastOrderTime.Time = O1.Time
Where O1.Status = 'Dropped'
And O1.CustomerId = C.Id
)
There are obviously alternatives based on the actual database product and version. For example, in SQL Server one could use the TOP command or a CTE perhaps. However, without knowing what specific product is being used, the above solution should produce the results you want in almost any database product.
Addition
If you were using a product that supported ranking functions (which database product and version isn't mentioned) and common-table expressions, then an alternative solution might be something like so:
With RankedOrders As
(
Select O.CustomerId, O.Status
, Row_Number() Over( Partition By CustomerId Order By Time Desc ) As Rnk
From Orders As O
)
Select ...
From Customers
Where Not Exists (
Select 1
From RankedOrders As O1
Where O1.CustomerId = C.Id
And O1.Rnk = 1
And O1.Status = 'Dropped'
)
Assuming Last order refers to the Time column here is my query:
SELECT C.Id,
C.Name,
MAX(O.Time)
FROM
Customers C
INNER JOIN Orders O
ON C.Id = O.CustomerId
WHERE
O.Status != 'Wrong'
GROUP BY C.Id,
C.Name
EDIT:
Regarding your table configuration. You should really consider revising the structure to include a third table. They would look like this:
Customer
CustomerId | Name
Order
OrderId | Status | Time
CompletedOrders
CoId | CustomerId | OrderId
Now what you do is store the info about a customer or order in their respective tables ... then when an order is made you just create a CompletedOrders entry with the ids of the 2 individual records. This will allow for a 1 to Many relationship between customer and orders.
Didn't check it out, but something like this?
SELECT c.CustmerId, c.Name, MAX(o.Time)
FROM Customers c
LEFT JOIN Orders o ON o.CustomerId = c.CustomerId
WHERE o.Status <> 'Wrong'
GROUP BY c.CustomerId, C.Name
You can get list of customers with the LAST order which has status of 'Wrong' with something like
select customerId from orders where status='Wrong'
group by customerId
having time=max(time)