SQL Server Case Statement bad performance - sql-server

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

Related

Cant able to create view with following snowflake query

Needs to create view with below columns. Need to understand how to create view using with clause inside the query.
create
or replace view TEST_RRX.DW_RRX.V_SIL_RRX_PTS_BusinessLocation_Dim(
--ROW_WID,
--ADDRESS_TYPE,
BUSN_LOC_NAME,
BUSN_LOC_NUM,
BUSN_LOC_TYPE,
ST_ADDRESS1,
ST_ADDRESS2,
CITY_NAME,
POSTAL_CODE,
STATE_CODE,
COUNTRY_CODE,
ACTIVE_FLG,
CREATED_BY_WID,
CHANGED_BY_WID,
CREATED_ON_DT,
CHANGED_ON_DT,
AUX1_CHANGED_ON_DT,
AUX2_CHANGED_ON_DT,
AUX3_CHANGED_ON_DT,
AUX4_CHANGED_ON_DT,
SRC_EFF_FROM_DT,
SRC_EFF_TO_DT,
EFFECTIVE_FROM_DT,
EFFECTIVE_TO_DT,
DELETE_FLG,
CURRENT_FLG,
W_INSERT_DT,
W_UPDATE_DT,
DATASOURCE_NUM_ID,
--ETL_PROC_WID,
INTEGRATION_ID,
--TENANT_ID,
--X_CUSTOM,
--GEO_COUNTRY_WID,
--GEO_WID,
UPD_FLG
) as WITH CODE AS (
SELECT
W_CODE_D.MASTER_CODE AS MASTER_CODE,
W_CODE_D.MASTER_VALUE AS MASTER_VALUE,
W_CODE_D.SOURCE_CODE AS SOURCE_CODE,
W_CODE_D.DATASOURCE_NUM_ID AS DATASOURCE_NUM_ID,
W_CODE_D.SOURCE_CODE_1 as SOURCE_CODE_1,
W_CODE_D.SOURCE_CODE_2 as SOURCE_CODE_2,
W_CODE_D.SOURCE_NAME_1 as SOURCE_NAME_1,
W_CODE_D.CATEGORY
FROM
W_CODE_D
WHERE
W_CODE_D.LANGUAGE_CODE = 'E'
),
USER_TAB as (
SELECT
LOOKUP_TABLE.ROW_WID as ROW_WID,
LOOKUP_TABLE.DATASOURCE_NUM_ID as DATASOURCE_NUM_ID,
LOOKUP_TABLE.INTEGRATION_ID as INTEGRATION_ID,
LOOKUP_TABLE.EFFECTIVE_FROM_DT as EFFECTIVE_FROM_DT,
LOOKUP_TABLE.EFFECTIVE_TO_DT as EFFECTIVE_TO_DT
FROM
DW_RRX.W_USER_D LOOKUP_TABLE
),
BUSN_LOCATION as (
SELECT
sq.BUSN_LOC_NAME,
sq.BUSN_LOC_NUM,
sq.BUSN_LOC_TYPE,
sq.ST_ADDRESS1,
sq.ST_ADDRESS2,
case when CITY.MASTER_VALUE is null then (
case when sq.CITY_NAME is null
OR LENGTH(sq.CITY_NAME) = 0
OR REGEXP_INSTR(sq.CITY_NAME, ' ')> 0 then 'Unspecified' else sq.CITY_NAME end
) else CITY.MASTER_VALUE end as city_name,
sq.POSTAL_CODE,
case when STATE.MASTER_CODE is null then (
case when sq.STATE_CODE is null
OR LENGTH(sq.STATE_CODE) = 0
OR REGEXP_INSTR(sq.STATE_CODE, ' ')> 0 then 'Unspecified' else sq.STATE_CODE end
) else STATE.MASTER_CODE end as STATE_CODE,
case when COUNTRY.MASTER_CODE is null then (
case when sq.COUNTRY_CODE is null
OR LENGTH(sq.COUNTRY_CODE) = 0
OR REGEXP_INSTR(sq.COUNTRY_CODE, ' ')> 0 then 'Unspecified' else sq.COUNTRY_CODE end
) else COUNTRY.MASTER_VALUE end as COUNTRY_CODE,
'Y' as ACTIVE_FLG,
CREATED_BY.ROW_WID AS CREATED_BY_WID,
CHANGED_BY.ROW_WID AS CREATED_BY_WID,
sq.AUX1_CHANGED_ON_DT,
sq.AUX2_CHANGED_ON_DT,
sq.AUX3_CHANGED_ON_DT,
sq.AUX4_CHANGED_ON_DT,
sq.SRC_EFF_FROM_DT,
sq.SRC_EFF_TO_DT,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as EFFECTIVE_FROM_DT,
TO_DATE('01013714', 'DDMMYYYY') as EFFECTIVE_TO_DT,
'N' As DELETE_FLG,
'Y' AS CURRENT_FLG,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as W_INSERT_DT,
W_BUSN_LOCATION_D.W_UPDATE_DT as current_date,
sq.DATASOURCE_NUM_ID,
--sq.ETL_PROC_WID,
sq.INTEGRATION_ID,
CASE WHEN (
SELECT
ETL_PROC_WID
FROM
TEST_RRX.DW_RRX.W_PARAM_G
WHERE
ROW_WID = 1
) = W_BUSN_LOCATION_D.ETL_PROC_WID THEN 'X' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NULL THEN 'I' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NOT NULL
AND (
sq.CHANGED_ON_DT <> W_BUSN_LOCATION_D.CHANGED_ON_DT
OR sq.AUX1_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX1_CHANGED_ON_DT
OR sq.AUX2_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX2_CHANGED_ON_DT
OR sq.AUX3_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX3_CHANGED_ON_DT
OR sq.AUX4_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX4_CHANGED_ON_DT
) THEN 'U' END as UPD_FLG
FROM
DW_RRX.W_BUSN_LOCATION_DS sq
LEFT OUTER JOIN CODE COUNTRY ON COUNTRY.SOURCE_CODE = sq.country_code
AND COUNTRY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND COUNTRY.CATEGORY = 'COUNTRY'
LEFT OUTER JOIN CODE CITY ON CITY.SOURCE_CODE_1 = sq.country_code
AND CITY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND CITY.SOURCE_CODE_2 = sq.STATE_CODE
AND CITY.SOURCE_NAME_1 = sq.CITY_NAME
AND CITY.CATEGORY = 'CITY'
LEFT OUTER JOIN CODE STATE ON STATE.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND STATE.CATEGORY = 'STATE'
LEFT OUTER JOIN USER_TAB CREATED_BY ON sq.DATASOURCE_NUM_ID = CREATED_BY.DATASOURCE_NUM_ID
AND CREATED_BY.INTEGRATION_ID = sq.CREATED_BY_ID
and CREATED_BY.EFFECTIVE_FROM_DT <= sq.CREATED_ON_DT
and CREATED_BY.EFFECTIVE_TO_DT >= sq.CREATED_ON_DT
LEFT OUTER JOIN USER_TAB CHANGED_BY ON sq.DATASOURCE_NUM_ID = CHANGED_BY.DATASOURCE_NUM_ID
AND CHANGED_BY.INTEGRATION_ID = sq.CHANGED_BY_ID
and CHANGED_BY.EFFECTIVE_FROM_DT <= sq.CHANGED_ON_DT
and CHANGED_BY.EFFECTIVE_TO_DT >= sq.CHANGED_ON_DT
LEFT OUTER JOIN W_BUSN_LOCATION_D ON sq.INTEGRATION_ID = W_BUSN_LOCATION_D.INTEGRATION_ID
AND sq.DATASOURCE_NUM_ID = W_BUSN_LOCATION_D.DATASOURCE_NUM_ID
)
SELECT
*
FROM
BUSN_LOCATION
WHERE
UPD_FLG <> 'X'
Getting SQL compilation error: Invalid column definition list
Needs to create view with above columns

Query optimization vtiger lead details

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!!

COUNT(DISTINCT()) Return false value

I try to count total employee in my subquery table. Suppose the count result will return 0, but it keeps returning 1.
If I try to return only employee_id and month together, I didn't get any return value for may which is correct, but each time I try to count(distinct), I will get 1 as my return value. This is my sql
SELECT
count (distinct(CASE WHEN (x.month =5 and x.employee_id <> 0) THEN
x.employee_id
ELSE 0 END)) as test_may
FROM(
(
SELECT
h.month,
h.employee_id,
eb.employee_no,
ee.company_code,
h.amount,
h.year,
h.trx_type,
h.trx_code,
v.trx_desc,
h.frequency,
h.run_sequence
FROM
v_employee h,
v_trans v,
employee_emp ee,
employee eb
WHERE
( h.year = 2014 ) AND
( h.employee_id = ee.employee_id ) AND
( ee.employee_id = eb.employee_id ) AND
( h.employee_no = eb.employee_no ) AND
( h.trx_code = v.trx_code ) AND
( h.trx_type = v.trx_type ) AND
( v.company_code = ee.company_code OR v.company_code is NULL) AND
( h.trx_type IN ('S','B','N','O','A','D','L') )
)
)x,
employee_emp ee,
employee eb
WHERE
( x.employee_id = ee.employee_id ) AND
( ee.employee_id = eb.employee_id ) AND
( x.employee_no = eb.employee_no ) AND
( x.year = 2014 )
The count as you have it now will also count the 0 that is in the ELSE clause of the CASE expression. Even with DISTINCT still one instance of that 0 will be counted.
Remove the ELSE 0 so that you have NULL -- which is not counted:
count (distinct(CASE WHEN x.month =5 and x.employee_id <> 0
THEN x.employee_id
END)) as test_may
Note that with NULLIF you can shorten this expression to:
count (distinct(CASE x.month WHEN 5 THEN NULLIF(x.employee_id, 0) END)) as test_may
Your count will return the same count even in both cases. Because you are giving the value for Count function in both the cases.
Change from
count (distinct(CASE WHEN (x.month =5 and x.employee_id <> 0) THEN
x.employee_id
ELSE 0 END))
To
count (distinct(CASE WHEN (x.month =5 and x.employee_id <> 0) THEN
x.employee_id
ELSE NULL END))
Count will just count the values whether it is 0 or 100 as 1 & skip null values while counting. So in the Else condition NULL will give you correct output.

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