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?
Related
my query taking more than 5 minutes to execute can anyone tell me what's wrong in this query, below is the query I try to optimize it but no luck
SELECT DISTINCT
'Freight' AS Expr1000,
'Acknowledged Trip Details' AS detailtype,
sCompanyDesc,
VehicleRegistration.sVehicleRegistrationNumber,
Token.iTokenId,
sTokenNumber,
Token.dtTokenGenerating AS TokenDate,
LoadAssign.sCustomerInvoiceNumber,
dtCustomerInvoiceDate,
FillingPoint.sFillingPointName AS [From],
DecantingPoint.sDecantingPointName AS [To],
CloseLoad.fExpectedFreightAmount AS fExpectedFreightAmount,
ISNULL(PayAdvance.fAdvanceAmount, 0) AS fAdvanceAmount,
CloseLoad.fCommissionAmount AS fCommissionAmount,
CloseLoad.fDecantedQuantity,
0 AS [Shortage Quantity],
0 AS [Shortage Rate],
0 AS [Shortage Amount],
sProductName,
ISNULL((SELECT SUM(ISNULL(JVDetails.fCreditAmount, 0))
FROM Transactions
INNER JOIN JV ON JV.sJVCode = Transactions.sTransactionCode
INNER JOIN JVDetails ON JVDetails.iJVId = JV.iJVId
WHERE CloseLoad.iTokenId = Transactions.iTokenId
AND JV.sDescription = 'Munshiana'),
0) AS Munshiana,
ISNULL(JV.sJVCode, '') + ISNULL(PV.sPVCode, '') AS advdocnum
FROM CloseLoad
INNER JOIN Token ON CloseLoad.iTokenId = Token.iTokenId
INNER JOIN LoadAssign ON CloseLoad.iLoadId = LoadAssign.iLoadId
INNER JOIN FillingPoint ON Token.iFillingPointId = FillingPoint.iFillingPointId
INNER JOIN DecantingPoint ON LoadAssign.iDecantingPointId = DecantingPoint.iDecantingPointId
INNER JOIN Product ON LoadAssign.iProductId = Product.iProductId
INNER JOIN VehicleRegistration ON Token.iVehicleRegistrationId = VehicleRegistration.iVehicleRegistrationId
INNER JOIN Company ON Token.iCompanyId = Company.iCompanyId
LEFT JOIN PayAdvance ON PayAdvance.iTokenId = Token.iTokenId
AND PayAdvance.bIsApproved = 1
LEFT JOIN PV ON PV.iPayAdvanceId = PayAdvance.iPayAdvanceId
AND PayAdvance.bIsApproved = 1
AND PV.bIsApproved = 1
LEFT JOIN JV ON JV.iPayAdvanceId = PayAdvance.iPayAdvanceId
AND PayAdvance.bIsApproved = 1
AND JV.bIsApproved = 1
WHERE CloseLoad.iLoadId NOT IN (SELECT tfrli.iLoadId
FROM TempFreightReceiptLoadInfo tfrli
INNER JOIN FreightReceiptChqInfo ci ON ci.iFreightReceiptChqInfoId = tfrli.iFreightReceiptChqInfoId
INNER JOIN LoadAssign l1 ON l1.iLoadId = tfrli.iLoadId
WHERE ci.bIsApproved = 1
AND l1.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
AND tfrli.sAllocationType = 'Freight')
AND LoadAssign.bIsLoadClose = 1
AND Token.iVehicleRegistrationId = 2644
AND LoadAssign.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
AND Token.iCompanyId IN (1, 2, 3)
AND Token.sDecantingPointType IN ('Domestic', 'Export')
AND LoadAssign.bIsActive = 1
AND Token.bIsLoadVerify = 1;
Execute EXPLAIN to find bottleneck.
EXPLAIN SELECT DISTINCT ...
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
I'm running a query that contains the same subquery two times, one used in a inner join condition and the another in a outer join. I'm highlighting the repeated subquery with **. How can I optimize this in order to run only once?
SELECT DISTINCT dbo.tb_contato.Nome, dbo.tb_contato.id_contato, dbo.tb_contato.Sexo, dbo.tb_contato.codigo, dbo.tb_email.email
FROM dbo.tb_contato INNER JOIN
dbo.tb_email ON dbo.tb_contato.id_contato = dbo.tb_email.id_contato INNER JOIN
dbo.tb_empresa ON dbo.tb_empresa.id_empresa = dbo.tb_contato.id_empresa LEFT OUTER JOIN
(SELECT dbo.tb_interacao.IDContato AS id_contato
FROM dbo.tb_interacao INNER JOIN
**(SELECT MAX(IDInteracao) AS IDIntMax, IDPerfilParticipante AS id_perfil_participante, IDProjeto, IDContato
FROM dbo.tb_interacao AS tb_interacao_2
GROUP BY IDPerfilParticipante, IDProjeto, IDContato)** AS IntMax1 ON dbo.tb_interacao.IDInteracao = IntMax1.IDIntMax INNER JOIN
dbo.tb_projeto ON dbo.tb_interacao.IDProjeto = dbo.tb_projeto.id_projeto INNER JOIN
dbo.tb_status_processo ON dbo.tb_interacao.IDStatusProcesso = dbo.tb_status_processo.id_status_processo
WHERE (dbo.tb_projeto.id_projeto = 2057) AND (dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 7) OR
(dbo.tb_projeto.id_projeto = 2057) AND (dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 6) OR
(dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 6) AND (dbo.tb_projeto.id_grupo = 55) OR
(dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 7) AND (dbo.tb_projeto.id_grupo = 55))
AS ConvidadosOut ON dbo.tb_contato.id_contato = ConvidadosOut.id_contato INNER JOIN
(SELECT tb_interacao_1.IDContato AS id_contato
FROM dbo.tb_interacao AS tb_interacao_1 INNER JOIN
**(SELECT MAX(IDInteracao) AS IDIntMax, IDPerfilParticipante AS id_perfil_participante, IDProjeto, IDContato
FROM dbo.tb_interacao AS tb_interacao_3
GROUP BY IDPerfilParticipante, IDProjeto, IDContato)** AS IntMax2 ON tb_interacao_1.IDInteracao = IntMax2.IDIntMax INNER JOIN
dbo.tb_projeto AS tb_projeto_1 ON tb_interacao_1.IDProjeto = tb_projeto_1.id_projeto INNER JOIN
dbo.tb_status_processo AS tb_status_processo_1 ON tb_interacao_1.IDStatusProcesso = tb_status_processo_1.id_status_processo
WHERE (tb_projeto_1.id_projeto = 181) AND (IntMax2.id_perfil_participante = 1) AND (tb_status_processo_1.id_status_processo = 4) OR
(tb_projeto_1.id_projeto = 1581) AND (IntMax2.id_perfil_participante = 1) AND (tb_status_processo_1.id_status_processo = 5) OR
(IntMax2.id_perfil_participante = 1) AND (tb_status_processo_1.id_status_processo = 6) AND (tb_projeto_1.id_grupo = 62)) AS ConvidadosIn ON
dbo.tb_contato.id_contato = ConvidadosIn.id_contato
WHERE (dbo.tb_email.email_visibility = 0 OR
dbo.tb_email.email_visibility IS NULL) AND (dbo.tb_empresa.id_pais = 1) AND (dbo.tb_contato.Fonte <> 'salesloft_orange' AND
dbo.tb_contato.Fonte <> 'salesloft_int_orange' OR
dbo.tb_contato.Fonte IS NULL) AND (dbo.tb_contato.id_contato_visibility = 1 OR
dbo.tb_contato.id_contato_visibility IS NULL) AND (ConvidadosOut.id_contato IS NULL)
I hope you are using SQL server 2005 or later. You can safely try using Common table expressions for the purpose as stated in your question.
Below is an example of script from adventureworks database:
USE AdventureWorks2008R2;
GO
-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;
GO
I have the following select
Select Exam.Name,
Test.Type,
Test.TestId,
Topic.Name,
Exam.Name
FROM Test
INNER JOIN Exam
ON ( Test.ExamId = Exam.ExamId)
INNER JOIN Topic
ON ( Test.TopicId = Topic.TopicId)
WHERE Test.TestStatusId = 1
When Test.Type = 1 then there will be an Exam.Name for the test
When Test.Type = 2 then there will be a Topic.Name for the test
Is there a way I can do an outer join and just return Name based on if Type = 1 or 2 ?
Use a left join and a case
Select Test.Type,
Test.TestId,
case when Test.Type = 1 then Exam.Name
when Test.Type = 2 then Topic.Name
end as Name
FROM Test
LEFT JOIN Exam ON Test.ExamId = Exam.ExamId
LEFT JOIN Topic ON Test.TopicId = Topic.TopicId
WHERE Test.TestStatusId = 1
I have a sql that is as under:
SELECT ib.branch_no,
ib.on_hand,
p.weightedav,
p.item_code,
FROM physical p
INNER JOIN
item_branch as ib on p.item_code = ib.item_code
WHERE ib.on_hand <> 0
This SQL returns only those branch_no that have on_hand <> 0.
I am trying to get all the branch_nos irrespective of the on_hand field, but while still using the where on_hand clause.
Taking the on_hand clause away solves my problem, but gives me large amount of un-needed rows with 0's.
I am using SQL SERVER 2008 R2.
Thanks in advance for any guidance. Please apologize if I am missing any information.
------------------------------------------ENTIRE SQL QUERY (Updated)---------------------------------------------
select
ib.branch_no,
p.weighted_av,
p.item_code,
p.x_value,
p.y_value,
ib.on_hand,
p.on_hand as PhysicalOH,
ip.price,
i.item_code as StyleCode,
i.description,
i.cat1,
i.cat2,
i.cat3,
i.cat4,
np.is_style_yn,
si.supplier_code ,
ysv.sort as YSort
from physical as p
left outer JOIN
item_branch as ib on p.item_code = ib.item_code -- and ib.on_hand <> 0
INNER JOIN
item_price as ip on p.item_code = ip.item_code and ip.price_type = 'P1'
INNER JOIN
style_values as sv on p.style_code = sv.style_code and p.x_value = sv.value
INNER JOIN
style_values as ysv on p.style_code = ysv.style_code and p.y_value = ysv.value and ysv.axis = 'Y'
INNER JOIN
ITEM as i on p.style_code = i.item_code
INNER JOIN
NON_PHYSICAL as np ON i.item_code = np.item_code and np.is_style_yn = 1
INNER JOIN
supplier_item as si ON i.item_code = si.item_code and si.pref_supp_no = 1
where --ib.on_hand <> 0 and
sv.axis = 'X' and
i.item_code in
(SELECT ITEM.item_code
FROM ITEM
INNER JOIN
NON_PHYSICAL ON ITEM.item_code = NON_PHYSICAL.item_code
LEFT JOIN
supplier_item ON Item.item_code = supplier_item.item_code and pref_supp_no = 1
WHERE NON_PHYSICAL.is_style_yn = 1 and ITEM.cat1 = 'Verge Sportswear Ltd' )
order by
si.supplier_code,
i.cat4,
i.cat3,
i.cat2,
i.cat1,
sv.sort
Try this:
SELECT ib.branch_no,
ib.on_hand,
p.weightedav,
p.item_code,
FROM physical p
INNER JOIN
item_branch as ib on (p.item_code = ib.item_code AND ib.on_hand <> 0)