Return unique row only - TSQL - sql

I have a customer table and order tables. In customer table we have 'Family link' column which is a given ID to each customer. e.g. familyLink: A121, if this customer has a family member in the table they will have this ID too : A121. Basically I need to return all customers with no family members and have made an order_number 2 or 3
Customer table:
CustmID(PK), Name(varchar), familyLink(varchar).
Order table:
OrderID(PK), order_number (varchar), CustmID(FK)
The query I've return which didn't seem to return customers with no family member..
Select Distinct
c.familyLink,
c.name,
o.order_number
From
Customer c
Left join
Order o on c.CustmID = o.CustmID
where
(o.order_number = 2 or order_number=3)
Examples:
Customer table
Custm ID Name FamilyLink
C1 Liam A11
C2 Lucy A12
C3 David A11
C4 Suzy A13
Orders table
OrderID Order_Number CustmID
O1 2 C1
O2 3 C2
O3 2 C4
Results`
This query should return Lucy and Suzy because they don't have any family members in the customer table..
Any idea why this is returning customers who share familyLink?
Any help appreciated.

Any idea why this is returning customers who share familyLink ?
Because nothing in your query is limiting it to that. You're asking for all rows where you the o.order_number = 2 or order_number = 3; there's nothing about "not returning customers that don't have a family link".
You also have a syntax error in your SQL, specifically Left join Order. ORDER is a Reserved Keyword in SQL Server, and in most (if not every) SQL language. It is strongly advised that you do not give objects names that are a Reserved keyword or a Future Keyword. If you do have an object that has an Reserved Keyword for a name, you must quote it: [Order].
As for what you are after, this is a total guess, but perhaps:
WITH CTE AS(
SELECT C.familyLink,
C.name,
O.order_number,
COUNT(C.CustmID) OVER (PARTITION BY O.order_number) AS Customers
FROM Customer C
INNER JOIN [Order] O ON C.CustmID = O.CustmID --This is an INNER JOIN, as the WHERE must be met, so there can never not be a row
WHERE O.order_number IN (2,3))
SELECT C.familyLink,
C.name,
C.order_number
FROM CTE
WHERE Customers = 1;
If this doesn't work, you'll need to provide sample data and expected results. I put this an answer, however, as my opening statements were also far too long for a comment.

Related

SQL JOIN to get the compare two values/row from table "A" and the same row from table "B"

I have two tables with the following rows
Table A (transaction)
Order Seller Customer
1 300 500
Table B (Persons)
PersonID FullName
300 Peter White
500 Scott Bold
I want a result like this
Order Seller Customer FullName (Seller) FullName (customer)
1 300 500 Peter White Scott Bold
I've tried multiple things however which makes more sense is a join a table twice, however I'm getting:
Ambiguous column name
This is SQL Server 2019.
Basically I'm looking to retrieve info from the same table instead of creating additional tables. Is that possible? If yes, how do you do? Thank you in advance.
As #jarlh wrote in comment:
select t.order, t.seller, t.customer, sel.fullname, cust.fullname
from transaction t
join persons sel -- sel is an alias to persons table
on sel.personid = t.seller
join persons cust
on cust.personid = t.customer;
Query with join will return the result as long as both seller and customer exist in persons table -- here it should as source table names transactions :).
I have another form of query it still join table B twice.
This is archaic syntax which I don't recommend but for beginner know the concept of JOIN:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A,B where A.Seller=B.PersionID
) t, B where t.Customer=B.PersionID
The proper way of JOIN:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A JOIN B ON A.Seller=B.PersionID
) t JOIN B ON t.Customer=B.PersionID
Hoping this can help you.

Listing Pairs on same table with different criteria on Oracle Sql

I need to list pairs of customer names as follows;
> CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME, CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME
such that each pair of customers has the same zip code (which is also in the customers table).
On the task there is a hint which says
HINT: Your output should have four columns: CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME, CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME
This is what I have written so far:
SELECT DISTINCT CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME, CUSTOMER_FIRST_NAME, CUSTOMER_LAST_NAME
FROM CUSTOMERS
WHERE CUSTOMER_ZIP = CUSTOMER_ZIP
But I am not sure how to continue since I've only started learning SQL yesterday. I have also tried to Join the same table which resulted in ambiguity errors.
Update#1:
I've written this code using aliases as suggested by #kpater87
SELECT DISTINCT C1.CUSTOMER_FIRST_NAME, C1.CUSTOMER_LAST_NAME , C2.CUSTOMER_FIRST_NAME, C2.CUSTOMER_LAST_NAME
FROM CUSTOMERS C1
INNER JOIN CUSTOMERS C2
ON C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP
But even though I have a distinct statement it will show duplicate data. Is this to be expected or am I missing something?
Your updated query looks fine. The only problem in your query is it will be joining also the same records.
If you have a primary key in the table you can improve your query by adding WHERE condition:
SELECT DISTINCT C1.CUSTOMER_FIRST_NAME,
C1.CUSTOMER_LAST_NAME ,
C2.CUSTOMER_FIRST_NAME,
C2.CUSTOMER_LAST_NAME
FROM CUSTOMERS C1
INNER JOIN CUSTOMERS C2
ON C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP
WHERE C1.PK <> C2.PK;
PK - is a column being a primary key in the table.
If you don't have primary key you can try this one:
SELECT C1.CUSTOMER_FIRST_NAME,
C1.CUSTOMER_LAST_NAME ,
C2.CUSTOMER_FIRST_NAME,
C2.CUSTOMER_LAST_NAME
FROM CUSTOMERS C1
INNER JOIN CUSTOMERS C2
ON C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP
WHERE C1.CUSTOMER_FIRST_NAME <> C2.CUSTOMER_FIRST_NAME
AND C2.CUSTOMER_LAST_NAME <> C2.CUSTOMER_LAST_NAME
But there still be a problem that in your output you will get e.g.
Mary Smith James Bond
James Bond Mary Smith
To remove permutations:
SELECT C1.CUSTOMER_FIRST_NAME,
C1.CUSTOMER_LAST_NAME ,
C2.CUSTOMER_FIRST_NAME,
C2.CUSTOMER_LAST_NAME,
C1.CUSTOMER_ZIP
FROM T_CUSTOMERS C1
LEFT JOIN T_CUSTOMERS C2
ON (C1.CUSTOMER_ZIP = C2.CUSTOMER_ZIP
AND
C1.CUSTOMER_NUMBER > C2.CUSTOMER_NUMBER );
See also: SQL: self join using each rows only once

Two group by tables stich another table

I have 3 tables I need to put together.
The first table is my main transaction table where I need to get distinct transaction id numbers and company id. It has all the important keys. The transaction ids are not unique.
The second table has item info which is linked to transaction id numbers which are not unique and I need to pull items.
The third table has company info which has company id.
Now I've sold some of these with the first one through a group by id. The second through a subquery which creates unique ids and joins onto the first one.
The issue I'm having is the third one by company. I cannot seem to create a query that works in the above combinations. Any ideas?
As suggested here is my code. It works but that's because for the company I used count which doesn't give the correct number. How else can I get the company number to come out correct?
SELECT
dep.ItemIDAPK,
dep.TotalOne,
dep.company,
company.vendname,
appd.ItemIDAPK,
appd.ItemName
FROM (
SELECT
csi.ItemIDAPK,
sum(f.TotalOne) as TotalOne,
count(f.DimCurrentcompanyID) company
FROM dbo.ReportOne F with (nolock)
INNER JOIN dbo.DSaleItem csi with (nolock)
on f.DSaleItemID = csi.DSaleItemID
INNER JOIN dbo.DimCurrentcompany cv
ON f.DimCurrentcompanyID = cv.DimCurrentcompanyID
INNER JOIN dbo.DimDate dat
on f.DimDateID = dat.DimDateID
where (
dat.date >='2013-01-29 00:00:00.000'
and dat.date <= '2013-01-30 00:00:00.000'
)
GROUP BY csi.ItemIDAPK
) as dep
INNER JOIN (
SELECT
vend.DimCurrentcompanyID,
vend.Name vendname
FROM dbo.DimCurrentcompany vend
) As company
on dep.company = company.DimCurrentcompanyID
INNER JOIN (
SELECT
c2.ItemIDAPK,
ItemName
FROM (
SELECT DISTINCT ItemIDAPK
FROM dbo.dimitem AS C
) AS c1
JOIN dbo.dimitem AS c2 ON c1.ItemIDAPK = c2.ItemIDAPK
) as appd
ON dep.ItemIDAPK = appd.ItemIDAPK
For further information my output is the following example, I know the code executes and the companyid is incorrect as I just put it with a (count) in their to make the above code execute:
Current Results:
Item Number TLS CompanyID Company Name Item Number Item Name
111111 300 303 Johnson Corp 29323 Soap
Proposed Results:
Item Number TLS CompanyID Company Name Item Number Item Name
111111 300 29 Johnson Corp 29323 Soap

Identify duplicate values when using JOIN in Microsoft Access

I have 2 tables that hold values for customers. The first table holds the names of the customer and the second holds information relating to the customer such as transactions.
The first table looks like
CustomerID Name
1 Joe
2 Jane
The second table looks like
TransactID CustomerID Reference
1 1 REF123
2 2 REF123
3 1 REF321
I need to able to identify all duplicates in the reference column as well as the customer it belongs to e.g. Joe, Jane
The code i have at the moment looks like
SELECT o.name, COUNT(p.reference) as RefCount
FROM (t_cust as o
INNER JOIN t_custprop as p
ON o.customerid = p.customerid)
GROUP BY o.name, p.reference
HAVING (COUNT(p.reference)>1)
ORDER BY o.name ASC
As i don't know the possible values that may be duplicates, the code above doesn't return the name of the customer and the reference that may be a duplicate.
Grouping by the item you're counting will always result in the count being 1, which is eliminated by your having clause. This should to the trick:
SELECT o.name, p.reference
FROM t_cust o
INNER JOIN t_custprop p ON o.customerid = p.customerid
WHERE p.reference IN (
SELECT p2.reference
FROM t_custprop p2
GROUP BY p2.reference
HAVING COUNT(p2.customerid) > 1
)
ORDER BY o.name ASC

SQL Syntax Issue with getting sum

Ok I have two tables.
Table IDAssoc has the columnsbill_id, year, area_id.
Table Bill has the columns bill_id, year, main_id, and amount_due.
I'm trying to get the sum of the amount_due column from the bill table for each of the associated area_ids in the IDAssoc table.
I'm doing a select statement to select the sum and joining on the bill_ids. How can I set this up so it will have a single row for each of the associated bills in each area_id from the assoc table. There may be three or four bill_ids associated with each area_id and I need those summed for each and returned so I can use this select in another statement. I have a group by set up for the area_id but it still is returning each row and not summing them up for each area_id. I have the year and main_id specified already in the where clause to return the data that I want, but I can't get the sum to work properly. Sorry I'm still learning and I'm not sure how to do this. Thanks!
Edit- Basically the query I'm trying so far is basically just like the one posted below:
select a.area_id, sum(b.amount_due)
from IDAssoc a
inner join Bill b
on a.bill_id = b.bill_id
where Bill.year = 2006 and bill.bill_id = 11111
These are just arbitrary numbers.
The data this is returning is like this:
amount_due - area_id
.05 1003
.15 1003
.11 1003
65 1004
55 1004
I need one row returned for each area_id with the amount_due summed. The area_id is only in the assoc table and not in the bill table.
select a.area_id, sum(b.amount_due)
from IDAssoc a
inner join Bill b
on a.bill_id = b.bill_id
where b.year = 2006 and b.bill_id = 11111
group by a.area_id
You might want to change inner join to left join if one IDAssoc can have many or no Bill:
select a.area_id, coalesce(sum(b.amount_due),0)
from IDAssoc a
left join Bill b
on a.bill_id = b.bill_id
where b.year = 2006 and b.bill_id = 11111
group by a.area_id
You are missing the GROUP BY clause:
SELECT a.area_id, SUM(b.amount_due) TotalAmount
FROM IDAssoc a
LEFT JOIN Bill b
ON a.bill_id = b.bill_id
GROUP BY a.area_id