Tables joined without common fields - sql-server

I have a SQL Server Database which has 2 tables
Client Table
Name Employment Race
Ronald 867 452
Arnold 845 123
Lookup Table
lookup_id Detail
867 Unemployed
845 Part time employed
452 White
123 Black
The numeric entries point to the primary key of LookUp table called lookup_id. Corresponding to each lookup_id (867,856 etc.) is the actual Employment or Race description in text - Unemployed, White etc. More Client fields follow the same referencing.
However, the lookup_id field by itself does not exist in the Client table. It seems to me that the two tables are linked without a PK,FK reference. Is this possible? Passing a key entry directly into a field to join tables? How do I query these tables together?

You can do that via a query like this.
new query:
SELECT Name, L1.Detail AS Employment, L2.Detail as Race
FROM Client C LEFT OUTER JOIN Lookup L1
ON C.Employment=L1.lookup_id
LEFT OUTER JOIN Lookup L2
ON C.Race=L2.lookup_id
old query:
SELECT Name, Detail
FROM Client C LEFT OUTER JOIN Lookup L
ON C.Employment=L.lookup_id
A FK need not have same name as PK in the FK table, like here Employment and Race columns are foreign key value for Lookup.
Also you should but not necessarily have a FK PK relation defined between tables. This is a common practice in Data warehousing.

Related

Join two one-to many tables on different databases to compare the many items

I have two tables on two databases on same server, each with a one to many relationship on the Asset/Equipment. I need to compare the Asset/Equipment in the two databases.
Here are the tables on one database-
Database 1:
Table1:
Application - one
-APP_KEY primary key
Table2:
Asset - many
-AS_APP_FKEY foreign key
-SampleAsset1
-SampleAsset2
-SampleAsset3
Database 2:
Table3:
Application - one
-ApplicationId primary key
-App_Key nullable, this ends up being the APP_KEY on database 1
Table4:
Equipment - many
-EquipID primary key
-ApplicationId foreign key of application
-SampleEquip1
-SampleEquip2
-SampleEquip3
Is there a way to make a query to show SampleEquip1 next to sampleAsset1 based on these relationships.
Edit:
This is the query I have tried but it creates duplicate items. For example if there is four items in each child table it creates 8 comparison rows with duplicates and distinct doesn't remove the duplicates.
SELECT app.APP_KEY,
e.SampleEquip1,
secondDb.APP_KEY,
secondDb.SampleAsset1
FROM dabatase1.dbo.Application app
JOIN database1.dbo.Equipment e
ON e.ApplicationId = app.ApplicationId
LEFT JOIN(
SELECT ap.APP_KEY,
a.SampleAsset1
FROM database2.dbo.Application ap
JOIN database2.dbo.Asset a
ON a.AS_APP_FKEY = ap.APP_KEY
) secondDb
ON secondDb.APP_KEY = app.APP_KEY
WHERE app.APP_KEY = 123

Table keys for SSAS project?

I'm creating a very basic cube with the data that I have. This is my scenario; please let me know if I'm approaching this the wrong way.
In our case, there's data in fact table FactSalesDaily that my dim table DimEmp doesn't have, and I want to know what that data is.
I have three tables: FactSalesDaily, DimDate, DimEmp
[FactSalesDaily]
EmpKey DateKey SalesAmount
194 20170125 45.30
195 20170125 21.00
[DimDate]
DateKey FullDate
20170125 01-25-2017
[DimEmp]
EmpKey FullName
194 Joe Smith
As you can see, my fact table has EmpKey 195 that's not part of DimEmp. My understanding is that in the Data Source View Wizard, when I click on Add Related Tables, the wizard will display the related tables based on the foreign keys for fact table FactSalesDaily.
In my particular case, I would like to see the total sales for employee 195. But I can't add a foreign key of FactSalesDaily to DimEmp because 195 doesn't exist.
As a result, Data Source View Wizard will not select DimEmp because there's not relationship between the two tables.
How am I supposed to deal with this issue? I can add a bogus row in DimEmp for all the employees that don't exist, but then I'd have to alter FactSalesDaily by replacing 195 with this bogus row.
Thanks.

Selecting multiple rows of many to many related columns into one column in SQL SERVER?

I have the following DB Tables with SQL Server
Booking(bookingID,customerName,branchID,RefNumber,...)
Trip(TripID,vehicleID,...)
BookingToTripMap(TripID,bookingID)
Branch(branchID, branchName)
Vehicle(vehicleID,vehicleNumber)
There is a one to one relationship between (Booking,Branch) and (Trip, Vehicle) and Many to many relationship between Booking, Trip which is saved in the table BookingToTripMap.
Now I want to extract a query that would return the following
Booking.RefNumber Booking.CustomerName Vehicle.VehicleNumber
(All vehicle numbers in one cell)
Here is your query
SELECT B.RefNumber, B.CustomerName, V.VehicleNumber
FROM ((Booking AS B INNER JOIN BookingToTripMap AS BT
ON B.bookingID = BT.bookingID) INNER JOIN TRIP as T
ON T.TripID = BT.TripID) INNER JOIN Vehicle as V
ON V.vehicleID = T.vehicleID
I would add the field bookingID to the table Trip, it seems that the table BookingToTripMap doesn't add any value to your database.
Also, if your vehicle's numbers are unique, you could change the primary key in the Vehicle table to vehicleNumber, and change the same columns in the Trip table. Thus you could retrieve the vehicleNumber directly from the Trip table.
I'm just guessing in that, based on the given information.
Regards,

One to Many Database Table Relationship

I do have two tables from the database..
Consultation Table
-ConsultationNo -PK
-PatientNo -FK
-Diagnosis
-Etc...
VitalSign Table
-VitalSignNo -PK
-Weight
-Height
-HeartRate
-BloodPressure
-Etc
I need to join these two tables like this..
Consultation Table
-ConsultationNo -PK
-PatientNo -FK
**-VitalSignNo** -FK
-Diagnosis
-Etc...
But sometimes, my VitalSign Table will not accept any values, therefore the relationship between those two tables would not be enforced, what should I do?
Use an outer join like so...
Select * from Consultation
Left join VitalSign on (Consultation.ConsultationNo = vitalsign.ConsultationNo)
You will get all rows from consultation, and the matching rows from Vitalsign. When there are no rows in Vitalsign all those columns will come back null, but you will still get the consultation rows.
This might not be exactly right for your situation because the table structure in your question doesn't look complete. That, is you didn't have a foreign key in either table referencing the PK of the other.

Recommended approach to merging two tables

I have a database schema like this:
[Patients] [Referrals]
| |
[PatientInsuranceCarriers] [ReferralInsuranceCarriers]
\ /
[InsuranceCarriers]
PatientInsuranceCarriers and ReferralInsuranceCarriers are identical, except for the fact that they reference either Patients or Referrals. I would like to merge those two tables, so that it looks like this:
[Patients] [Referrals]
\ /
[PatientInsuranceCarriers]
|
[InsuranceCarriers]
I have two options here
either create two new columns - ID_PatientOrReferral + IsPatient (will tell me which table to reference)
or create two different columns - ID_Patient and ID_Referral, both nullable.
Generally, I try to avoid nullable columns, because I consider them a bad practice (meaning, if you can live w/o nulls, then you don't really need a nullable column) and they are more difficult to work with in code (e.g., LINQ to SQL).
However I am not sure if the first option would be a good idea. I saw that it is possible to create two FKs on ID_PatientOrReferral (one for Patients and one for Referrals), though I can't set any update/delete behavior there for obvious reasons, I don't know if constraint check on insert works that way, either, so it looks like the FKs are there only to mark that there are relationships. Alternatively, I may not create any foreign keys, but instead add the relationships in DBML manually.
Is any of the approaches better and why?
To expand on my somewhat terse comment:
I would like to merge those two tables
I believe this would be a bad idea. At the moment you have two tables with good clear relation predicates (briefly, what it means for there to exist a record in the table) - and crucially, these relation predicates are different for the two tables:
A record exists in PatientInsuranceCarriers <=> that Patient is associated with that Insurance Carrier
A record exists in ReferralInsuranceCarriers <=> that Referral is associated with that Insurance Carrier
Sure, they are similar, but they are not the same. Consider now what would be the relation predicate of a combined table:
A record exists in ReferralAndPatientInsuranceCarriers <=> {(IsPatient is true and the Patient with ID ID_PatientOrReferral) or alternatively (IsPatient is false and the Referral with ID ID_PatientOrReferral)} is associated with that Insurance Carrier
or if you do it with NULLs
A record exists in ReferralAndPatientInsuranceCarriers <=> {(ID_Patient is not NULL and the Patient with ID ID_Patient) or alternatively (ID_Referral is not NULL and the Referral with ID ID_Referral)} is associated with that Insurance Carrier
Now, I'm not one to automatically suggest that more complicated relation pedicates are necessarily worse; but I'm fairly sure that either of the two above are worse than those they would replace.
To address your concerns:
we now have two LINQ to SQL entities, separate controllers and views for each
In general I would agree with reducing duplication; however, only duplication of the same things! Here, is it not the case that all the above are essentially 'boilerplate', and their construction and maintenance can be delegated to suitable development tools?
and have to merge them when preparing data for reports
If you were to create a VIEW, containing a UNION, for reporting purposes, you would keep the simplicity of the actual data and still have the ability to report on a combined list; eg (making assumptions about column names etc):
CREATE VIEW InterestingInsuranceCarriers
AS
SELECT
IC.Name InsuranceCarrierName
, P.Name CounterpartyName
, 'Patient' CounterpartyType
FROM InsuranceCarriers IC
INNER JOIN PatientInsuranceCarriers PIC ON IC.ID = PIC.InsuranceCarrierID
INNER JOIN Patient P ON PIC.PatientId = P.ID
UNION
SELECT
IC.Name InsuranceCarrierName
, R.Name CounterpartyName
, 'Referral' CounterpartyType
FROM InsuranceCarriers IC
INNER JOIN ReferralInsuranceCarriers RIC ON IC.ID = RIC.InsuranceCarrierID
INNER JOIN Referral R ON PIC.ReferralId = R.ID
Copying my answer from this question
If you really need A_or_B_ID in TableZ, you have two similar options:
1) Add nullable A_ID and B_ID columns to table z, make A_or_B_ID a computed column using ISNULL on these two columns, and add a CHECK constraint such that only one of A_ID or B_ID is not null
2) Add a TableName column to table z, constrained to contain either A or B. now create A_ID and B_ID as computed columns, which are only non-null when their appropriate table is named (using CASE expression). Make them persisted too
In both cases, you now have A_ID and B_ID columns which can have appropriate foreign
keys to the base tables. The difference is in which columns are computed. Also, you
don't need TableName in option 2 above if the domains of the 2 ID columns don't
overlap - so long as your case expression can determine which domain A_or_B_ID
falls into

Resources