Query optimization vtiger lead details - query-optimization

I am new to use vtiger crm. I am using vtiger 6.0 version. i am creating API.
Vtiger table: vtiger_leaddetails have almost 7 lacks records and i am running query below: It is taking almost 30 sec to give response. can anybody help me how can i optimize this query:
SELECT
COUNT(
CASE WHEN (
crm1.`createdtime` BETWEEN '2017-02-02'
AND '2017-03-18'
) THEN 1 END
) AS `'number_of_leads'`,
COUNT(
CASE WHEN (
vtiger_leaddetails.`current_status` = 'Consent Provided'
AND vtiger_leaddetails.`leadactivitystartdate` BETWEEN '2017-02-02'
AND '2017-03-18'
) THEN 1 END
) AS `'number_of_sales'`,
vtiger_leaddetails.`plan_name` AS `'plan_name'`,
plan.`plan_name_short` AS `'plan_name_short'`,
ROUND(
(
(
COUNT(
CASE WHEN (
vtiger_leaddetails.`current_status` = 'Consent Provided'
AND vtiger_leaddetails.`leadactivitystartdate` BETWEEN '2017-02-02'
AND '2017-03-18'
) THEN 1 END
)
) * 100
) / COUNT(vtiger_leaddetails.lead_no),
2
) AS `'ratio_of_conversion'`,
ROUND(
SUM(
CASE WHEN (
vtiger_leaddetails.`current_status` = 'Consent Provided'
AND vtiger_leaddetails.`leadactivitystartdate` BETWEEN '2017-02-02'
AND '2017-03-18'
) THEN vtiger_leaddetails.`plan_price` END
) / 100000,
2
) AS `'revenu_in_lakh'`
FROM
vtiger_leaddetails
INNER JOIN vtiger_crmentity AS `crm1` ON crm1.crmid = vtiger_leaddetails.leadid
INNER JOIN oa_plan_master AS `plan` ON vtiger_leaddetails.`plan_id` = plan.`oasys_plan_id`
INNER JOIN vtiger_users AS `user_tab` ON user_tab.id = crm1.smownerid
INNER JOIN vtiger_campaign ON vtiger_campaign.campaignid = vtiger_leaddetails.campaign_name
INNER JOIN vtiger_crmentity AS `crm2` ON crm2.`crmid` = vtiger_campaign.campaignid
WHERE
vtiger_leaddetails.leadid > 0
AND crm1.`deleted` = '0'
AND crm2.`deleted` = '0'
AND plan.`deleted` = '0'
AND vtiger_leaddetails.converted = 0
AND (
(
crm1.createdtime BETWEEN '2017-02-02'
AND '2017-03-18'
)
OR (
vtiger_leaddetails.`leadactivitystartdate` BETWEEN '2017-02-02'
AND '2017-03-18'
)
)
GROUP BY
vtiger_leaddetails.`plan_id`
Thanks in Advance!!

Related

Select with WITH

I am new in MySQL I have a db2 select and a would like to do this in MSsql and with WITH clause
db2
1 SQL.
SELECT
SQLUSER.TT_VALUTRAZ.SIFRA3,
SQLUSER.TT_VALUTRAZ.SIFVAL32,
SQLUSER.TT_VALUTRAZ.DATUM,
SQLUSER.TT_VALUTRAZ.RAZMERJE
FROM
SQLUSER.TT_VALUTRAZ
WHERE
(
(SQLUSER.TT_VALUTRAZ.DATUM >= '1.5.2007')
) ---> this go to DW.TEMP_PFPC_TT_VALUTRAZ
2 sql.
SELECT
'705' AS SIFRA3,
'891' AS SIFVAL32,
A.DATUM,
A.RAZMERJE AS RAZMERJE
FROM
DW.TEMP_PFPC_TT_VALUTRAZ A
WHERE
A.DATUM >= '1.5.2007' AND
A.SIFRA3 = '891' AND
A.SIFVAL32 = '978' AND
('705', '891', A.DATUM) NOT IN
(
SELECT
SIFRA3,
SIFVAL32,
DATUM
FROM
DW.TEMP_PFPC_TT_VALUTRAZ
WHERE
SIFRA3 = '705' AND
SIFVAL32 = '891'
)
now I like to join this two SQL statement and would like to use ons with clause and MSsql syntax
There are many ways of doing this. I only posted one way. There are some places that have been changed due to syntax issues. Let me know this answer if this answer is useful.
; WITH CTE_1 AS ( SELECT
SQLUSER.TT_VALUTRAZ.SIFRA3,
SQLUSER.TT_VALUTRAZ.SIFVAL32,
SQLUSER.TT_VALUTRAZ.DATUM,
SQLUSER.TT_VALUTRAZ.RAZMERJE
FROM
SQLUSER.TT_VALUTRAZ
WHERE
(
(SQLUSER.TT_VALUTRAZ.DATUM >= '1.5.2007')
) ---> this go to DW.TEMP_PFPC_TT_VALUTRAZ
)
, CTE_2 AS (
SELECT * FROM
(
SELECT
'705' AS SIFRA3,
'891' AS SIFVAL32,
A.DATUM,
A.RAZMERJE AS RAZMERJE
FROM
DW.TEMP_PFPC_TT_VALUTRAZ A
) AS B
WHERE
B.DATUM >= '1.5.2007' AND
B.SIFRA3 = 891 AND
B.SIFVAL32 = 978 AND
B.SIFRA3 NOT IN (705) --use of sub queries in where clause has been fixed.
AND B.SIFVAL32 NOT IN (891) --use of sub queries in where clause has been fixed.
AND B.DATUM NOT IN
(
SELECT
DATUM
FROM
DW.TEMP_PFPC_TT_VALUTRAZ
)
)
SELECT * FROM
CTE_1 AS [C]
INNER JOIN CTE_2 AS [CT]
ON [CTE_1]. [SIFRA3] = [CT].[SIFRA3]
AND [C]. [SIFVAL32] = [CT].[SIFVAL32]
AND [C].[DATUM] = [CT].[DATUM]
AND [C].[RAZMERJE] = [CT].[RAZMERJE]

SQL Server Case Statement bad performance

I have a Query with multiple CASE statements as below. It is taking taking lot of time to execute even after proper Indexing. The Sum operation on case statements causing bad performance. How can I re write the above Query to improve performance.
SELECT H.Item,
SUM(CASE A.CategeoryId
WHEN 123 THEN NULLIF(IIF(C.IsActive = 0
AND ( ( c.RowID IN ( 2, 4 )
AND H.SubId <> ISNULL(C.ItemId, 0) )
OR ( c.RowId NOT IN ( 2, 4 )
AND H.SubId = ISNULL(C.ItemId, 0) ) ), 0, A.Sales), 0)
ELSE 0
END) AS [TotalSales1],
SUM(CASE A.CategeoryId
WHEN 198 THEN NULLIF(IIF(C.IsActive = 0
AND ( ( c.RowID IN ( 2, 4 )
AND H.SubId <> ISNULL(C.ItemId, 0) )
OR ( c.RowId NOT IN ( 2, 4 )
AND H.SubId = ISNULL(C.ItemId, 0) ) ), 0, A.Sales), 0)
ELSE 0
END) AS [TotalSales2],
'',
'',
'',
'',
''
FROM SubItem AS H
INNER JOIN Item AS C WITH (NOLOCK)
ON H.Item = C.ItemId
LEFT OUTER JOIN #temp1 AS A
ON H.SubId = A.ItemId
WHERE H.Productid = 99
GROUP BY H.Item,
C.ItemId,
C.RowID

Each Group by expression must contain at least one column that is not an outer reference, need a work around

Hi this code runs perfectly as a query but when i try to parse it as a view i have the error on the title of this post. "Each Group by expression must contain at least one column that is not an outer reference". I need a second pair of eyes to help me work around this problem.
Thank you!
SELECT Codigo, Nome, DataNascimento, IDADE, DataAdmissao, FUNCAO, CodEstabelecimento, Vencimento
, 'GRATIFICACOES' AS Expr1, 'SUB.TURNO' AS Expr2, OUTROS, DataUltProcessamento, 'DESCONTO MULTAS' AS Expr3
, AntiguidadeMeses, 'FALTAS' AS Expr4, Ano
FROM (
SELECT F.Codigo, F.Nome, F.DataNascimento, (
SELECT FLOOR((CAST(GETDATE() AS INTEGER) - CAST(F.DataNascimento AS INTEGER)) / 365.25) AS Expr1
) AS IDADE, F.DataAdmissao, (
SELECT Descricao
FROM dbo.Categorias
WHERE (Categoria = F.Categoria)
) AS FUNCAO, F.Categoria, F.CodEstabelecimento, F.Vencimento, (
SELECT SUM(Valor) AS G
FROM dbo.FuncRem
WHERE (
Remuneracao IN (
'R21'
,'R23'
,'R24'
,'R25'
,'R94'
,'R96'
)
)
AND (Funcionario = F.Codigo)
) AS 'GRATIFICACOES', (
SELECT SUM(Valor) AS ST
FROM dbo.FuncRem AS FuncRem_2
WHERE (
Remuneracao IN (
'R05'
,'R22'
,'R43'
,'R50'
)
)
AND (Funcionario = F.Codigo)
) AS 'SUB.TURNO', (
SELECT SUM(Valor) AS O
FROM dbo.FuncRem AS FuncRem_1
WHERE (
Remuneracao NOT IN (
'R21'
,'R23'
,'R24'
,'R25'
,'R94'
,'R96'
,'R05'
,'R22'
,'R43'
,'R50'
)
)
AND (Funcionario = F.Codigo)
) AS OUTROS, (
SELECT SUM(Valor) AS A
FROM dbo.MovimentosFuncionarios
WHERE (CodMov = 'D15')
AND (Funcionario = F.Codigo)
) AS 'DESCONTO MULTAS', F.DataUltProcessamento, DATEDIFF(m, F.DataAdmissao, GETDATE())
AS AntiguidadeMeses, (
SELECT SUM(Tempo) AS F
FROM dbo.CadastroFaltas
WHERE (
Falta IN (
'F12'
,'F10'
)
)
AND (Funcionario = F.Codigo)
AND (YEAR(Data) = M.Ano)
) AS 'FALTAS', M.Ano
FROM dbo.Funcionarios AS F
INNER JOIN dbo.Situacoes AS S ON F.Situacao = S.Situacao
LEFT OUTER JOIN dbo.FuncRem AS FR ON FR.Funcionario = F.Codigo
LEFT OUTER JOIN dbo.MovimentosFuncionarios AS M ON F.Codigo = M.Funcionario
LEFT OUTER JOIN dbo.CadastroFaltas AS CF ON CF.Funcionario = F.Codigo
WHERE (S.Tipo = 0)
AND (
F.CodDepartamento IN (
912
,914
,916
,921
,922
,924
,931
,934
,937
)
)
AND (M.Ano = 2016)
GROUP BY F.Codigo, F.Nome, F.DataNascimento, F.DataAdmissao, F.Categoria, F.CodEstabelecimento
, F.Vencimento, F.DataUltProcessamento, F.Situacao, CF.Falta, M.Ano, CF.Tempo, FR.Remuneracao
, FR.Valor, M.CodMov, M.Valor
) AS R
GROUP BY Codigo, Nome, DataNascimento, IDADE, DataAdmissao, FUNCAO, CodEstabelecimento, Vencimento
, AntiguidadeMeses, DataUltProcessamento, 'GRATIFICACOES', 'FALTAS', 'SUB.TURNO', OUTROS, 'DESCONTO MULTAS', Ano

TSQL Subquery related

SELECT DT.TenantDescription
,DT.PropertyNumber
,DT.UnitNo
,DT.AdressLn1
,DT.AddressLn2
,DT.AddressSituation
,(
CASE
WHEN DT.TransactionCode = 1
THEN DT.New_TransactionValue
ELSE 0
END
) AS RentDue
,(
CASE
WHEN DT.TransactionCode = 2
THEN DT.New_TransactionValue
ELSE 0
END
) AS OTHERSUMSDUE
,(
CASE
WHEN DT.TransactionCode = 3
THEN DT.New_TransactionValue
ELSE 0
END
) AS ARREARSBFWD
,(
CASE
WHEN DT.TransactionCode = 4
THEN DT.New_TransactionValue
ELSE 0
END
) AS ARREARSCFWD
,(
CASE
WHEN DT.TransactionCode = 5
THEN DT.New_TransactionValue
ELSE 0
END
) AS IRRECOVERABLERENT
,(
CASE
WHEN DT.TransactionCode > 5
THEN DT.New_TransactionValue
ELSE 0
END
) AS Expenditure
FROM (
SELECT * * (
SELECT New_TenantNameOnly
FROM New_Rentmaster Rm
WHERE Rm.New_rentmasterId = PD.new_rentmasterid
) AS TenantDescription
,* * (
SELECT [New_UnitNumber]
FROM new_propertyunits NPU
WHERE NPU.[New_propertyunitsId] = PD.[new_unitnumberid]
) AS UnitNo
,(
SELECT New_AddressLine1
FROM New_address
WHERE New_addressId = (
SELECT New_addressid
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
)
) AS AdressLn1
,(
SELECT New_AddressLine2
FROM New_address
WHERE New_addressId = (
SELECT New_addressid
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
)
) AS AddressLn2
,(
SELECT TT.[New_TransactionTypeCode] AS TransactionCode
FROM New_transactiontype TT
WHERE [New_transactiontypeId] = PD.[new_transactioncodenameid]
) AS TransactionCode
,(
SELECT New_PropertyNumber
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
) AS PropertyNumber
,(
SELECT New_UnitAddressIdName
FROM New_propertyunits NPU
WHERE NPU.[New_propertyunitsId] = PD.[new_unitnumberid]
) AS AddressSituation
,PD.New_TransactionValue
FROM New_PropertyDetails PD
) AS DT
The above piece of code works fine
Now I want to make changes to the above column (the name is aliased to TenantDescription)
where I want to replace the above column with the following code
Select New_TenantNameOnly from New_Rentmaster Rm
New_TenantNumber IN
(Select MAX(New_TenantNumber) from new_rentmaster GROUP BY [New_Unit_No],[New_Propety_Number])
then it gives me an error
Subquery returns more than one value
This code is supposed to return more than one value
So what should I do about it >??
If you're wanting to bring back multiple results, you ought to be thinking about using joins rather than subqueries. An Inner Join looks something like this:
SELECT *
FROM HumanResources.Employee AS e
INNER JOIN Person.Person AS p
ON e.BusinessEntityID = p.BusinessEntityID
this will produce as many rows as can be produced by matching rows from each table based on the ON condition (e.g. if there are two rows in Employee with BusinessEntityID of 1, and three rows in Person with BusinessEntityID of 1, the above will produce six rows in the result set where BusinessEntityID is 1)

Convert From Access Query to SQL Server

I'm trying to convert a report query from Access to SQL SERVER 2008. Using the same database but i can't get the same results. not even close. The Access query is like this:
SELECT Sum(INPUT_ItemSaleLines.TaxExclusiveTotal) AS TotalexTax,([TotalexTax])- Sum( Nz([SumOfTaxExclusiveAmount])+ Nz([CostOfGoodsSoldAmount])+ Nz
(
Nz
( IIf
( Left([Input_Items.ItemNumber],5)='31-63',136*[Quantity]/1000,
IIf(Left([Input_Items.ItemNumber],6)='34S-63',200*[Quantity]/1000)
)
)+ Nz
( IIf
( Left([Input_Items.ItemNumber],5)='34-63',250*[Quantity]/1000,
IIf(Left([Input_Items.ItemNumber],6)='26-63',250*[Quantity]/1000)
)
)
)
) AS Margin,
INPUT_Cards_1.Name AS SalesPerson, INPUT_Sales.SalesPersonID,
INPUT_Sales.InvoiceStatusID, INPUT_Cards.Name, INPUT_Items.ItemName,
Sum(INPUT_ItemSaleLines.Quantity) AS TotalQty,
Sum(INPUT_ItemSaleLines.CostOfGoodsSoldAmount) AS TotalCOGS,
Count(INPUT_Sales.SaleID) AS [Number of Sales],
Sum(qryShippingTotalexGST.SumOfTaxExclusiveAmount) AS ShippingTotal
FROM
( qryShippingTotalexGST RIGHT JOIN
(
(
(
INPUT_Items INNER JOIN INPUT_ItemSaleLines
ON INPUT_Items.ItemID = INPUT_ItemSaleLines.ItemID
) INNER JOIN INPUT_Sales ON INPUT_ItemSaleLines.SaleID = INPUT_Sales.SaleID
) INNER JOIN INPUT_Cards ON INPUT_Sales.CardRecordID = INPUT_Cards.CardRecordID
) ON qryShippingTotalexGST.JobID = INPUT_ItemSaleLines.JobID
) LEFT JOIN INPUT_Cards AS INPUT_Cards_1 ON INPUT_Sales.SalesPersonID = INPUT_Cards_1.CardRecordID
WHERE
(((INPUT_Sales.Date) Between [Forms]![MenuReports]![StartDate] And [Forms]![MenuReports]![EndDate]))
GROUP BY INPUT_Items.ItemNumber,
INPUT_Cards_1.Name, INPUT_Sales.SalesPersonID, INPUT_Sales.InvoiceStatusID,
INPUT_Cards.Name, INPUT_Items.ItemName
HAVING
(((INPUT_Sales.InvoiceStatusID)<>"OR"));
Then the SQL Server script that i write like this:
SELECT MYOBItems.ItemName, MYOBCards.Name AS SalesPerson, MYOBCards1.Name,
SUM(MYOBsalesLines.Qty) AS TotalQty,
SUM(MYOBsalesLines.CostOfGoodsSoldAmount) AS TotalCOGS,
COUNT(MYOBSales.SaleID) AS NumberOfSales,
SUM(MYOBsalesLines.TaxExclusiveAmount) AS TotalexTax,
SUM(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2))) AS ShippingTotal,
(SUM(MYOBsalesLines.TaxExclusiveAmount)) - SUM
(
COALESCE(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2)),0)+ COALESCE(MYOBsalesLines.CostOfGoodsSoldAmount,0)+ COALESCE
(
COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '31-63' THEN (136*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '34S-63' THEN (200*MYOBsalesLines.Qty/1000)
ELSE 0
END, 0
)+ COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '34-63' THEN (250*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '26-63' THEN (250*MYOBsalesLines.Qty/1000)
ELSE 0
END , 0
), 0
)
)AS Margin
, MYOBSales.InvoiceStatusID FROM
( MYOBJobsShippingTotals RIGHT JOIN
(
(
(
MYOBItems INNER JOIN MYOBsalesLines
ON MYOBItems.ItemID = MYOBsalesLines.ItemID
) INNER JOIN MYOBSales ON MYOBsalesLines.SaleID = MYOBSales.SaleID
AND MYOBSales.ElevateCompanyID = MYOBsalesLines.ElevateCompanyID
) INNER JOIN MYOBCards AS MYOBCards1 ON MYOBSales.CardRecordID = MYOBCards1.CardRecordID
AND MYOBsalesLines.ElevateCompanyID = MYOBCards1.ElevateCompanyID
AND MYOBSales.ElevateCompanyID = MYOBCards1.ElevateCompanyID
) ON MYOBJobsShippingTotals.JobID = MYOBsalesLines.JobID
) LEFT JOIN MYOBCards ON MYOBSales.SalesPersonID = MYOBCards.CardRecordID
GROUP BY MYOBItems.ItemName, MYOBCards.Name,
MYOBCards1.Name, MYOBSales.InvoiceStatusID
I suspect there was something wrong with the joined tables but not sure how to fix it.
Is there any mistake in my SQL Server script that is not relevant with the Access syntax?
Thank for the help in advance. and sorry for my long scripts.
Your SQL server query is missing the WHERE and HAVING clauses of the MS Access query, it's GROUP BY clause doesn't have the same number or order of columns as the MS Access query, and has additional JOIN criteria that wasn't in the MS Access query.
A more faithful conversion would look like this:
SELECT SUM(MYOBsalesLines.TaxExclusiveAmount) AS TotalexTax
, SUM(MYOBsalesLines.TaxExclusiveAmount)
- SUM
(
COALESCE(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2)), 0)
+ COALESCE(MYOBsalesLines.CostOfGoodsSoldAmount,0)
+ COALESCE
(
COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '31-63' THEN (136*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '34S-63' THEN (200*MYOBsalesLines.Qty/1000)
ELSE 0
END
, 0
)
+ COALESCE
(
CASE
WHEN LEFT(MYOBItems.ItemNumber,5) = '34-63' THEN (250*MYOBsalesLines.Qty/1000)
WHEN LEFT(MYOBItems.ItemNumber,6) = '26-63' THEN (250*MYOBsalesLines.Qty/1000)
ELSE 0
END
, 0
)
, 0
)
)
AS Margin
, MYOBCards1.Name AS SalesPerson
, MYOBSales.SalesPersonID
, MYOBSales.InvoiceStatusID
, MYOBCards.Name
, MYOBItems.ItemName
, SUM(MYOBsalesLines.Qty) AS TotalQty
, SUM(MYOBsalesLines.CostOfGoodsSoldAmount) AS TotalCOGS
, COUNT(MYOBSales.SaleID) AS NumberOfSales
, SUM(cast(MYOBJobsShippingTotals.TaxExclusiveAmount AS Decimal(18,2))) AS ShippingTotal
FROM
(
MYOBJobsShippingTotals RIGHT JOIN
(
(
(
MYOBItems INNER JOIN MYOBsalesLines
ON MYOBItems.ItemID = MYOBsalesLines.ItemID
) INNER JOIN MYOBSales ON MYOBsalesLines.SaleID = MYOBSales.SaleID
) INNER JOIN MYOBCards ON MYOBSales.CardRecordID = MYOBCards.CardRecordID
) ON MYOBJobsShippingTotals.JobID = MYOBsalesLines.JobID
) LEFT JOIN MYOBCards AS MYOBCards1 ON MYOBSales.SalesPersonID = MYOBCards1.CardRecordID
WHERE MYOBSales.Date BETWEEN ? AND ?
GROUP BY MYOBItems.ItemNumber
, MYOBCards1.Name
, MYOBSales.SalesPersonID
, MYOBSales.InvoiceStatusID
, MYOBCards.Name
, MYOBItems.ItemName
HAVING MYOBSales.InvoiceStatusID <> 'OR'
Where the two question marks are your [Forms]![MenuReports]![StartDate] and [Forms]![MenuReports]![EndDate] values.

Resources