SQL Server 2008: Only one result, joining 3 tables - sql-server

I have the following databases:
IMAGE UPDATED
SELECT
l.FECHA, nc.IdNumeroControlTrabajador AS ENLACE,
t.RFC, t.Homonimia AS HOM,
t.ApellidoPaterno, t.ApellidoMaterno,
t.Nombre, l.IMPORTE,
cp.NombreOrgano AS DEPENDENCIA, l.OBSERVACIONES,
l.FECHA_INICIAL, l.FECHA_FINAL,
MAX (cn.FechaIngresoGobierno)
FROM
CapturaFAIFAP.dbo.Laudos AS l
LEFT JOIN FAIFAPparalelo.dbo.NumeroControlTrabajadores AS nc ON l.ID = nc.idTrabajador
LEFT JOIN FAIFAPparalelo.dbo.ClaveNominalTrabajadores AS cn ON l.ID = cn.idTrabajador
LEFT JOIN FAIFAPparalelo.dbo.Trabajadores AS t ON l.ID = t.idTrabajador
LEFT JOIN FAIFAPparalelo.dbo.ClaveProgramatica AS cp ON cn.idClaveProgramatica = cp.idClaveProgramatica
LEFT JOIN (
SELECT
cp.NombreOrgano,
MAX (cnt.FechaIngresoGobierno) AS fecha
FROM
FAIFAPparalelo.dbo.ClaveNominalTrabajadores as cnt
GROUP BY
cp.NombreOrgano
) AS j ON (
cp.NombreOrgano = j.NombreOrgano
AND j.fecha = cn.FechaIngresoGobierno
)
GROUP BY
l.FECHA, nc.IdNumeroControlTrabajador, t.RFC,
t.Homonimia, t.ApellidoPaterno, t.ApellidoMaterno,
t.Nombre,l.IMPORTE,cp.NombreOrgano,l.OBSERVACIONES,
l.FECHA_INICIAL,l.FECHA_FINAL,cn.FechaIngresoGobierno
I need to unify the query. The huge query i put in code, and a similar query in the image. If i join the tables ClaveNominal and ClaveProgramatica i have duplicities, because sometimes the persons have 2 ClavesProgramaticas, due to the system I use, not delete or update the current registry, just puts in inactive and adds a new one active, and i can't make the condition to activo because, that represents if the person still works here.

Related

sql server - How to Get all distinct value in group by column from two table and count from another table for each value

I have 3 tables in that 2 tables are master table and 3rd is transaction table. i need to get count from transaction table for each value in other two table without loosing rows in mater table
i need result like below
Table layout for understanding
This is the code i have tried,
select s.status_name, e.machine_group_name, qty = COALESCE(COUNT(e.id),0)
from tbl_status s
left outer JOIN tbl_transaction as e ON e.status_name = s.status_name
group by e.machine_group_name, s.status_name
This is solution i have figured:
select m.machine_group_name, s.status_name, qty = COUNT(e.id) from
tbl_machine_group as m
cross join tbl_status as s
left outer join tbl_transaction as e on e.status_name = s.status_name
and e.machine_group_name = m.machine_group_name
group by m.machine_group_name, s.status_name
order by machine_group_name
select
MC_Group_Name
,Status_Name
,count(1) as [Count of Transaction]
from
tbl_Transaction tbl_3
left join tbl_Machine_Group tbl_1
on tbl_3.MC_Group_Name = tbl_1.MC_Group_Name
left join tbl_Status tbl_2
on tbl_3.Status_Name = tbl_2.Status_Name
group by
MC_Group_Name
,Status_Name

SSIS merge join lacks row (and also How to simulate SSIS join with tsql query)

In my project I have a merge join transformation, that uses inner join. It is supposed to join the files lookup with the rest of the data flow. However, the join seems to not include some rows, with files, even though it should? I'm trying to simulate the join in tsql, but I seem to be doing it wrong as it shows me the missing rows.
Here are the outputs I'm trying to join
Input A:
SELECT *
FROM
tblExpense expense
OUTER APPLY(
SELECT TOP 1 *
FROM tblExpenseDtl Details
WHERE expense.intExpenseID = Details.intExpenseID
ORDER BY Details.sintLineNo
) details
WHERE
expense.dtUpdateDateTime > '2017-06-01'
ORDER BY expense.intExpenseID desc
Input B:
SELECT f.*
FROM dbo.tblExpense e
JOIN tblExpenseDtl d ON d.intExpenseID = e.intExpenseID
JOIN tblExpReceiptFile f ON f.intExpenseDtlID = d.intExpenseDtlID
WHERE
e.dtUpdateDateTime > '2017-06-01'
ORDER BY e.intExpenseID desc
And the sql query that I thought would produce the same result as my SSIS inner join
SELECT *
FROM
tblExpense expense
OUTER APPLY(
SELECT TOP 1 *
FROM tblExpenseDtl Details
WHERE expense.intExpenseID = Details.intExpenseID
ORDER BY Details.sintLineNo
) details
inner join ( SELECT f.*
FROM dbo.tblExpense e
JOIN tblExpenseDtl d ON d.intExpenseID = e.intExpenseID
JOIN tblExpReceiptFile f ON f.intExpenseDtlID = d.intExpenseDtlID
WHERE
e.dtUpdateDateTime > '2017-06-01'
ORDER BY e.intExpenseID desc
) innerJ
WHERE
expense.dtUpdateDateTime > '2017-06-01'
ORDER BY expense.intExpenseID desc
The join key in the SSIS is the expense.intExpenseID = e.intExpenseID.
Input A gives 1 row, with an expenseID=X, and input B gives 2 rows with an expenseID=X
How are you sorting data before merging it? According to this SSIS is sorting in different way than SQL Server (in most cases). Maybe there is a problem.
Edit: What type is intExpenseID?

SQL server -Multiple address joins in from clause

Ok, so I might be trying to do this all wrong, but here it goes.
In my data I have customer seq which is where the order was shipped to. But, since some orders are dropped shipped they have a different customer number and seq kept in a different table.
So basically, I want to say
if custaddr.country <> "" then custaddr.country, else DR.country
the from clause I currently have looks like this
CO is order table
Coitem is line of order
co_ship is shipped line
custaddr is customer address
if the order is drop ship, the customer and seq is pulled from coitem instead of co.
from
co inner join coitem on co.co_num = coitem.co_num
inner join co_ship on (co_ship.co_num = coitem.co_num and co_ship.co_line = coitem.co_line and co_ship.co_release = coitem.co_release)
inner join custaddr on (co.cust_num = custaddr.cust_num and co.cust_seq = custaddr.cust_seq)
inner join custaddr DR on (coitem.cust_num = custaddr.cust_num and coitem.cust_seq = custaddr.cust_seq)
when I run this, with the last inner join active I get no results.

MS SQL Table Joins - Multiple Tables

I am new to MS SQL and am having trouble joining 4 tables within a query.
I am trying to join Orders, Order Lines, Client, and Picked tables to create a query to show quantity ordered and picked for a client. If I comment out the last inner join for Picked, I get the correct results. When I include the inner join for Picked the query returns results but data that should be in the Picked fields is NULL. One order line can have 1 or more Picked lines.
SELECT W_Warehouse, OH.OrderID, OH.RequiredDate, C.Client, OL.LineNbr, OL.QtyOrd, P.QtyPick
FROM Order
INNER JOIN Warehouse on Order.OH_WHS = Warehouse.W_PK
INNER JOIN Client on Order.O_Client = Client.C_PK
INNER JOIN OrderLine on Order.O_PK = OrderLine.OL_PK
INNER JOIN Picked on OrderLine.O_PK = Picked.P_PK
WHERE C.CLIENT = 'WENDYS'
Without knowing the data in the tables it is difficult to answer precisely.
But as you say you have 1+ rows in the Picked table, you probably want to do aggregation with GROUP BY and SUM()
Maybe this is what you're looking for:
SELECT
W.W_Warehouse,
OH.OrderID,
OH.RequiredDate,
C.Client,
OL.LineNbr,
OL.QtyOrd,
P.QtyPick
FROM
Order OH
INNER JOIN Warehouse W on OH.OH_WHS = W.W_PK
INNER JOIN Client C on OH.O_Client = C.C_PK
INNER JOIN OrderLine OL on OH.O_PK = OL.OL_PK
CROSS APPLY (
select sum(QtyPick) as QtyPick
from Picked P
where OL.O_PK = P.P_PK
) P
WHERE
C.CLIENT = 'WENDYS'
It calculates the sum of QtyPick separately so it doesn't increase the number of lines in the result.

How to write sql for this logic?

I have the following tables (this is abbreviated)
tableAssignments
id
timestamp // updated when row is modified
tableSystems
tableUsers
...
tableAssignmentsSnapshot
id
timestamp // set when row created, snapshots never change
tableSystemsSnapshot
tableUsersSnapshot
tableAssignments_id // reference to "tableAssignments" row this was created from
syncKey // Changed when snapshots are created, max value is latest
Sometime after the tableAssignments are changed, snapshots of all the assignments are taken and the snapshots are created with the same syncKey. I am trying to write a query to check if the latest "tableAssignmentsSnapshot" are up to date or if new ones should be taken. The logic required is:
Determine the latest tableAssignmentSnapshots for each system, which is determine by maximum syncKey (see query below).
Join the result from #1 with tableAssignments.
If timestamp from tableAssignments > timestamp from tableAssignmentsSnapshot then new snapshot is required.
The following query accomplishes step #1 and runs fast. It returns the tableAssignmentSnapshots with the greatest value of "syncKey" for each system.
select * from
tableAssignmentsSnapshot d inner join tableSystemsSnapshot e
on d.systemId = e.id
where d.syncKey = (select MAX(syncKey) from tableAssignmentsSnapshot y inner join tableSystemsSnapshot z
on y.systemId = z.id
where tableSystems_id = e.tableSystems_id)
I'm struggling with what to do next. I need to be able to do something like the following but am having trouble with the syntax required:
select * from tableAssignments a right outer join
(
the result from above query
)
on a.id = ?.tableAssignments_id
You could wrap your first query on a CTE:
;WITH CTE AS
(
SELECT * -- Here you should list only the columns that you are gonna need
FROM tableAssignmentsSnapshot D
INNER JOIN tableSystemsSnapshot E
ON D.systemId = E.id
WHERE D.syncKey = ( select MAX(syncKey) from tableAssignmentsSnapshot y inner join tableSystemsSnapshot z
on y.systemId = z.id
where tableSystems_id = e.tableSystems_id)
)
SELECT *
FROM tableAssignments A
RIGHT JOIN CTE B
ON A.id = B.tableAssignments_id

Resources