How do I join two tables with different column in SQL Server CE? - tsql

How can I joining two tables with different column in SQL Server CE?
I have two tables:
Table Schedule
+-----+----------+------+
+ ID + Name + Type +
+-----+----------+------+
+ 1 + A + 1 +
+ 2 + B + 1 +
+ 3 + C + 2 +
+-----+----------+------+
Table Description
+-----+--------------------+
+ ID + Description +
+-----+--------------------+
+ 1 + A1 - XXXXX +
+-----+--------------------+
And what I want to get is the table like:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+ 2 + B + - +
+ 3 + C + - +
+-----+----------+-----------------+
Where the Description column should be filled in by - when the ID is not on the Description table.
I tried this code:
SELECT S.ID, D.Description
FROM Schedule AS S
INNER JOIN Description AS D
But resulted in:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+ 2 + B + A1 - XXXXX +
+ 3 + C + A1 - XXXXX +
+-----+----------+-----------------+
And when I tried to give ON Clause:
SELECT S.ID, D.Description
FROM Schedule AS S
INNER JOIN Description AS D ON S.ID = D.ID
It just get the row where the ID is on the Description table, like:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+-----+----------+-----------------+
How can I do that?
[UPDATE]
I tried this code and it works:
SELECT S.ID, S.Name, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D ON S.ID = D.ID
But now, how can I add a WHERE clause on it (pls see table SCHEDULE above)?
I tried:
SELECT S.ID, S.Name, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D ON S.ID = D.ID AND S.Type = '1'
But still get the whole rows.

LEFT OUTER JOIN in SQL Server CE
You need to use LEFT OUTER JOIN to join the tables Schedule and Description on the key field ID. Also, use COALESCE to replace NULL values in Description column with -
Script:
SELECT S.ID
, S.Name
, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D
ON S.ID = D.ID
Output:
Tested in Microsoft SQL Server CE version 4.0.8482.1
With WHERE clause
You need add the WHERE clause after the JOINs. If you are planning to having an ORDER BY, it should come after the WHERE clause.
Script:
SELECT S.ID
, S.Name
, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D
ON S.ID = D.ID
WHERE (S.Type = 1)
Output:
Tested in Microsoft SQL Server CE version 4.0.8482.1

You need LEFT OUTER JOIN.
SQLFiddle: http://sqlfiddle.com/#!3/7dccf/1
Query:
select s.ID, s.Name, Coalesce(d.description,'-') as description
from schedule s
left outer join description d on d.id = s.id

SELECT S.ID, D.Description
FROM Schedule AS S FULL OUTER JOIN Description AS D
ON S.ID = D.ID
INNER JOIN means select only rows that exist in both tables.
FULL OUTER JOIN means select rows as long as they exist in one table.
You need FULL OUTER JOIN...

You need to use an OUTER JOIN instead of INNER, and use IsNull or Coalesce to replace NULL values:
SELECT S.ID, Coalesce(D.Description , '-') AS Description
FROM Schedule AS S FULL OUTER JOIN Description AS D
ON S.ID = D.ID

Related

Convert a Postgres query into JPQL

I have the following query in Postgres:
SELECT *
from table1
LEFT OUTER JOIN table1.table2 ON table1.latest_id = table2.id
WHERE table1.table2.status = 0
AND table1.id NOT IN (
(SELECT id from table3 where userId = table2.user))
I do not have the ability to join table1 and table3 and I am stuck writing the subquery in a format JPA will understand - working with a spring boot app. Here is where I got so far in my repository class:
#Query("SELECT c FROM #{#entityName} c JOIN FETCH c.table2 WHERE c.table2.status = 0")
fun findByIdAndStatus(id: String): MyEntity
I have attempted at the subquery as follows, but with no joy - there is a clear syntax error I cannot wrap my head around:
#Query("SELECT c FROM #{#entityName} c JOIN FETCH c.table2 WHERE c.table2.status = 0" AND c.id NOT IN (" +
"SELECT * FROM Table3 WHERE userId = c.table2.user")
Can you help?
Thank you
Assuming:
your SQL query doesn't utilize any input arguments
table1 is mapped by MyEntity and table3 is mapped by Table3 entity
entity associated with table2 is mapped in MyEntity using latest_id join column
status is mapped as a number (i.e Long / Integer)
You can rewrite the query to following JPQL form:
#Query("SELECT t1 FROM MyEntity t1 "
+ "JOIN t1.table2 t2 "
+ "WHERE t2.status = 0 AND t1.id NOT IN ("
+ " SELECT t3.id from Table3 t3 "
+ " WHERE t3.userId = t2.user "
+ ")")
List<MyEntity> findMyEntities();

What is the proper syntax to alias a join that contains a subquery?

I am trying to alias a JOIN that has a subquery.
RIGHT OUTER JOIN
(
SELECT FieldA, FieldB
FROM Table1
JOIN Table2
ON Table1.WellId = Table2.WellId
) AS wi
AS MProd
ON Units.RS_Unit_Name = RTRIM(wi.RS_POOL) + '-' + wi.RS_Field
I get incorrect syntax near 'AS'...
wi is the alias FieldA & FieldB; How do I alias the RIGHT OUTER JOIN?
My original code was:
RIGHT OUTER JOIN TABLE1
AS MProd
ON Units.RS_Unit_Name = RTRIM(wi.RS_POOL) + '-' + wi.RS_Field
which worked fine. I replaced TABLE1 with a subquery which I did in the code sample. I just can't seem to figure out the proper syntax to set MProd as the alias.
The problem is this line of code:
AS wi AS MProd
This is not valid syntax. It can be AS wi or AS MProd, but not AS wi AS MProd.
This is valid:
RIGHT OUTER JOIN
(
SELECT FieldA, FieldB
FROM Table1
JOIN Table2 ON Table1.WellId = Table2.WellId
) AS MProd
ON Units.RS_Unit_Name = RTRIM(MProd.RS_POOL) + '-' + MProd.RS_Field ...
and so is this:
RIGHT OUTER JOIN
(
SELECT FieldA, FieldB
FROM Table1
JOIN Table2 ON Table1.WellId = Table2.WellId
) AS wi
ON Units.RS_Unit_Name = RTRIM(wi.RS_POOL) + '-' + wi.RS_Field ...

TSQL join to another table with Group By

The pseudo code of what I currently have is
Cost + CostTax = CostActual
However, I need it to be:
Cost + tax - totalSumDiscounts = CostActual
I have a SQL Select statement at joins 3 tables that calculates cost + tax = CostActual.
SELECT dbo.XMP_EventUsers.ID, dbo.XMP_EventUsers.EventID, dbo.XMP_EventUsers.UserID,
CONVERT(VARCHAR(20),dbo.XMP_EventUsers.DateCreated, 100)
AS DateCreated, CONVERT(VARCHAR, dbo.XMP_Event.Cost, 1) AS Cost, dbo.Users.FirstName, dbo.Users.LastName,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax - dbo.XMP_EventUsers.Paid AS Outstanding,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax AS CostActual
FROM dbo.XMP_Event INNER JOIN
dbo.XMP_EventUsers ON dbo.XMP_Event.ID = dbo.XMP_EventUsers.EventID INNER JOIN
dbo.Users ON dbo.XMP_EventUsers.UserID = dbo.Users.UserID
Another table records discounts to be applied to the total cost. This query totals up the discounts to be applied.
SELECT UserID, SUM([Amount]) AS Amount
FROM [dbo].[XMP_EventPromoUsers]
GROUP BY UserID
How do I join the 2nd results to the first so that the total number of discount is minuses from the final cost in the select statement for each record?
Thanks for your help!
-R
Example results below for answer 1
Query 1 returns:
ID|EventID|UserID|DateCreated|Cost|FirstName|LastName|Outstanding|CostActual|FinalValue|
51|14-----|41----|Aug 11 2011|0.00|John-----|Smith---|-120-------|0.00------|-10-------|
Query 2
UserID-|Amount----|
41-----|10--------|
96-----|30--------|
SELECT
dbo.XMP_EventUsers.ID, dbo.XMP_EventUsers.EventID, dbo.XMP_EventUsers.UserID,
CONVERT(VARCHAR(20),dbo.XMP_EventUsers.DateCreated, 100) AS DateCreated,
CONVERT(VARCHAR, dbo.XMP_Event.Cost, 1) AS Cost,
dbo.Users.FirstName, dbo.Users.LastName,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax - dbo.XMP_EventUsers.Paid AS Outstanding,
dbo.XMP_Event.Cost + dbo.XMP_Event.CostTax AS CostActual,
dbo.XMP_Event.cost + dbo.XMP_Event.CostTax - Users2.Amount AS FinalValue
FROM
dbo.XMP_Event
INNER JOIN dbo.XMP_EventUsers
ON dbo.XMP_Event.ID = dbo.XMP_EventUsers.EventID
INNER JOIN dbo.Users
ON dbo.XMP_EventUsers.UserID = dbo.Users.UserID
INNER JOIN (SELECT UserID, SUM([Amount]) AS Amount
FROM [dbo].[XMP_EventPromoUsers]
GROUP BY UserID) Users2
ON dbo.Users.UserID = Users2.UserID

How to access a OnetoMany join table in JPQL?

I want to write a lttl complicated query in JPQL where i access a OneToMany Join table. I get QuerySyntaxException: Pan_PanRes is not mapped.
QUERY -
query = "SELECT p FROM Pan p WHERE p.id IN " +
"(SELECT p_id FROM Pan_PanRes p_prs WHERE prs_id IN " +
"(SELECT r.id FROM PRS r where r.pant = :pant))"+
" ORDER BY pr.clD"
i tried implementing this concept in MYSQL. It works fine. So i know i am not calling the join table in right way. How should it be called then?
I would like to add MYSQL statement which works fine -
mysql> select * from pan where id not in
(select pan_id from pan_panres where panres_id in
(select id from panres where pant_id = 3));
Thanks...
Solved it myself -
query = "SELECT p FROM Pan p WHERE p.id IN " +
"(SELECT p.id FROM p.panRes prs WHERE id IN " +
"(SELECT r.id FROM PanRes r where r.pant = :pant))"+
" ORDER BY pr.clD"
Where panRes is the oneToMany variable name i have used in Pan Class.

SQL Join query, getting ManagerName

I have an tblEmployeeProfile & a tblPersonnel. tblPersonnel is an HR table, that consists of all employees in the company; tblEmployeeProfile contains details about an employee's position.
tblPersonnel.PersonnelID
tblPersonnel.FirstName
tblPersonnel.MiddleName
tblPersonnel.LastName
tblPersonnel.PhoneNumber
tblPersonnel.Email
tblEmployeeProfile.EmployeeID
tblEmployeeProfile.ManagerID
tblEmployeeProfile.DepartmentID
tblEmployeeProfile.JobCategoryID
tblEmployeeProfile.SalaryID
I want to return a record with the following fields:
EmployeeID, FirstName, MiddleName, LastName, Email, ManagerFullName
where EmployeeID = #EmployeeID
*tblEmployeeProfile.ManagerID = tblPersonnel.PersonnelID*
I can't seem to get the query correct for getting the ManagerFullName
Not sure if it's the same for Tsql, but you're going to need two join statements. 1st join is the employee profile table to your personnel table. Second is to join the personnel table to to the profile table to grab the manager name. Might look something like this
FROM personnel p
JOIN employeeprofile prof
ON prof.employeeID = p.personnelID
LEFT OUTER JOIN personnel man
ON man.personnelID = prof.managerID
The only reason I did a left outer join on the manager stuff is in the odd event a user might not have a manager assigned.
You may want to try the following:
SELECT
e1.EmployeeID,
e1.FirstName,
e1.MiddleName,
e1.LastName,
e1.Email,
e2.FirstName + ' ' + e2.LastName AS ManagerFullName
FROM
tblPersonnel e1
INNER JOIN
tblEmployeeProfile ep ON (ep.EmployeeID = e1.PersonnelID)
INNER JOIN
tblPersonnel e2 ON (e2.PersonnelID = ep.ManagerID)
WHERE
e1.EmployeeID = #EmployeeID
SELECT
employee.PersonnelID, employee.FirstName, employee.MiddleName, employee.LastName, employee.Email, manager.FirstName + ' ' + manager.Surname
FROM
tblPersonnel AS employee
INNER JOIN tblEmployeeProfile ON employee.PersonnelID = tblEmployeeProfile.EmployeeID
INNER JOIN tblPersonnel AS manager ON tblEmployeeProfile.ManagerID = manager.PersonnelID
WHERE
employee.PersonnelID = #EmployeeID
Try this:
SELECT
p1.PersonnelID,
p1.FirstName,
p1.MiddleName,
p1.LastName,
p1.Email,
p2.FirstName + ' ' + p2.MiddleName + ' ' + p2.LastName as ManagerFullName
FROM
tblEmployeeProfile e,
tblPersonnel p1,
tblPersonnel p2
WHERE
e.EmployeeId = p1.PersonnelId AND
e.ManagerId = p2.PersonnelId AND
e.EmployeeId = #EmployeeId
select p.EmployeeID
, E.FirstName
, E.MiddleName
, E.LastName
, E.Email
, M.FirstName
+ ' '
+ M.MiddleName
+ ' '
+ M.LastNameas as ManagerFullName
from tblPersonnel p
join tblEmployeeProfile as E on p.PersonnelID=E.EmplyeeID
join tblEmployeeProfile as M on M.PersonnelID=E.ManagerID
where E.EmplyeeID=#EmployeeID
assuming of course:
tblPersonnel.PersonnelID = tblEmployeeProfile.EmployeeID
every person has a manager (this means the CEO will be missing when you as for him/her)
Are you trying to do something like this?
Select
EmployeeID
,empTable.FirstName
,empTable.MiddleName
,empTable.LastName
,empTable.Email
,mgrTable.FirstName + ' '
+ mgrTable.MiddleName + ' '
+ mgrTable.LastName
as ManagerFullName
from
tblEmployeeProfile
inner join
tblPersonnel as empTable
on tblEmployeeProfile.EmployeeID = empTable.PersonnelID
inner join
tblPersonnel as mgrTable
on tblEmployeeProfile.ManagerID = mgrTable.PersonnelID
where EmployeeID = #EmployeeID