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.
Related
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]
Adding "not in" statement to my SQL command makes the whole thing extremely slow. Any suggestion on how to get around this would be greatly appreciated!
select distinct
d.fiscal_year,d.calendar_year,d.month_num
from vw_ePCR_eMeds_tickets v
inner join incident_date_dim d on v.ticketdos=d.inci_date
left join vw_all_incidents i on i.CADIncidentNumber=v.incident_num
where TicketDOS between '12/01/2017' and '05/31/2018'
and [transportedstatus] = 'transported'
and i.call_type_id not in (
select call_type_id
from DW_EMS_Elite.dbo.MCFRS_EMS_BillingExclude
)
Just give it a try
with cte as (
select call_type_id from DW_EMS_Elite.dbo.MCFRS_EMS_BillingExclude
)
select distinct
d.fiscal_year,
d.calendar_year,
d.month_num
from
vw_ePCR_eMeds_tickets as v
join incident_date_dim as d on ( v.ticketdos=d.inci_date )
left join vw_all_incidents as i on ( i.CADIncidentNumber=v.incident_num )
left join cte as c on ( c.call_type_id = i.call_type_id )
where
( ( '20171201'<= TicketDOS ) and ( TicketDOS < '20180601' ) )
and ( [transportedstatus] = 'transported' )
and ( c.call_type_id is null )
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!!
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
I created a query in MS SQL Management Studio for SQL Server 2012 that uses common_table_expression to self join a table. It works correctly in MS SQL Studio but in Codeigniter no result or error is returned.
The query:
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY u.[PatientID], u.[CreateDate]) AS rn
FROM (
SELECT a.[PatientID], a.[BGValue], a.[CreateDate], a.[HospitalUnit], 'MSHA' as 'Hospital', h.[system_name], f.[facility_code], f.[facility_name], 'IV' as 'Treatment'
FROM [Analytics].[dbo].[MSHA_IVTreatment] a
JOIN [Analytics].[dbo].[MSHA_Patients] p
ON p.[PatientID] = a.[PatientID]
JOIN [Analytics].[dbo].[Facilities] f
ON f.[facility_code] = p.[facility_code]
JOIN [Analytics].[dbo].[Hospitals] h
ON f.[hospital] = h.[hospital]
WHERE a.[CreateDate] BETWEEN '2013-05-01' AND '2013-05-31'
UNION ALL
SELECT a.[PatientID], a.[BGValue], a.[CreateDate], a.[HospitalUnit], 'MSHA' as 'Hospital', h.[system_name], f.[facility_code], f.[facility_name], 'SubQ' as 'Treatment'
FROM [Analytics].[dbo].[MSHA_SubQTreatment] a
JOIN [Analytics].[dbo].[MSHA_Patients] p
ON p.[PatientID] = a.[PatientID]
JOIN [Analytics].[dbo].[Facilities] f
ON f.[facility_code] = p.[facility_code]
JOIN [Analytics].[dbo].[Hospitals] h
ON f.[hospital] = h.[hospital]
WHERE a.[CreateDate] BETWEEN '2013-05-01' AND '2013-05-31'
) u
)
SELECT mc.[PatientID], mc.[BGValue], mc.[CreateDate], mc.[Hospital], mc.[system_name] as 'System', mc.[facility_code], mc.[facility_name], mc.[HospitalUnit], DATEDIFF(second, mp.[CreateDate], mc.[CreateDate])/60 as 'Interval', mc.[Treatment]
FROM rows mc
JOIN rows mp
ON mc.rn = mp.rn + 1 and mc.[PatientID] = mp.[PatientID]
ORDER BY mc.[CreateDate] ASC;
When I put that into a variable and attempt to retrieve the result in codeigniter nothing is returned:
$result = $this->db->query($query);
CI_DB_sqlsrv_result Object
(
[conn_id] => Resource id #30
[result_id] => Resource id #41
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[num_rows] => -1
[row_data] =>
)
I have tried putting the query in a transaction but got the same result.
Any insight greatly appreciated.
Possible this be helpful for you -
;WITH [rows] AS
(
SELECT
a.[PatientID]
, a.[BGValue]
, a.[createdate]
, a.[HospitalUnit]
, Hospital = 'MSHA'
, h.[system_name]
, f.[facility_code]
, f.[facility_name]
, u.Treatment
, rn = ROW_NUMBER() OVER (ORDER BY u.[PatientID], u.[createdate])
FROM (
SELECT
PatientID
, BGValue
, createdate
, HospitalUnit
, Treatment = 'IV'
FROM dbo.MSHA_IVTreatment
WHERE createdate BETWEEN '20130501' AND '20130531'
UNION ALL
SELECT
PatientID
, BGValue
, createdate
, HospitalUnit
, Treatment = 'SubQ'
FROM dbo.MSHA_SubQTreatment
WHERE createdate BETWEEN '20130501' AND '20130531'
) a
JOIN [dbo].[MSHA_Patients] p ON p.[PatientID] = a.[PatientID]
JOIN [dbo].[Facilities] f ON f.[facility_code] = p.[facility_code]
JOIN [dbo].[Hospitals] h ON f.[Hospital] = h.[Hospital]
)
SELECT
mc.[PatientID]
, mc.[BGValue]
, mc.[createdate]
, mc.[Hospital]
, [System] = mc.[system_name]
, mc.[facility_code]
, mc.[facility_name]
, mc.[HospitalUnit]
, [Interval] = DATEDIFF(SECOND, mp.[createdate], mc.[createdate]) / 60
, mc.[Treatment]
FROM [rows] mc
JOIN [rows] mp ON mc.rn = mp.rn + 1 AND mc.[PatientID] = mp.[PatientID]
ORDER BY mc.[createdate];