Help me do this SQL update query correctly - sql-server

I have 3 values that I need to copy from one table to another table. Here is my amateur attempt at it, I know it is horribly ineffecent, what would the correct way of doing this query?
update [IDAT_PATIENTS]
set TargetRabiesSerial =
(select top 1 SERIAL_NUMBER
from [IDAT_RABIESHISTORY] as rab
where TargetPetAccountNum = rab.PATIENT_ACCOUNT_ID
and TargetClientAccountNum = rab.CLIENT_ACCOUNT_ID
order by rab.DATE_TIME_PERFORMED desc)
, TargetRabiesBrandName =
(select top 1 BRAND_NAME
from [IDAT_RABIESHISTORY] as rab
where TargetPetAccountNum = rab.PATIENT_ACCOUNT_ID
and TargetClientAccountNum = rab.CLIENT_ACCOUNT_ID
order by rab.DATE_TIME_PERFORMED desc)
, TargetRabiesTag =
(select top 1 TAG_NUMBER
from [IDAT_RABIESHISTORY] as rab
where TargetPetAccountNum = rab.PATIENT_ACCOUNT_ID
and TargetClientAccountNum = rab.CLIENT_ACCOUNT_ID
order by rab.DATE_TIME_PERFORMED desc)
where TargetClientAccountNum in
(select CLIENT_ACCOUNT_ID
from [IDAT_RABIESHISTORY]
where TargetPetAccountNum = PATIENT_ACCOUNT_ID)

Try This:
Update p Set
TargetRabiesSerial = h.SERIAL_NUMBER,
TargetRabiesBrandName = h.BRAND_NAME,
TargetRabiesTag = h.TAG_NUMBER
From IDAT_PATIENTS p
Join IDAT_RABIESHISTORY h
On h.PATIENT_ACCOUNT_ID = p.TargetPetAccountNum
And h.CLIENT_ACCOUNT_ID = p.TargetClientAccountNum
And h.DATE_TIME_PERFORMED =
(Select Max(DATE_TIME_PERFORMED)
From IDAT_RABIESHISTORY
Where h.CLIENT_ACCOUNT_ID = p.TargetClientAccountNum
And h.CLIENT_ACCOUNT_ID = p.TargetClientAccountNum)
Where TargetClientAccountNum In
(Select CLIENT_ACCOUNT_ID
From IDAT_RABIESHISTORY
Where TargetPetAccountNum = PATIENT_ACCOUNT_ID)

Something more or less like this, didn't have a schema to validate against so double check the syntax :)
update [IDAT_PATIENTS]
set TargetRabiesSerial = tblLatestHistory.SERIAL_NUMBER,
TargetRabiesBrandName = IDAT_RABIESHISTORY,
TargetRabiesTag = IDAT_RABIESHISTORY
from [IDAT_PATIENTS]
inner join (
select PATIENT_ACCOUNT_ID, CLIENT_ACCOUNT_ID, SERIAL_NUMBER, BRAND_NAME, TAG_NUMBER, max(DATE_TIME_PERFORMED)
from IDAT_RABIESHISTORY
group by PATIENT_ACCOUNT_ID, CLIENT_ACCOUNT_ID, SERIAL_NUMBER, BRAND_NAME, TAG_NUMBER
) tblLatestHistory
on TargetPetAccountNum = tblLatestHistory.PATIENT_ACCOUNT_ID
and TargetClientAccountNum = tblLatestHistory.CLIENT_ACCOUNT_ID

Related

Select top 1 subquery with parameters (SQL)

I am removing a user function which finds shows item prices based on configurations but the function is too slow.
Therefore I'm trying to write a query to do the same. This query finds the latest price that matches the required criteria
This is kind of what I'm going for but I cannot figure out how to handle this requirement correctly:
(Intellisesnse says s.inventdimid does not exist in the h subquery)
SELECT s.salesid
,s.itemid
,h.price
FROM salesline s
LEFT OUTER JOIN (
SELECT TOP 1 p.price
,p.itemid
,p.dataareaid
,l.inventdimid
FROM inventitemprice p
JOIN inventdim d ON d.dataareaid = p.dataareaid
AND d.inventdimid = p.inventdimid
JOIN inventdim l ON l.dataareaid = p.dataareaid
AND (
l.configid = d.configid
OR d.configid = ''
)
AND (
l.inventcolorid = d.inventcolorid
OR d.inventcolorid = ''
)
AND (
l.inventsizeid = d.inventsizeid
OR d.inventsizeid = ''
)
AND (
l.inventstyleid = d.inventstyleid
OR d.inventstyleid = ''
)
AND (p.ACTIVATIONDATE < getdate())
AND l.inventsiteid = d.inventsiteid
WHERE pricetype = 0
AND l.inventdimid = s.inventdimid /* <========= */
AND p.dataareaid = 'lkc'
ORDER BY activationdate DESC
,d.configid DESC
,d.inventcolorid DESC
,d.INVENTSIZEID DESC
,d.inventstyleid DESC
) AS h ON h.itemid = s.itemid
AND h.DATAAREAID = s.DATAAREAID
AND h.INVENTDIMID = s.inventdimid
WHERE s.dataareaid = 'lkc'
AND s.SALESSTATUS = 1
What would be the appropriate method for querying this?

Count in CTE query with variables

I have a query and want to COUNT all the related ids from other table.
I am using CTE and I also assigning variables.
When I print I get all the ids but how can I COUNT the same ids? I mean if I have an id "254aswer" 3 times it should show 3
This is the query:
;WITH cte AS (
select q.fecha, '31' as cdocu, q.Cotizacion__c, cli.codcli,
q."name", q.RUC__c, c.Nombre_contacto__c as atte, a.Direcci_n__c,
q.Referencia__c, q.Requisicion__c, con.mone, q.T_Cambio__c, q.TotalPrice,
(q.TotalPrice*q.IGV__c)/100 as toti,(q.TotalPrice+
(q.TotalPrice*q.IGV__c)/100) as totn, '0' as flag, ven.codven, cd.codcdv,
'00' as codscc,q.fecha as fven ,q.Validez_por__c,'0' as selchk,'0' as
estado,q.Descripcion__c,'0' as word,'0' as frontera,'0' as
idalias,q.T_Cambio__c as tcme,'0'as idcliente,'0' as idcontacto,'0' as
persnt,'0'as flag_rp,'0' as origen,ti.IDdespacho,'0' as nrosal,'0' as
iddirfis,tr.codtra,q.fecha as fecreg,ROW_NUMBER() OVER(ORDER BY
q.Cotizacion__c) AS 'Row1', q.Id
from quote AS q
LEFT JOIN tbl01cor cor ON q.Cotizacion__c = cor.nroini
LEFT JOIN mst01cli cli ON q.RUC__c = cli.ruccli
LEFT JOIN Contact c ON q.RUC__c = c.RUC_contacto__c
LEFT JOIN Account a ON q.RUC__c = a.RUC__c
LEFT JOIN tbl01cdv cd ON q.Condicion__c = cd.nomcdv
LEFT JOIN tbl_tipo_despacho ti ON q.T_Entrega__c = ti.despacho
LEFT JOIN tbl01tra tr ON q.Transportista__c = tr.nomtra
LEFT JOIN consulta con ON q.CurrencyIsoCode = con.CurrencyIsoCode
LEFT JOIN tbl01ven ven ON q.Vendedor__c = ven.nomven
select #fecha = cte.fecha, #cdocu = cte.cdocu, #ndocu = cte.Cotizacion__c, #codcli = cte.codcli, #nomcli = cte."name", #ruccli = cte.RUC__c, #atte = cte.atte,
#dirent = cte.Direcci_n__c, #nrefe = cte.Referencia__c, #requ = cte.Requisicion__c, #mone = cte.mone, #tcam = cte.T_Cambio__c, #tota = cte.TotalPrice, #toti = cte.toti,
#totn = cte.totn, #flag = cte.flag, #codven = cte.codven, #codcdv = cte.codcdv,#codscc = cte.codscc,#fven = cte.fven, #dura =cte.Validez_por__c, #selchk = cte.selchk,
#estado = cte.estado, #obsere = cte.Descripcion__c, #word= cte.word, #frontera = cte.frontera,#idalias = cte.idalias,#tcme = cte.tcme, #idcliente = cte.idcliente,
#idcontacto = cte.idcontacto, #persnt = cte.persnt, #flag_rp= cte.flag_rp, #origen = cte.origen,#tipent = cte.IDdespacho, #nrosal = cte.nrosal,
#iddirfis = cte.iddirfis, #CodTra = cte.codtra, #fecreg = cte.fecreg, #ID = cte.Id
FROM cte
--WHERE cte.fecha >= dateadd(day,datediff(day,0,GETDATE()),0)
WHERE Row1 = #COUNTER +1
SET #ITEM = (Select COUNT(*) from QuoteLineItem where Id = #ID)
PRINT #ITEM
I tried to create a new select like this:
SET #ITEM = (Select COUNT(*) from QuoteLineItem where Id = #ID)
But it only count all the items and I need to show the count for each of the ids. How can I get that?
I fixed it with this:
select count(QuoteId) from QuoteLineItem Where QuoteId = q.Id Group by QuoteId

Getting TFS work items on SSMS

I need some help mimicking a TFS query.
I have tried writing the following SQL query to do so but I am not able to get a matching population:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id
, LastUpdatedDateTime = MAX(LastUpdatedDateTime)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
SELECT distinct ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Current'
WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-14,CONVERT(Date,getdate(),1)) AND Microsoft_VSTS_Common_ClosedDate < dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Last'
ELSE 'Previous' END
, TSRNumber = Custom_TSRNumber
FROM
(Select * from (select *, rn = row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc)
from dbo.DimWorkItem w1) d where rn = 1) w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.LastUpdatedDateTime = l.LastUpdatedDateTime
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
WHERE System_WorkItemType = 'Task'
AND da.AreaPath like '\LOS\Reporting%'
AND w.Microsoft_VSTS_Common_Priority < 4
Also if anyone knows where I could find the department field as I am not sure whether it is a custom field or not.
SQL Server 2014: 12.0
TFS: 12.0
Visual studio professional 2015: 14.0
Thank you in advance for your suggestions!
I found a solution although still not able to find the the Department field :
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id, LastChangedDate = MAX(System_ChangedDate)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
DECLARE #FromDateWeek DATE
DECLARE #FromDateTwoWeek DATE
SET #FromDateWeek = dateadd(d,-7,CONVERT(Date,getdate(),1))
SET #FromDateTwoWeek = dateadd(d,-14,CONVERT(Date,getdate(),1))
--SELECT #FromDate
SELECT ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN w.Microsoft_VSTS_Common_ClosedDate >= #FromDateWeek OR w.System_State = 'Active' THEN 'Current'
WHEN (w.Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek AND w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek)
OR w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek THEN 'Last'
ELSE 'Previous' END
FROM [dimWorkItem] w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.System_ChangedDate = l.LastChangedDate
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
WHERE
da.AreaPath LIKE '\LOS\Reporting%'
AND System_WorkItemType = 'Task'
AND (Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek
OR w.System_State = 'Active')
AND ISNULL(Microsoft_VSTS_Common_Priority,0) < 4
AND w.System_Reason <> 'Obsolete'

How to update a table with a recursive CTE?

I hope you can help me
I have a problem over here, been trying to solve this but cannot figure out how. I have a simple table which represents reps and their leaders over cycles (time measures) like this:
RepID|LeaderID|CycleID
I need to calculate for each leader the whole tree below them only with certain status twice, because the formula is:
(All reps below the leader with status 1 or 2) - (All reps below the leader on the previous cycle with status 7)
My code is as follows:
update ccp
set ccp.Total_reps =
(
select isnull(COUNT(*),0)
from dbo.MCP_Reps_by_cycle ccp_total_reps
join dbo.MCP_Compensation_Plan cp_total_reps on cp_total_reps.ID_Compensation_Plan = ccp_total_reps.ID_Compensation_Plan and cp_total_reps.CycleID = #previous_cycle and cp_total_reps.Definitive = 1 and cp_total_reps.Active = 1
join dbo.F_Get_reps(ccp.RepID, #previous_cycle) r on r.RepID = ccp_total_reps.RepID
where ccp_total_reps.StatusDetailID in(1,2) and ccp_total_reps.Active = 1
)
-
(
select isnull(COUNT(*),0)
from dbo.MCP_Reps_by_cycle ccp_total_reps
join dbo.MCP_Compensation_Plan cp_total_reps on cp_total_reps.ID_Compensation_Plan = ccp_total_reps.ID_Compensation_Plan and cp_total_reps.CycleID = #previous_cycle_two and cp_total_reps.Definitive = 1 and cp_total_reps.Active = 1
join dbo.F_Get_reps(ccp.RepID, #previous_cycle_two) r on r.RepID = ccp_total_reps.RepID
where ccp_total_reps.StatusDetailID = 7 and ccp_total_reps.Active = 1
)
from dbo.MCP_Reps_by_cycle ccp
join dbo.MCP_Compensation_Plan cp on cp.ID_Compensation_Plan = ccp.ID_Compensation_Plan and cp.ID_Compensation_Plan = #ID_Compensation_Plan and cp.Active = 1
where ccp.Active = 1
What the F_Get_reps function does, is a simple recursive CTE:
RETURNS #MIT table (RepID int)
as
begin
with rep_network as (
select ccp.RepID
from dbo.MCP_Reps_by_cycle ccp
join dbo.MCP_Compensation_Plan cp on cp.ID_Compensation_Plan = ccp.ID_Compensation_Plan and cp.CycleID = #cycleid and cp.Definitive = 1 and cp.Active = 1
where ccp.Active = 1 and ccp.LeaderID = #repid
union all
select ccp_2.RepID
from dbo.MCP_Reps_by_cycle ccp_2
join dbo.MCP_Compensation_Plan cp_2 on cp_2.ID_Compensation_Plan = ccp_2.ID_Compensation_Plan and cp_2.CycleID = #cycleid and cp_2.Definitive = 1 and cp_2.Active = 1
join rep_network r on r.RepID = ccp_2.LeaderID
where ccp_2.Active = 1
)
insert into #MIT
select RepID
from rep_network
return
end
I know the call to the function is the problem, but I cannot figure out how to remove it.
Please help me
Thanks in advance

how to convert the below subquery into joins using one update statement

Below is a complete query I have and the ultimate aim is to update the claim table. But it should be only one statement without any subquery, only joins are allowed because I am going to run this in an appliance which won't support subquery:
DECLARE #DecWdrwn as TABLE(CtryId smallint, CmId int, DecWdrwnDt int);
WITH s AS
(
SELECT
Ctryid,CmId,Dt,
ISNULL((
SELECT max(CmHistDtTmId)
FROM ClaimHistory l
WHERE St = 3
AND l.Ctryid = c.Ctryid
AND l.CmId = c.CmId)
, 0) MaxDec,
ISNULL((
SELECT max(CmHistDtTmId)
FROM ClaimHistory l
WHERE St = 7
AND l.Ctryid = c.Ctryid
AND l.CmId = c.CmId)
, 0) MaxSet
FROM
ClaimHistory c
WHERE
St =3
)
INSERT INTO #DecWdrwn
SELECT CtryId, CmId, Max(Dt) DecDt
FROM s
WHERE MaxSet > MaxDec
GROUP BY CtryId,CmId
Your response is much appreciated...
UPDATE Claims
SET CmDclnWdwnDt = (
SELECT DecWdrwnDt
FROM #DecWdrwn d
WHERE d.CmId = Claims.CmId
AND d.CtryId = Claims.CtryId
)
WHERE EXISTS (
SELECT *
FROM #DecWdrwn d
WHERE d.CmId = Claims.CmId
AND d.CtryId = Claims.CtryId
)
Please try INNER JOIN Update:
UPDATE a
SET a.CmDclnWdwnDt = b.DecWdrwnDt
FROM Claims a, #DecWdrwn b
WHERE a.CmId = b.CmId AND
a.CtryId =b.CtryId

Resources