I have the following query .its execution took 15 min .It is too much slowly .
Is there a way to optimize it ?
Query
SELECT
Id,Fees,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Fees ' AS FeesName
,#MonthName AS [MonthName]
INTO ##TempFeesMonthly
from
(
SELECT DISTINCT
1 as Id,sum(((CNTI_THPAYE *(CNTI_THFACT / CNTI_THPAYE)) *
(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate)t
--CREATE INDEX IDX_TempFeesMonthly ON ##TempFeesMonthly(WeekOfMonth)
--Calcul Temp Margin
UNION ALL
--INSERT INTO ##TempFeesMonthly(Id,Fees,WeekOfMonth,StartDate,EndDate,FeesName,[MonthName])
SELECT
2, sum(Fees) AS Fees ,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Margin ' AS FeesName
,#MonthName AS [MonthName]
from
(
SELECT DISTINCT
sum((CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*#NumberOfDays)-(CNTI_THPAYE *(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*1.453*1.21*#NumberOfDays) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
LEFT JOIN
SCHHAYS.dbo.WTTIEINT INT
ON (
TAT.TIE_ID = INT.TIE_ID
)
AND (
TAT.VTAT_IORDRE = INT.TIEI_ORDRE
)
LEFT JOIN
SCHHAYS.dbo.PYCONTRAT CC
ON TAT.PER_ID = CC.PER_ID
AND TAT.CNT_ID = CC.CNT_ID
LEFT JOIN
SCHHAYS.dbo.CMTIERS T
ON TAT.TIE_ID = T.TIE_ID
LEFT JOIN
SCHHAYS.dbo.WTMISS M
ON CC.PER_ID = M.PER_ID
AND CC.CNT_ID = M.CNT_ID
LEFT JOIN
##WTCNTIWeek COT1
ON M.PER_ID = COT1.PER_ID
AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
SCHHAYS.dbo.WTPRH AS PRH
ON M.PER_ID = PRH.PER_ID
AND M.CNT_ID = PRH.CNT_ID
AND M.TIE_ID = PRH.TIE_ID
INNER JOIN
##tempStartEndWeekDates AS Tsed
ON PRH_DTEDEBSEM>=Tsed.StartDate
AND PRH_DTEFINSEM<=Tsed.EndDate
LEFT JOIN
SCHHAYS.dbo.WTSCCT C
ON CC.RGPCNT_ID = C.RGPCNT_ID
AND CC.PER_ID = C.PER_ID
AND CC.CNT_ID = C.CNT_ID
INNER JOIN
##TempHaysStaffWeek HF
ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate,CNTI_THPAYE,CNTI_DURHEBDO)t
GROUP BY WeekOfMonth,StartDate,EndDate
Related
my query isn't working at all and been working to see what's wrong but can't find it. says that have two values that are the same but honestly I am doing my best to proof-read my code:
SELECT
"HQCO"."HQCo",
"HQCO"."Name",
"JCJP"."Contract",
"JCJP"."Item",
"JCJP"."Phase",
"JCCP"."CostType",
"JCCI"."Item",
"JCCI"."Description",
"JCCP"."Phase",
"JCJP"."Description",
"JCCT"."Description",
"JCCH"."UM",
"JCCP"."CurrEstUnits",
"JCCP"."CurrEstCost",
"JCCP"."ActualUnits",
"JCCP"."ActualCost",
"JCCM"."Description",
"JCJP"."JCCo",
"JCCP"."ProjCost",
"JCCP"."RemainCmtdCost",
"JCCP"."ProjPlug",
"JCCP"."Mth",
"JCCI"."BilledAmt",
"JCCM"."BilledAmt",
"JCCM"."udGEACrev",
"JCCP"."Job",
"JCCM"."Department",
"JCJM"."ProjectMgr",
"JCMP"."Name"
FROM
(
(((((("Viewpoint"."dbo"."JCCP" "JCCP"
INNER JOIN
"Viewpoint"."dbo"."HQCO" "HQCO"
ON "JCCP"."JCCo" = "HQCO"."HQCo")
INNER JOIN
"Viewpoint"."dbo"."JCCT" "JCCT"
ON ("JCCP"."PhaseGroup" = "JCCT"."PhaseGroup")
AND
(
"JCCP"."CostType" = "JCCT"."CostType"
)
)
LEFT OUTER JOIN
"Viewpoint"."dbo"."JCCH" "JCCH"
ON (((("JCCP"."JCCo" = "JCCH"."JCCo")
AND
(
"JCCP"."Job" = "JCCH"."Job"
)
)
AND
(
"JCCP"."PhaseGroup" = "JCCH"."PhaseGroup"
)
)
AND
(
"JCCP"."Phase" = "JCCH"."Phase"
)
)
AND
(
"JCCP"."CostType" = "JCCH"."CostType"
)
)
LEFT OUTER JOIN
"Viewpoint"."dbo"."JCJP" "JCJP"
ON ((("JCCP"."JCCo" = "JCJP"."JCCo")
AND
(
"JCCP"."Job" = "JCJP"."Job"
)
)
AND
(
"JCCP"."PhaseGroup" = "JCJP"."PhaseGroup"
)
)
AND
(
"JCCP"."Phase" = "JCJP"."Phase"
)
)
LEFT OUTER JOIN
"Viewpoint"."dbo"."JCCI" "JCCI"
ON (("JCJP"."JCCo" = "JCCI"."JCCo")
AND
(
"JCJP"."Contract" = "JCCI"."Contract"
)
)
AND
(
"JCJP"."Item" = "JCCI"."Item"
)
)
INNER JOIN
"Viewpoint"."dbo"."JCCM" "JCCM"
ON ("JCCI"."JCCo" = "JCCM"."JCCo")
AND
(
"JCCI"."Contract" = "JCCM"."Contract"
)
)
INNER JOIN
"Viewpoint"."dbo"."JCJM" "JCJM"
ON ("JCCM"."JCCo" = "JCJM"."JCCo")
AND
(
"JCCM"."Contract" = "JCJM"."Job"
)
)
LEFT OUTER JOIN
"Viewpoint"."dbo"."JCMP" "JCMP"
ON ("JCJM"."JCCo" = "JCMP"."JCCo")
AND
(
"JCJM"."ProjectMgr" = "JCMP"."ProjectMgr"
)
WHERE
"JCCP"."Mth" < {ts '2017-04-02 00:00:00'}
AND "JCJP"."JCCo" = 1
AND "JCJM"."ProjectMgr" = 8
AND "JCCM"."Department" = '10'
ORDER BY
"JCJP"."Contract", "JCJP"."Item", "JCJP"."Phase", "JCCP"."CostType"
As you can see all tables and values are related and joined with inner and outer joins to complement the tables. It is for a report
Your query have multiple problems.
1) Problem with parenthese (too '(')
2) You use left outer join on table and you test a zone of this table -> null will be excluded like it
3) Multiples Zones in your select with same name
4) Quotes for zones and alias for tables are not necessary
Try this query remainded :
SELECT
HQCO.HQCo,
HQCO.Name,
JCJP.Contract,
JCJP.Item,
JCJP.Phase,
JCCP.CostType,
JCCI.Item,
JCCI.Description Desc1,
JCCP.Phase,
JCJP.Description Desc2,
JCCT.Description Desc3,
JCCH.UM,
JCCP.CurrEstUnits,
JCCP.CurrEstCost,
JCCP.ActualUnits,
JCCP.ActualCost,
JCCM.Description Desc4,
JCJP.JCCo,
JCCP.ProjCost,
JCCP.RemainCmtdCost,
JCCP.ProjPlug,
JCCP.Mth,
JCCI.BilledAmt BilledAmt1,
JCCM.BilledAmt BilledAmt2,
JCCM.udGEACrev,
JCCP.Job,
JCCM.Department,
JCJM.ProjectMgr,
JCMP.Name Name2
FROM
Viewpoint.dbo.JCCP
INNER JOIN Viewpoint.dbo.HQCO ON JCCP.JCCo = HQCO.HQCo
INNER JOIN Viewpoint.dbo.JCCT ON JCCP.PhaseGroup = JCCT.PhaseGroup AND JCCP.CostType = JCCT.CostType
LEFT OUTER JOIN Viewpoint.dbo.JCCH ON JCCP.JCCo = JCCH.JCCo AND JCCP.Job = JCCH.Job
AND JCCP.PhaseGroup = JCCH.PhaseGroup AND JCCP.Phase = JCCH.Phase AND JCCP.CostType = JCCH.CostType
LEFT OUTER JOIN Viewpoint.dbo.JCJP ON JCCP.JCCo = JCJP.JCCo AND JCCP.Job = JCJP.Job
AND JCCP.PhaseGroup = JCJP.PhaseGroup AND JCCP.Phase = JCJP.Phase AND JCJP.JCCo = 1
LEFT OUTER JOIN Viewpoint.dbo.JCCI ON JCJP.JCCo = JCCI.JCCo AND JCJP.Contract = JCCI.Contract AND JCJP.Item = JCCI.Item
INNER JOIN Viewpoint.dbo.JCCM ON JCCI.JCCo = JCCM.JCCo AND JCCI.Contract = JCCM.Contract
INNER JOIN Viewpoint.dbo.JCJM ON JCCM.JCCo = JCJM.JCCo AND JCCM.Contract = JCJM.Job
LEFT OUTER JOIN Viewpoint.dbo.JCMP ON JCJM.JCCo = JCMP.JCCo AND JCJM.ProjectMgr = JCMP.ProjectMgr
WHERE
JCCP.Mth < {ts '2017-04-02 00:00:00'}
AND JCJM.ProjectMgr = 8
AND JCCM.Department = '10'
ORDER BY JCJP.Contract, JCJP.Item, JCJP.Phase, JCCP.CostType
Hoping you can help.
We have an app that displays a grid. We can add custom fields to the grid using subqueries with which I am struggling. The main grid query looks like this.
SELECT TOP 300000
'' AS alloc_status
,'' AS stock_status
,wo_description
,wo_quantity
,wo_number
,wo_pwos_id
,vad_variant_code
,oh_order_number
,oh_datetime
,ohd_dm_id
,ohd_customer_name
,vad_description AS vad_description_Condition
,vad_variant_code AS vad_variant_code_Condition
,wo_id AS key_id
FROM works_order
LEFT OUTER JOIN works_order_analysis
ON works_order_analysis.woa_wo_id = works_order.wo_id
LEFT OUTER JOIN works_order_process
ON works_order_process.wop_id = works_order.wo_current_wop_id
LEFT OUTER JOIN works_order_process_analysis
ON works_order_process_analysis.wopa_wop_id = works_order_process.wop_id
INNER JOIN variant_detail
ON variant_detail.vad_id = works_order.wo_vad_id
LEFT OUTER JOIN works_order_total
ON works_order.wo_id = works_order_total.wot_wo_id
LEFT JOIN order_line_item
ON oli_id = wo_oli_id
LEFT JOIN order_header
ON oh_id = oli_oh_id
LEFT JOIN job_number
ON jn_id = wo_jn_id
LEFT JOIN works_order_process_subcontract_analysis
ON wopsa_wop_id = wop_id
LEFT JOIN order_header_detail
ON ohd_oh_id = oh_id
LEFT JOIN customer_detail
ON cd_id = oh_cd_id
WHERE ((cd_ow_account = 'NOTHS')
AND (wo_pwos_id = 1)
OR (cd_ow_account = 'EBAY')
AND (wo_pwos_id = 1)
OR (cd_ow_account = '4008')
AND (wo_pwos_id = 1)
OR (cd_ow_account = 'TRUSCA')
AND (wo_pwos_id = 1))
AND ((wo_required_datetime <= '2016-12-24 23:59:59'
OR wo_required_datetime IS NULL)
AND (wo_wos_id <> 4)
AND (wo_kit = 0))
The subquery is to basically provide a column that looks at the sales order and returns a count of row within that order. When I do this I get the following:
There was a problem retrieving the data:
subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, < etc
or when the subquery is used as an expression
Below is the query complete with subquery. If anyone can help that would be amazing
SELECT TOP 300000
'' AS alloc_status
,'' AS stock_status
,wo_description
,wo_quantity
,wo_number
,wo_pwos_id
,vad_variant_code
,oh_order_number
,oh_datetime
,ohd_dm_id
,ohd_customer_name
,(SELECT
COUNT(order_line_item.oli_id) AS 'Count'
FROM dbo.order_line_item
INNER JOIN dbo.order_header
ON order_line_item.oli_oh_id = order_header.oh_id
INNER JOIN dbo.variant_detail
ON order_line_item.oli_vad_id = variant_detail.vad_id
INNER JOIN dbo.variant_setting
ON variant_setting.vas_vad_id = variant_detail.vad_id
WHERE variant_setting.vas_manufactured_variant = 1
GROUP BY order_header.oh_order_number)
AS CustomLineCount
,vad_description AS vad_description_Condition
,vad_variant_code AS vad_variant_code_Condition
,wo_id AS key_id
FROM works_order
LEFT OUTER JOIN works_order_analysis
ON works_order_analysis.woa_wo_id = works_order.wo_id
LEFT OUTER JOIN works_order_process
ON works_order_process.wop_id = works_order.wo_current_wop_id
LEFT OUTER JOIN works_order_process_analysis
ON works_order_process_analysis.wopa_wop_id = works_order_process.wop_id
INNER JOIN variant_detail
ON variant_detail.vad_id = works_order.wo_vad_id
LEFT OUTER JOIN works_order_total
ON works_order.wo_id = works_order_total.wot_wo_id
LEFT JOIN order_line_item
ON oli_id = wo_oli_id
LEFT JOIN order_header
ON oh_id = oli_oh_id
LEFT JOIN job_number
ON jn_id = wo_jn_id
LEFT JOIN works_order_process_subcontract_analysis
ON wopsa_wop_id = wop_id
LEFT JOIN order_header_detail
ON ohd_oh_id = oh_id
LEFT JOIN customer_detail
ON cd_id = oh_cd_id
WHERE ((cd_ow_account = 'NOTHS')
AND (wo_pwos_id = 1)
OR (cd_ow_account = 'EBAY')
AND (wo_pwos_id = 1)
OR (cd_ow_account = '4008')
AND (wo_pwos_id = 1)
OR (cd_ow_account = 'TRUSCA')
AND (wo_pwos_id = 1))
AND ((wo_required_datetime <= '2016-12-24 23:59:59'
OR wo_required_datetime IS NULL)
AND (wo_wos_id <> 4)
AND (wo_kit = 0))
Try the below query, it may helps you
SELECT TOP 300000
'' AS alloc_status
,'' AS stock_status
,wo_description
,wo_quantity
,wo_number
,wo_pwos_id
,vad_variant_code
,oh_order_number
,oh_datetime
,ohd_dm_id
,ohd_customer_name
,(SELECT
COUNT(order_line_item.oli_id) AS 'Count'
FROM dbo.order_line_item
INNER JOIN dbo.order_header
ON order_line_item.oli_oh_id = order_header.oh_id
INNER JOIN dbo.variant_detail
ON order_line_item.oli_vad_id = variant_detail.vad_id
INNER JOIN dbo.variant_setting
ON variant_setting.vas_vad_id = variant_detail.vad_id
WHERE variant_setting.vas_manufactured_variant = 1
and order_header.oh_order_number=ordhead.oh_order_number)
AS CustomLineCount
,vad_description AS vad_description_Condition
,vad_variant_code AS vad_variant_code_Condition
,wo_id AS key_id
FROM works_order
LEFT OUTER JOIN works_order_analysis
ON works_order_analysis.woa_wo_id = works_order.wo_id
LEFT OUTER JOIN works_order_process
ON works_order_process.wop_id = works_order.wo_current_wop_id
LEFT OUTER JOIN works_order_process_analysis
ON works_order_process_analysis.wopa_wop_id = works_order_process.wop_id
INNER JOIN variant_detail
ON variant_detail.vad_id = works_order.wo_vad_id
LEFT OUTER JOIN works_order_total
ON works_order.wo_id = works_order_total.wot_wo_id
LEFT JOIN order_line_item
ON oli_id = wo_oli_id
LEFT JOIN order_header ordhead
ON oh_id = oli_oh_id
LEFT JOIN job_number
ON jn_id = wo_jn_id
LEFT JOIN works_order_process_subcontract_analysis
ON wopsa_wop_id = wop_id
LEFT JOIN order_header_detail
ON ohd_oh_id = oh_id
LEFT JOIN customer_detail
ON cd_id = oh_cd_id
WHERE ((cd_ow_account = 'NOTHS')
AND (wo_pwos_id = 1)
OR (cd_ow_account = 'EBAY')
AND (wo_pwos_id = 1)
OR (cd_ow_account = '4008')
AND (wo_pwos_id = 1)
OR (cd_ow_account = 'TRUSCA')
AND (wo_pwos_id = 1))
AND ((wo_required_datetime <= '2016-12-24 23:59:59'
OR wo_required_datetime IS NULL)
AND (wo_wos_id <> 4)
AND (wo_kit = 0))
Change your sub query to this:
(SELECT
COUNT(order_line_item.oli_id) AS 'Count'
FROM dbo.order_line_item
INNER JOIN dbo.order_header
ON order_line_item.oli_oh_id = order_header.oh_id
INNER JOIN dbo.variant_detail
ON order_line_item.oli_vad_id = variant_detail.vad_id
INNER JOIN dbo.variant_setting
ON variant_setting.vas_vad_id = variant_detail.vad_id
WHERE variant_setting.vas_manufactured_variant = 1
AND order_header.oh_order_number = OUTER_QUERY_TABLE.SAME_FIELD )
I've added this line:
AND order_header.oh_order_number = OUTER_QUERY_TABLE.SAME_FIELD
You have to make this query correlated , so add the condition to match the record to the outer query . I didn't know which field it is.
You could also optimize your WHERE and make it more readable with IN() :
WHERE wo_pwos_id = 1
AND cd_ow_account IN('NOTHS','EBAY','4008','TRUSCA')
AND (wo_required_datetime <= '2016-12-24 23:59:59' OR wo_required_datetime IS NULL)
AND wo_wos_id <> 4
AND wo_kit = 0
I'm fairly new to writing queries and I'm struggling with getting the next to queries combined:
SELECT od.ODCode
, c.Description as 'Line Position'
, ps.Description as 'Pallet Stacking'
, pt.Description as 'Pallet Type'
, odex.PalletRows
, odex.PalletTypeID
,CONCAT(( SELECT sp.SpecPropertyValue FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'DocDir'and sc.specclassname = 'Pallettypedoc'
),
(SELECT sp.SpecPropertyValue FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'Documentname'and sc.specclassname = 'Pallettypedoc' )) AS Spec
FROM ODExitPallet odex
INNER JOIN OperationDescr od
ON od.OperationDescrID=odex.OperationDescrID
INNER JOIN PalletStacking ps
ON ps.PalletStackingID=odex.PalletStackingID
INNER JOIN PalletType pt
ON pt.PalletTypeID=odex.PalletTypeID
INNER JOIN Code c
on c.CodeNumber=odex.LinePosition and c.CodeTypeID=72
INNER JOIN WorkOrder wo
on wo.OperationDescrID=odex.OperationDescrID
WHERE wo.WorkOrderID = #WorkOrderID
and
SELECT SUM(PlannedBatch) / SUM(NominalBlanks * Stacks) as NrOfPallets
FROM (SELECT WO.PlannedBatch, WO.NominalBlanks, ODEP.OperationDescrID, LinePosition,
Case when COUNT(*) = 0 then 1
else COUNT(*)
end as Stacks
FROM WorkOrder Wo
INNER JOIN ODExitPallet ODEX
ON WO.operationDescrID = ODEX.OperationDescrID
INNER JOIN Stacking ST
ON ST.PalletStackingID = ODEX.PalletStackingID
WHERE WO.WorkOrderID = #WorkOrderID
GROUP BY PlannedBatch, NominalBlanks, ODEX.OperationDescrID, LinePosition
) TOTAL
So I want to add the second query as a field in my first one. I've tried it with numerous thing like parentheses and stuff but I keep getting errors. Can someone enlighten me?
insert ( ) in whole second Query but make sure you second query return only 1 row
SELECT od.ODCode
, c.Description as 'Line Position'
, ps.Description as 'Pallet Stacking'
, pt.Description as 'Pallet Type'
, odex.PalletRows
, odex.PalletTypeID
,CONCAT(
(
SELECT sp.SpecPropertyValue
FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'DocDir'and sc.specclassname = 'Pallettypedoc'
)
,
(
SELECT sp.SpecPropertyValue FROM SpecificationProperty sp
INNER JOIN specificationclass sc ON sc.specclassid = sp.specclassid
INNER JOIN specificationcode sco ON sco.specclassid = sc.specclassid and sco.speccodeid = pt.pallettypeid
INNER JOIN SpecificationClassProperty scp ON scp.specClassid = sp.specclassid and scp.specpropertyid = sp.specpropertyid and sco.speccodeid = sp.speccodeid
WHERE scp.specpropertyname = 'Documentname'and sc.specclassname = 'Pallettypedoc'
)
) AS Spec
,(
SELECT SUM(PlannedBatch) / SUM(NominalBlanks * Stacks)
FROM (
SELECT WO.PlannedBatch, WO.NominalBlanks, ODEP.OperationDescrID, LinePosition,
Case when COUNT(*) = 0 then 1
else COUNT(*)
end as Stacks
FROM WorkOrder Wo
INNER JOIN ODExitPallet ODEX
ON WO.operationDescrID = ODEX.OperationDescrID
INNER JOIN Stacking ST
ON ST.PalletStackingID = ODEX.PalletStackingID
WHERE WO.WorkOrderID = #WorkOrderID
GROUP BY PlannedBatch, NominalBlanks, ODEX.OperationDescrID, LinePosition
) TOTAL
) AS [NrOfPallets]
FROM ODExitPallet odex
INNER JOIN OperationDescr od ON od.OperationDescrID=odex.OperationDescrID
INNER JOIN PalletStacking ps ON ps.PalletStackingID=odex.PalletStackingID
INNER JOIN PalletType pt ON pt.PalletTypeID=odex.PalletTypeID
INNER JOIN Code c on c.CodeNumber=odex.LinePosition and c.CodeTypeID=72
INNER JOIN WorkOrder wo on wo.OperationDescrID=odex.OperationDescrID
WHERE wo.WorkOrderID = #WorkOrderID
Trying to get the last/lastest record from ShipHead.Shipdate instead of all the records How do i Do last record with this query?
SELECT
OrderRel.ReqDate
,OrderHed.EntryPerson
,ShipHead.ShipDate
,Customer.Name
,ShipDtl.OrderNum
,ShipDtl.OrderLine
,ShipDtl.OrderRelNum
FROM
OrderHed
INNER JOIN OrderDtl
ON OrderHed.Company = OrderDtl.Company AND OrderHed.OrderNum = OrderDtl.OrderNum
INNER JOIN OrderRel
ON OrderDtl.Company = OrderRel.Company AND OrderDtl.OrderNum = OrderRel.OrderNum AND OrderDtl.OrderLine = OrderRel.OrderLine
INNER JOIN ShipDtl
ON OrderRel.Company = ShipDtl.Company AND OrderRel.OrderNum = ShipDtl.OrderNum AND OrderRel.OrderLine = ShipDtl.OrderLine AND OrderRel.OrderRelNum = ShipDtl.OrderRelNum
INNER JOIN ShipHead
ON ShipDtl.Company = ShipHead.Company AND ShipDtl.PackNum = ShipHead.PackNum
INNER JOIN Customer
ON ShipHead.Company = Customer.Company AND ShipHead.CustNum = Customer.CustNum
WHERE
OrderRel.OrderNum = 603205
You could try the following. If you wanted the last dated record for each entry person then change to the B:
SELECT
X.ReqDate,
X.EntryPerson,
X.ShipDate,
X.Name,
X.OrderNum,
X.OrderLine,
X.OrderRelNum
FROM
(
SELECT
ORl.ReqDate,
OH.EntryPerson,
SH.ShipDate,
rn = row_number() OVER(ORDER BY SH.ShipDate DESC),
--rn = row_number() OVER(PARTITION BY OH.EntryPerson ORDER BY SH.ShipDate DESC) --<<B
C.Name,
SD.OrderNum,
SD.OrderLine,
SD.OrderRelNum
FROM
OrderHed OH
INNER JOIN OrderDtl OD ON
OH.Company = OD.Company AND
OH.OrderNum = OD.OrderNum
INNER JOIN OrderRel ORl ON
OD.Company = ORl.Company AND
OD.OrderNum = ORl.OrderNum AND
OD.OrderLine = ORl.OrderLine
INNER JOIN ShipDtl SD ON
ORl.Company = SD.Company AND
ORl.OrderNum = SD.OrderNum AND
ORl.OrderLine = SD.OrderLine AND
ORl.OrderRelNum = SD.OrderRelNum
INNER JOIN ShipHead SH ON
SD.Company = SH.Company AND
SD.PackNum = SH.PackNum
INNER JOIN Customer C ON
SH.Company = C.Company AND
SH.CustNum = C.CustNum
WHERE
ORl.OrderNum = 603205
) X
WHERE X.rn = 1
P.S. why don't you use shorter aliases - that is part of the point of aliases
I have a big query as following, someone please tweak this query? i need to avoid this big group by ... :-)
SELECT COALESCE( SUM(total_retail), 0 ) total_retail,
COALESCE( SUM(meterial_sub_total), 0 ) meterial_sub_total,
COALESCE( MIN(po_template_group_by_code), 0 ) po_template_group_by_code,
COALESCE( MIN(po_template_sort_by_code), 0 ) po_template_sort_by_code
FROM
(
SELECT
COALESCE( CASE WHEN COALESCE(ihbol.valuation_method_code, pih.valuation_method_code, #default_valuation_method_code, 'i') IN ('r', 'i', 'l') THEN
COALESCE ( rmiretail.retail_price / rmiretail.unit_of_measure_quantity
/ COALESCE( uomcvrmi.atomic_conversion_factor * UOMrmi.factor, UOMrmi.factor ), 0 )
* poi.confirmed_quantity
* ( CASE WHEN poi.catch_weight_flag = 'y'
THEN ( poi.package_weight * COALESCE( uomcvpr.atomic_conversion_factor * UOMpr.factor, UOMpr.factor ) )
WHEN si.shipper_flag = 'y'
THEN ( meterial_data.linked_meterial_quantity * COALESCE( uomcvitm.atomic_conversion_factor * uomitm.factor, uomitm.factor ) )
ELSE ( COALESCE( uomcvpkg.atomic_conversion_factor * UOMpkg.factor, UOMpkg.factor ) )
END )
ELSE
NULL
END, 0 ) AS total_retail,
CASE WHEN MIN(s.rcv_using_po_default_cost_target_code) = 'p' AND MIN(po.status_code) <> 't'
THEN COALESCE( MIN(po.last_draft_total), 0 )
ELSE CASE WHEN meterial_data.linked_meterial_quantity IS NULL
THEN CASE WHEN poi.catch_weight_flag = 'y'
THEN COALESCE( poi.confirmed_quantity * poi.package_weight * spicost.net_supplier_price, 0 )
ELSE COALESCE( poi.confirmed_quantity * spicost.net_supplier_price, 0 )
END
ELSE 0
END
END AS meterial_sub_total
,po.po_template_group_by_code AS po_template_group_by_code
,po.po_template_sort_by_code AS po_template_sort_by_code
FROM purchase_order po
JOIN supplier s WITH (NOLOCK)
ON po.supplier_id = s.supplier_id
JOIN purchase_order_meterial poi WITH (NOLOCK)
ON po.purchase_order_id = poi.purchase_order_id
AND po.business_unit_id = poi.business_unit_id
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
AND poi.supplier_id = si.supplier_id
JOIN supplier_packaged_meterial spi WITH (NOLOCK)
ON spi.supplier_meterial_id = si.supplier_meterial_id
AND spi.supplier_id = #supplier_id:int
JOIN unit_of_measure uompkg WITH (NOLOCK)
ON uompkg.unit_of_measure_id = spi.packaged_in_uom_id
JOIN merch_bu_spi_cost_list spicost WITH (NOLOCK)
ON spicost.business_unit_id = #bu_id:int
AND spicost.supplier_id = si.supplier_id
AND spicost.supplier_meterial_id = si.supplier_meterial_id
AND spicost.packaged_meterial_id = spi.packaged_meterial_id
LEFT OUTER JOIN
(
SELECT poi.supplier_meterial_id AS supplier_meterial_id,
si.meterial_id AS linked_meterial_id,
NULL AS linked_meterial_uom,
NULL AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
UNION ALL
SELECT siil.supplier_meterial_id AS supplier_meterial_id,
siil.inventory_meterial_id AS linked_meterial_id,
siil.unit_of_measure_id AS linked_meterial_uom,
siil.inventory_meterial_quantity AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_inventory_meterial_list siil WITH (NOLOCK)
ON siil.supplier_id = #supplier_id:int
AND poi.supplier_meterial_id = siil.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
) meterial_data
ON meterial_data.supplier_meterial_id = si.supplier_meterial_id
LEFT OUTER JOIN meterial i
ON i.meterial_id = meterial_data.linked_meterial_id
LEFT OUTER JOIN meterial_hierarchy ih
ON ih.meterial_hierarchy_id = COALESCE(si.meterial_hierarchy_id, i.meterial_hierarchy_id)
LEFT OUTER JOIN meterial_hierarchy pih
ON ih.setstring LIKE pih.setstring + '%'
AND pih.meterial_hierarchy_level_id = #meterial_hierarchy_level_id
LEFT OUTER JOIN meterial_hierarchy_bu_override_list ihbol
ON ihbol.business_unit_id = #bu_id:int
AND ihbol.meterial_hierarchy_id = pih.meterial_hierarchy_id
LEFT OUTER JOIN retail_modified_meterial rmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = rmi.retail_meterial_id
AND rmi.retail_valuation_flag = 'y'
LEFT OUTER JOIN merch_bu_rmi_retail_list rmiretail WITH (NOLOCK)
ON rmiretail.retail_modified_meterial_id = rmi.retail_modified_meterial_id
AND rmiretail.business_unit_id = #bu_id:int
LEFT OUTER JOIN unit_of_measure uompr WITH (NOLOCK)
ON uompr.unit_of_measure_id = spi.priced_in_uom_id
LEFT OUTER JOIN unit_of_measure uomitm WITH (NOLOCK)
ON uomitm.unit_of_measure_id = meterial_data.linked_meterial_uom
LEFT OUTER JOIN unit_of_measure uomrmi WITH (NOLOCK)
ON uomrmi.unit_of_measure_id = rmi.unit_of_measure_id
LEFT OUTER JOIN meterial_uom_conversion uomcvitm WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvitm.meterial_id
AND uomitm.unit_of_measure_class_id = uomcvitm.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvrmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvrmi.meterial_id
AND uomrmi.unit_of_measure_class_id = uomcvrmi.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpr WITH (NOLOCK)
ON uomcvpr.meterial_id = meterial_data.linked_meterial_id
AND uomcvpr.unit_of_measure_class_id = uompr.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpkg WITH (NOLOCK)
ON uomcvpkg.meterial_id = meterial_data.linked_meterial_id
AND uomcvpkg.unit_of_measure_class_id = uompkg.unit_of_measure_class_id
WHERE po.purchase_order_id = #po_id:int
AND po.business_unit_id = #bu_id:int
GROUP BY poi.supplier_meterial_id, poi.confirmed_quantity, spicost.net_supplier_price,
meterial_data.linked_meterial_quantity,poi.catch_weight_flag,poi.package_weight,
ihbol.valuation_method_code, pih.valuation_method_code,rmiretail.retail_price,
rmiretail.unit_of_measure_quantity, uomcvrmi.atomic_conversion_factor, UOMrmi.factor,
UOMrmi.factor, uomcvpr.atomic_conversion_factor, UOMpr.factor, si.shipper_flag,
meterial_data.linked_meterial_quantity, uomcvitm.atomic_conversion_factor ,uomitm.factor,
uomitm.factor, uomcvpkg.atomic_conversion_factor,UOMpkg.factor, UOMpkg.factor,
po.po_template_group_by_code, po.po_template_sort_by_code
) resultTable
Try:
SELECT COALESCE( SUM(total_retail), 0 ) total_retail,
COALESCE( SUM(meterial_sub_total), 0 ) meterial_sub_total,
COALESCE( MIN(po_template_group_by_code), 0 ) po_template_group_by_code,
COALESCE( MIN(po_template_sort_by_code), 0 ) po_template_sort_by_code
FROM
(
SELECT
sum(COALESCE( CASE WHEN COALESCE(ihbol.valuation_method_code, pih.valuation_method_code, #default_valuation_method_code, 'i') IN ('r', 'i', 'l') THEN
COALESCE ( rmiretail.retail_price / rmiretail.unit_of_measure_quantity
/ COALESCE( uomcvrmi.atomic_conversion_factor * UOMrmi.factor, UOMrmi.factor ), 0 )
* poi.confirmed_quantity
* ( CASE WHEN poi.catch_weight_flag = 'y'
THEN ( poi.package_weight * COALESCE( uomcvpr.atomic_conversion_factor * UOMpr.factor, UOMpr.factor ) )
WHEN si.shipper_flag = 'y'
THEN ( meterial_data.linked_meterial_quantity * COALESCE( uomcvitm.atomic_conversion_factor * uomitm.factor, uomitm.factor ) )
ELSE ( COALESCE( uomcvpkg.atomic_conversion_factor * UOMpkg.factor, UOMpkg.factor ) )
END )
ELSE
NULL
END, 0 )) AS total_retail,
sum(CASE WHEN MIN(s.rcv_using_po_default_cost_target_code) = 'p' AND MIN(po.status_code) <> 't'
THEN COALESCE( MIN(po.last_draft_total), 0 )
ELSE CASE WHEN meterial_data.linked_meterial_quantity IS NULL
THEN CASE WHEN poi.catch_weight_flag = 'y'
THEN COALESCE( poi.confirmed_quantity * poi.package_weight * spicost.net_supplier_price, 0 )
ELSE COALESCE( poi.confirmed_quantity * spicost.net_supplier_price, 0 )
END
ELSE 0
END
END) AS meterial_sub_total
,po.po_template_group_by_code AS po_template_group_by_code
,po.po_template_sort_by_code AS po_template_sort_by_code
FROM purchase_order po
JOIN supplier s WITH (NOLOCK)
ON po.supplier_id = s.supplier_id
JOIN purchase_order_meterial poi WITH (NOLOCK)
ON po.purchase_order_id = poi.purchase_order_id
AND po.business_unit_id = poi.business_unit_id
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
AND poi.supplier_id = si.supplier_id
JOIN supplier_packaged_meterial spi WITH (NOLOCK)
ON spi.supplier_meterial_id = si.supplier_meterial_id
AND spi.supplier_id = #supplier_id:int
JOIN unit_of_measure uompkg WITH (NOLOCK)
ON uompkg.unit_of_measure_id = spi.packaged_in_uom_id
JOIN merch_bu_spi_cost_list spicost WITH (NOLOCK)
ON spicost.business_unit_id = #bu_id:int
AND spicost.supplier_id = si.supplier_id
AND spicost.supplier_meterial_id = si.supplier_meterial_id
AND spicost.packaged_meterial_id = spi.packaged_meterial_id
LEFT OUTER JOIN
(
SELECT poi.supplier_meterial_id AS supplier_meterial_id,
si.meterial_id AS linked_meterial_id,
NULL AS linked_meterial_uom,
NULL AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_meterial si WITH (NOLOCK)
ON poi.supplier_meterial_id = si.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
UNION ALL
SELECT siil.supplier_meterial_id AS supplier_meterial_id,
siil.inventory_meterial_id AS linked_meterial_id,
siil.unit_of_measure_id AS linked_meterial_uom,
siil.inventory_meterial_quantity AS linked_meterial_quantity
FROM purchase_order_meterial poi WITH (NOLOCK)
JOIN supplier_inventory_meterial_list siil WITH (NOLOCK)
ON siil.supplier_id = #supplier_id:int
AND poi.supplier_meterial_id = siil.supplier_meterial_id
WHERE poi.purchase_order_id = #po_id:int
AND poi.business_unit_id = #bu_id:int
) meterial_data
ON meterial_data.supplier_meterial_id = si.supplier_meterial_id
LEFT OUTER JOIN meterial i
ON i.meterial_id = meterial_data.linked_meterial_id
LEFT OUTER JOIN meterial_hierarchy ih
ON ih.meterial_hierarchy_id = COALESCE(si.meterial_hierarchy_id, i.meterial_hierarchy_id)
LEFT OUTER JOIN meterial_hierarchy pih
ON ih.setstring LIKE pih.setstring + '%'
AND pih.meterial_hierarchy_level_id = #meterial_hierarchy_level_id
LEFT OUTER JOIN meterial_hierarchy_bu_override_list ihbol
ON ihbol.business_unit_id = #bu_id:int
AND ihbol.meterial_hierarchy_id = pih.meterial_hierarchy_id
LEFT OUTER JOIN retail_modified_meterial rmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = rmi.retail_meterial_id
AND rmi.retail_valuation_flag = 'y'
LEFT OUTER JOIN merch_bu_rmi_retail_list rmiretail WITH (NOLOCK)
ON rmiretail.retail_modified_meterial_id = rmi.retail_modified_meterial_id
AND rmiretail.business_unit_id = #bu_id:int
LEFT OUTER JOIN unit_of_measure uompr WITH (NOLOCK)
ON uompr.unit_of_measure_id = spi.priced_in_uom_id
LEFT OUTER JOIN unit_of_measure uomitm WITH (NOLOCK)
ON uomitm.unit_of_measure_id = meterial_data.linked_meterial_uom
LEFT OUTER JOIN unit_of_measure uomrmi WITH (NOLOCK)
ON uomrmi.unit_of_measure_id = rmi.unit_of_measure_id
LEFT OUTER JOIN meterial_uom_conversion uomcvitm WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvitm.meterial_id
AND uomitm.unit_of_measure_class_id = uomcvitm.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvrmi WITH (NOLOCK)
ON meterial_data.linked_meterial_id = uomcvrmi.meterial_id
AND uomrmi.unit_of_measure_class_id = uomcvrmi.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpr WITH (NOLOCK)
ON uomcvpr.meterial_id = meterial_data.linked_meterial_id
AND uomcvpr.unit_of_measure_class_id = uompr.unit_of_measure_class_id
LEFT OUTER JOIN meterial_uom_conversion uomcvpkg WITH (NOLOCK)
ON uomcvpkg.meterial_id = meterial_data.linked_meterial_id
AND uomcvpkg.unit_of_measure_class_id = uompkg.unit_of_measure_class_id
WHERE po.purchase_order_id = #po_id:int
AND po.business_unit_id = #bu_id:int
GROUP BY po.po_template_group_by_code, po.po_template_sort_by_code
) resultTable
I think it should return the same results as the query above, although whether those results are what you actually want is a different matter...