Basic SQL - What’s best possible answer if you know ? - sql-server

In SQL Server, you have a Customer table and an Order table. The relationship between the two tables is the CustomerId field. It’s a foreign key from the Orders back to the primary table Customer. With that in mind, how would you write a query that would retrieve Customers that don’t have Orders.

The following will return all customers on the left of the query and will show a NULL on the right where there are no matching order records.
We then filter to only show those with NULL in the right table.
SELECT *
FROM Customers c
LEFT JOIN Orders o
ON c.CustomerId = o.CustomerId
WHERE o.CustomerId IS NULL
Below is a great diagram explaining the different types of join

Related

Data warehouse Fact table foreign key Generation

I am pretty new to data warehouse designing.
I have a database like below.
https://webpages.charlotte.edu/mirsad/itcs6265/group1/domain.html
I am planning to create a simple data warehouse like below.
But the problem I am facing now is I don't have ClientId and LoanId in the Fact table. Because in the original database it was lnked via Account table.
I am trying to achieve this via SQL server. Can someone show me the direction how to approach this.
If you want to create the FactTransaction fact table you don't need the Loan because it represents a fact so Transaction and Loan are two differnt actions like mentioned in the data dictionary :
TRANSACTIONS (TRANS) Each record describes one transaction on an
account
LOANS Each record describes a loan granted for a given account
the design can be like below if we follow a separate context for each :
Datamart Transaction :
Datamart Loan :
The query to populate the FactTransaction is like below :
SELECT T.account_id AS TransactionID, C.client_id AS ClientID,
A.account_id AS AccountID
FROM Transactions AS T
LEFT JOIN Account AS A ON A.account_id=T.account_id
LEFT JOIN Disposition AS D ON A.account_id=D.account_id
LEFT JOIN Client AS C ON C.client_id=D.client_id
AccountID, TransactionID, ClientID represent a composite key to uniquely identify the tuple transaction in a the fact table.
The query to populate the FactLoan is like below :
SELECT L.account_id AS LoanID, C.client_id AS ClientID,
A.account_id AS AccountID
FROM Loan AS L
LEFT JOIN Account AS A ON A.account_id=A.account_id
LEFT JOIN Disposition AS D ON A.account_id=D.account_id
LEFT JOIN Client AS C ON C.client_id=D.client_id
AccountID, LoanID, ClientID represent a composite key to uniquely identify the tuple transaction in a the fact table.
Do not forget to implement the DimDate.

How do I query three related tables?

I'm new to databases and I'm having a hard time figuring this out. Any assistance would be greatly appreciated
Deliveries Table
-- ID (PK)
-- DriverID (FK to Drivers Table)
Drivers Table
-- ID (PK)
-- LocationID (FK to Locations Table)
Locations Table
-- ID (PK)
-- RestaurantID (FK to Restaurants Table)
Restaurant Table
--ID (PK)
A Restaurant can have multiple locations (1 to many). A location can have multiple drivers (1 to many). a Driver can have multiple deliveries (1 to many). This design is supposed to break things out in 3rd normal form. So if I want to go to the deliveries table and get all of the deliveries associated with a particular restaurant, how would I query or do a join for that? Would I have to add a second foreign key to Deliveries that directly references the Restaurant table? I think after I see the query I can figure out what is going on. Thx
You can use left or right outer join to make a combined table and then you can easily query it, or else you can use a query with multiple sub-queries inside it to attain the required result without using join. Here is an example on how to use sub-query for your use-case.
SELECT ID FROM Deliveries De
WHERE De."DriverID" IN (SELECT ID FROM Drivers Dr
WHERE Dr. "LocationID" IN (SELECT ID FROM Locations L
WHERE L. "RestaurantID" IN (SELECT ID FROM Restaurant)))
I hope this solves your issue without using join statement.
You can use inner join or union depending on what you want to achieve. Example:
SELECT a."articleId" AS id, a.title, a."articleImage" AS "articleImage/url", c.category AS "category/public_id", a."createdOn", concat("firstName", ' ', "lastName") AS author
FROM articles a
INNER JOIN users u ON a."userId" = u."userId"
INNER JOIN categories c ON a."categoryId" = c."categoryId"
UNION
SELECT g."gifId" AS id, g.title, g."imageUrl" AS "articleImage/url", g.public_id AS "category/public_id", g."createdOn", concat("firstName", ' ', "lastName") AS author
FROM gifs g
INNER JOIN users u ON g."userId" = u."userId"
ORDER BY "createdOn" DESC
You can say how you want to get the results for more detailed query.
If I understand what you want to do then it maybe like this,
1st you have to join all those table to get corresponding result you want,
the join condition will be
select <your desire column name>
from Restaurant A,Locations B,Drivers C,Deliveries D
where A.ID = B.RestaurantID
and B.ID = C.LocationID
and C.ID = D.DriverID
Hope this is helpful, fell free to say anything.

SQL query to join "GeneralJournalAccountEntry" to table "CustInvoiceTrans" to get column value "MainAccount"

We have a Dynamics AX 2012 environment backed by SQL Server. We load invoice line data from table "CustInvoiceTrans" into an EDW fact table. We are wanting to find what the "MainAccount" column value is for each invoice line as it relates to table "GeneralJournalAccountEntry". This would need to be done through a SQL query.
I have attempted an Internet search on the topic, but found nothing definitive. I have also searched through the AX SQL views hoping to find a solution there, but did not come across anything. It is possible that I could be missing something though.
SQL Pseudo Example:
SELECT CIT.InvoiceID
,CIT.InvoiceDate
,CIT.SalesPrice
,GJAE.MainAccount
FROM CustInvoiceTrans CIT
LEFT JOIN {..Some table(s)} ST
ON ST.{SomeColumn} = CIT.{SomeColumn}
LEFT JOIN GeneralJournalAccountEntry GJAE
ON GJAE.{SomeColumn} = ST.{SomeColumn}
If this is possible, it would assume that one invoice line relates to one general ledger account entry line to return one MainAccount. I am uncertain if an invoice line could be split among multiple general ledger account entry lines.
It sounds to me like you are worried that you might end up with duplicates when you join the GeneralJournalAccountEntry table? My example shows how you can ensure that the GeneralJournalAccountEntry table has a 1:1 relationship with the CustInvoiceTrans table. I've assumed:
That there is a primary key for your accounts and customers (AccountId and CustomerId)
That there is some table that maps customer's to accounts
SELECT
cit.InvoiceID
, cit.InvoiceDate
, cit.SalesPrice
, t.MainAccount
FROM (
SELECT
gjae.AccountId
, gjae.MainAccount
FROM GeneralJournalAccountEntry gjae
GROUP BY
gjae.AccountId
, gjae.MainAccount
) t
JOIN [SomeTable] st
ON st.AccountId = t.AccountId
JOIN CustInvoiceTrans cit
ON cit.CustomerId = st.CustomerId

SQL Joining journal tables to user tables

I have a MSSQL database with 3 tables: Journals, Customers, and UserAccounts.
I'm trying to query Journals for transactions per account manager. This table has a customer ID column that links to Customers.
The Customers table has a ACC_Manager column that links to UserAccounts via UserID.
Inside the UserAcounts table are first and last name columns.
So it would be
Select
Journal.amount,
Customer.name,
UserAccounts.first
From
Tables
where
Journal.ACC_manager = 'Matt'
I'm having issues joining the tables so I can query using UserAccounts.first. Could anybody help? Thanks
Try the following. I didn't get exact column names so don't just use this code without modifying it a bit to suit your specific needs:
SELECT
j.amount,
c.name,
u.first
FROM
Journals j
JOIN Customers c ON
c.customerID = j.customerID -- Exact column names?
JOIN UserAccounts u ON
u.UserID = c.ACC_Manager
WHERE
u.first = 'Matt'
You may also need to use LEFT JOIN as opposed to JOIN. Read up on JOINs to be sure.

Find matching records of two different tables in SQL Server

I have two tables in one of them a seller saves a record for a product he is selling. and in another table buyers save what they need to buy.
I need to get a list of user ids (uid field) from buyers table which matches a specific product on sales table. this is what I have written:
select n.[uid]
from needs n
left join ads(getdate()) a
on n.mid=a.mid
and a.[year] between n.from_year and n.to_year
and a.price between n.from_price and n.to_price
and n.[uid]=a.[uid]
and a.pid=n.pid
Well I need to use a where clause to eliminate those records which doesn't match. as I think all of these conditions are defined with ON must be defined with a where clause. but joining needs at least one ON clause. may be I shouldn't join two tables? what can I do?
There is an important difference between LEFT JOIN and JOIN, or more accurately OUTER and INNER joins respectively.
Inner joins require that both sides of the join match. In other words, if you:
had a table representing People
you had another table representing Automobiles
and each automobile had a PersonId
and joined these tables using ON with the PersonId
using LEFT (OUTER) JOIN would return all people, even those without automobiles. INNER JOIN only returns the people with vehicles.
This article may help: http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Resources