Count in CTE query with variables - sql-server

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

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?

T-SQL to MS Access SQL

I have a working query in SQL Server, but I fail to convert it to MS Access SQL.
This is the bare working query in SQL Server:
select tblKPIData.id
,tblKPIData.KPI_id
,tblKPI.KPI_Name
,tblKPIData.ImportTimestamp
,tblKPIData.Quantity
,tblKPIData.FinancialMonth
,tblKPIData.FinancialYear
,tblKPIData.Zone_id
,tblZone.ZoneName
,tblKPIData.DMA_id
,tblDMA.DMA_Name
,tblKPIData.TargetOrResult
from tblKPIData
inner join tblKPI
on tblKPI.Id = KPI_id
left outer join tblDMA
on tblDMA.Id = tblKPIData.DMA_id
left outer join tblZone
on tblZone.ID = tblKPIData.Zone_id
inner join tblDashboardKPI
on tblDashboardKPI.KPI_Id = tblKPIData.KPI_id
inner join
( select a.kpi_id
,a.financialMonth
,a.financialYear
,isnull(a.zone_id,0) as zone_id
,isnull(a.dma_id,0) as dma_id
,a.targetorresult
,max(a.importtimestamp) as importtimestamp
from tblKPIData a
group by kpi_id
,financialMonth
,financialYear
,zone_id
,dma_id
,targetorresult) as max_kpi
on (tblKPIData.KPI_id = max_kpi.KPI_id
and tblKPIData.ImportTimestamp = max_kpi.importtimestamp
and tblKPIData.FinancialMonth = max_kpi.FinancialMonth
and tblKPIData.FinancialYear = max_kpi.FinancialYear
and isnull(tblKPIData.Zone_id,0) = isnull(max_kpi.zone_id,0)
and isnull(tblKPIData.DMA_id,0) = isnull(max_kpi.dma_id,0)
and tblKPIData.TargetOrResult = max_kpi.TargetOrResult)
where tblKPIData.FinancialMonth = 'Oct'
and tblKPIData.FinancialYear = 2017
and tblKPIData.KPI_id in (select kpi_id from tblDashboardKPI where tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
and (tblKPIData.Zone_id = 5 or tblKPIData.DMA_id in (select id from tblDMA where Zoneid = 5))
AND ((tblDashboardKPI.Status) = 1)
and ((tblDashboardKPI.Dashboard_Id) = 6)
I know I have to add brackets, but not exactly sure where. This is what I came up with, but I get an error (Join Expression not supported) and it highlites a piece of code on the first join (tblKPI.Id = KPI_id):
select tblKPIData.id
,tblKPIData.KPI_id
,tblKPI.KPI_Name
,tblKPIData.ImportTimestamp
,tblKPIData.Quantity
,tblKPIData.FinancialMonth
,tblKPIData.FinancialYear
,tblKPIData.Zone_id
,tblZone.ZoneName
,tblKPIData.DMA_id
,tblDMA.DMA_Name
,tblKPIData.TargetOrResult
from (((((tblKPIData
inner join tblKPI
on tblKPI.Id = KPI_id)
left outer join tblDMA
on tblDMA.Id = tblKPIData.DMA_id)
left outer join tblZone
on tblZone.ID = tblKPIData.Zone_id)
inner join tblDashboardKPI
on tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
inner join
( select a.kpi_id
,a.financialMonth
,a.financialYear
,isnull(a.zone_id,0) as zone_id
,isnull(a.dma_id,0) as dma_id
,a.targetorresult
,max(a.importtimestamp) as importtimestamp
from tblKPIData a
group by kpi_id
,financialMonth
,financialYear
,zone_id
,dma_id
,targetorresult) as max_kpi
on (tblKPIData.KPI_id = max_kpi.KPI_id)
and tblKPIData.ImportTimestamp = max_kpi.importtimestamp
and tblKPIData.FinancialMonth = max_kpi.FinancialMonth
and tblKPIData.FinancialYear = max_kpi.FinancialYear
and isnull(tblKPIData.Zone_id,0) = isnull(max_kpi.zone_id,0)
and isnull(tblKPIData.DMA_id,0) = isnull(max_kpi.dma_id,0)
and tblKPIData.TargetOrResult = max_kpi.TargetOrResult)
where tblKPIData.FinancialMonth = 'Oct'
and tblKPIData.FinancialYear = 2017
and tblKPIData.KPI_id in (select kpi_id from tblDashboardKPI where tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
and (tblKPIData.Zone_id = 5 or tblKPIData.DMA_id in (select id from tblDMA where Zoneid = 5))
AND ((tblDashboardKPI.Status) = 1)
and ((tblDashboardKPI.Dashboard_Id) = 6)
What am I doing wrong?

When Trying to update the above Query in MS SQL SERVER ,it is saying ZERO rows affected

Update a
set approvedby = 'Matt Schmitt', changenumber = 'CHG48038', effectiveenddatetime = 'DEC 31 2199 11:59PM'
from esg_staging..enoc_auditexceptions a
join esg_staging..enoc_auditresult b
on a.[WorkdayValue] = b.workdayvalue
and a.[Applicationvalue] = b.applicationvalue
and a.name = b.name
and a.workdayid = b.workdayid
and a.email = b.email
and a.application = '29905'
Try These if you are updating from another table
Update esg_staging.enoc_auditexceptions
set approvedby = b.approvedby
, changenumber = b.changenumber enter code here
, effectiveenddatetime = b.effectiveenddatetime
from esg_staging.enoc_auditexceptions a
join esg_staging.enoc_auditresult b on a.[WorkdayValue] = b.workdayvalueand a.[Applicationvalue] = b.applicationvalue
and a.name = b.name and a.workdayid = b.workdayid and a.email = b.email and a.application = '29905'

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

Help me do this SQL update query correctly

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

Resources