select distinct sotr_sys_no
, SODETS_VINYL_COLOUR
, SODETS_MDF_COLOUR
, SOTR_PROMISED_DATE
, DATEDIFF(dd,getdate(),sotr_promised_date) as DueDays
, AEXTRA_5_SHORT_NAME
, AEXTRA_5_VINYL_PARTCODE
, CASE WHEN SODETS_MDF_COLOUR > '0' THEN AltMDFCode ELSE AEXTRA_5_MDF_PARTCODE END AS AEXTRA_5_MDF_PARTCODE
, ISNULL(Vinylqty,0) As VinylQty
, ISNULL(MDFqty,0) as MDFQty
, Vinyldue
, MDFdue
, WO.WOOutstanding
from Defactouser.F_SO_Transaction WITH (NOLOCK)
inner join defactouser.F_SO_Transaction_Details WITH (NOLOCK)
on sotr_sys_no = sotd_head_no
inner join defactouser.F_SO_Transaction_Details_Extra WITH (NOLOCK)
on SOTD_SYS_NO = SODETS_LINK
left outer join (
select distinct AEXTRA_5_CODE as AltMDFKey
, AEXTRA_5_MDF_PARTCODE AS AltMDFCode
from DeFactoUser.F_AD_Extra_5 WITH (NOLOCK)
) as AltMDF
on SODETS_MDF_COLOUR = AltMDF.AltMDFKey
left outer join defactouser.F_AD_Extra_5 WITH (NOLOCK)
on SODETS_VINYL_COLOUR = [AEXTRA_5_CODE]
inner join defactouser.F_ST_Products WITH (NOLOCK)
on sotd_strc_code = strc_code
left Outer join (
SELECT Product_Code As VinylStockCode, sum(Physical_Qty_Units) as Vinylqty FROM DBO.DFBI_Stock_Physical WITH (NOLOCK)
WHERE Warehouse = 'DOORS' and LEFT(product_code ,3) = 'vfl'
Group By Product_Code
HAVING SUM(Physical_Qty_Units) >0
) VinylStock
on AEXTRA_5_VINYL_PARTCODE = VinylStock.VinylStockCode
left outer join (
SELECT Product_Code As MDFStockCode, sum(Physical_Qty_Units) as MDFqty FROM DBO.DFBI_Stock_Physical WITH (NOLOCK)
WHERE Warehouse = 'PANELS' and LEFT(product_code ,3) = 'MDF'
Group By Product_Code
HAVING SUM(Physical_Qty_Units) >0
) MDFStock
on CASE WHEN SODETS_MDF_COLOUR > '0' THEN AltMDF.AltMDFCode ELSE AEXTRA_5_MDF_PARTCODE END = MDFStock.MDFStockCode
left Outer JOin (select stex_strc_code as VinylStex , sum(STEX_QTY_UNITS) as Qty, MIN(stex_promised_date) as Vinyldue
from defactouser.F_ST_Transaction_Expediting
where left(stex_strc_code ,3) = 'vfl'
and stex_type = 'pop+'
group By STEX_STRC_CODE
) VinylStockIn
on AEXTRA_5_VINYL_PARTCODE = VinylStex
left Outer Join (
select stex_strc_code as MDFStex , sum(STEX_QTY_UNITS) as Qty, MIN(stex_promised_date) as MDFdue
from defactouser.F_ST_Transaction_Expediting
where left(stex_strc_code ,3) = 'mdf'
and stex_type = 'pop+'
group By STEX_STRC_CODE
) MDFStockIn on CASE WHEN SODETS_MDF_COLOUR > '0' THEN AltMDF.AltMDFCode ELSE AEXTRA_5_MDF_PARTCODE END = MDFStex
LEFT OUTER JOIN (
select SOTD_HEAD_NO, SODETS_VINYL_COLOUR as WOVinyl, SUM(BMTD_QTY_OUTSTANDING) as WOOutstanding from defactouser.f_bm_transactions_details
inner join defactouser.F_SO_Transaction_Details on BMTD_ORDER_LINK_NUMBER = SOTD_SYS_NO
inner join defactouser.F_SO_Transaction_Details_Extra on BMTD_ORDER_LINK_NUMBER = SODETS_LINK
where bmtd_type = 1 and bmtd_bmtr_type = 0 and bmtd_stwh_code in ('doors', 'shef trans') and SOTD_STATUS <99
Group by SOTD_HEAD_NO, SODETS_VINYL_COLOUR
) WO
on sotr_sys_no = WO.SOTD_HEAD_NO AND SODETS_VINYL_COLOUR = WO.WOVinyl
where (SOTD_QTY_UNITS_OUTSTANDING > 0
and SOTR_TYPE = 10
and SOTD_STWH_CODE IN ('doors' , 'hpp shef')
and left(sotd_strc_code ,5) <> 'drill'
and SOTR_CUST_CODE <>'hpp'
and STRC_ANAL1 = '1027'
and ISNULL(VinylQty,0) <10
and DATEDIFF(dd,getdate(),sotr_promised_date) <5
)
or
(SOTD_QTY_UNITS_OUTSTANDING > 0
and SOTR_TYPE = 10
and SOTD_STWH_CODE IN ('doors' , 'hpp shef')
and left(sotd_strc_code ,5) <> 'drill'
and SOTR_CUST_CODE <>'hpp'
and STRC_ANAL1 = '1027'
and ISNULL(MDFQty,0) <4
and DATEDIFF(dd,getdate(),sotr_promised_date) <5
)
Order By MDFQty, AEXTRA_5_MDF_PARTCODE
Currently this query produces a report that returns a table with products due to arrive in the next 5 days. How do I add a parameter to the report that will show me the results as it is, and then also to show a report for products due in whenever. I am using Report Builder 3.0, and have tried to add a parameter but cannot get the desired result.
Can this be done without editing the query and just in report builder?
Change you WHERE clause and replace < 5 with < #Days. Assuming the query is not a stored proc and is directly in the dataset query then SSRS will automatically add the #Days parameter to your report.
Related
I have a table with customers that I join with a fact table with sales, based on invoices.
What I need from my report is to get in first part the biggest value of sales based on the incoming order type (1,2,3,C,D) for a customer for last year. And in the second part to get the same but for current year. What I get as result from my current query is all incoming order types with the customer revenue made for each of them. I tried with outer apply as subquery to get only the top 1 value ordered by revenue descending, but in the result I get the same - For all order types the customer revenue. Please help! I hope my explanation isn't understood only by me (happens a lot..)
use dwh01;
WITH OrderTypeUsedLY AS
(
SELECT
c.CustomerKey
,c.BranchId
,c.CustomerId
,c.CustomerName
,ISNULL(SUM(y.[Sale_Revenue]), 0) as [Sale_Revenue_LY]
,ISNULL(SUM(y.[Sale_GrossMarginTotal]), 0) as [Sale_GrossMarginTotal_LY]
,y.IncomingOrderTypeId as IncomingOrderType_LY
FROM live.DimCustomer c
left join (SELECT s.CustomerKey,iot.IncomingOrderTypeid, s.[Sale_Revenue], s.[Sale_GrossMarginTotal] FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d
on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType iot on iot.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where s.ReportCurrencyId = 'LC'
and D.Year = YEAR(GETDATE())-1 --- Last Year
) y on c.CustomerKey = y.CustomerKey
where c.CustomerKey = '157053'
group by c.CustomerKey, c.CustomerId, c.CustomerName, c.BranchId, y.IncomingOrderTypeId
),
--*********************************************************************************************************************************--
OrderTypeCY as(
SELECT
c.CustomerKey
,c.BranchId
,c.SalesRepKey
,c.CustomerId
,c.CustomerName
,ISNULL(SUM(y.[Sale_Revenue]), 0) as [Sale_Revenue_CY]
,ISNULL(SUM(y.[Sale_GrossMarginTotal]), 0) as [Sale_GrossMarginTotal_CY]
,y.IncomingOrderTypeId as IncomingOrderType_CY
FROM live.DimCustomer c
left join (SELECT s.CustomerKey,iot.IncomingOrderTypeid, s.[Sale_Revenue], s.[Sale_GrossMarginTotal] FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d
on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType iot on iot.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where s.ReportCurrencyId = 'LC'
and D.Year = YEAR(GETDATE()) --- Current Year
) y on c.CustomerKey = y.CustomerKey
where c.CustomerKey = '157053'
group by c.CustomerKey, c.CustomerId, c.CustomerName, c.BranchId, y.IncomingOrderTypeId, c.SalesRepKey
)
--*********************************************************************************************************************************--
SELECT
otly.BranchId,
rep.SalesRepId,
rep.SalesRepName,
otly.CustomerId,
otly.CustomerName,
otly.Sale_Revenue_LY,
otly.Sale_GrossMarginTotal_LY,
IncomingOrderType_LY,
otcy.Sale_Revenue_CY,
otcy.Sale_GrossMarginTotal_CY,
IncomingOrderType_CY
from OrderTypeUsedLY otly
left join OrderTypeCY otcy
on otly.CustomerKey = otcy.CustomerKey
join live.DimCustomer cus on cus.CustomerKey = otcy.CustomerKey
join live.DimSalesRep rep on rep.SalesRepKey = otcy.SalesRepKey
order by otcy.Sale_Revenue_CY desc, otly.Sale_Revenue_LY desc
,rep.SalesRepId
And here is the outer apply I tried:
outer apply (
SELECT top 1
iot.IncomingOrderTypeId,
Sale_Revenue
FROM [dwh01].[live].DimIncomingOrderType iot
where iot.IncomingOrderTypeKey = y.IncomingOrderTypeKey
order by Sale_Revenue desc) x
In the first select ( with OrderTypeUsed_LY ) I get this:
And I get the same in the second select, but with the values for current year.
The purpose of the report is to see the difference in the incoming order type most used (most profit made with it) for a customer last year and to see if he continues to use it this year, or uses another incoming order type this year.
Again I'm sorry for the bad explanation, I'm trying my best (I understand myself very well)
Here is the expected result:
Expected Result
I marked in red the last year part and in green the current year part.
If you change the subquery to:
SELECT
iot.IncomingOrderTypeKey,
MAX(Sale_Revenue)
FROM [dwh01].[live].DimIncomingOrderType iot
GROUP BY iot.IncomingOrderTypeKey
then you can JOIN (not APPLY) directly on IncomingOrderTypeKey AND Sale_Revenue.
Try this:
USE dwh01;
DECLARE #CustomerKey varchar(6) = '157053'
, #ReportCurrencyId varchar(2) = 'LC'
, #CurrentYear int = YEAR(GETDATE())
, #TargetYear int = YEAR(GETDATE())-1
;
WITH FactsTable AS
(
SELECT
s.CustomerKey
, i.IncomingOrderTypeid
, [Sale_Revenue] = ISNULL(s.[Sale_Revenue] , 0)
, [Sale_GrossMarginTotal] = ISNULL(s.[Sale_GrossMarginTotal], 0)
, d.[Year]
FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType i on i.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where
s.CustomerKey = #CustomerKey
and s.ReportCurrencyId = #ReportCurrencyId
)
, OrderTypeTable
(
SELECT
c.CustomerKey
, c.BranchId
, c.CustomerId
, c.CustomerName
, c.SalesRepKey
, IncomingOrderType_LY = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.IncomingOrderTypeId ELSE 0 END)
, [Sale_Revenue_LY] = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.[Sale_Revenue] ELSE 0 END)
, [Sale_GrossMarginTotal_LY] = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.[Sale_GrossMarginTotal] ELSE 0 END)
, IncomingOrderType_LY = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.IncomingOrderTypeId ELSE 0 END)
, [Sale_Revenue_CY] = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.[Sale_Revenue] ELSE 0 END)
, [Sale_GrossMarginTotal_CY] = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.[Sale_GrossMarginTotal] ELSE 0 END)
FROM live.DimCustomer c
left join FactsTable y on y.CustomerKey = c.CustomerKey
group by
c.CustomerKey
, c.BranchId
, c.CustomerId
, c.CustomerName
, y.IncomingOrderTypeId
, c.SalesRepKey
)
SELECT
O.BranchId
, R.SalesRepId
, R.SalesRepName
, O.CustomerId
, O.CustomerName
, O.Sale_Revenue_LY
, O.Sale_GrossMarginTotal_LY
, O.IncomingOrderType_LY
, O.Sale_Revenue_CY
, O..Sale_GrossMarginTotal_CY
, O.IncomingOrderType_CY
from OrderTypeTable O
join live.DimSalesRep R on R.SalesRepKey = O.SalesRepKey
order by
O.Sale_Revenue_CY desc
, O.Sale_Revenue_LY desc
, R.SalesRepId
The solution is with using row_number() function in the inner query of the first CTE:
(
select *, row_number() over (partition by x0.CustomerKey order by x0.Sale_Revenue desc) as rn
from
(
select fs.CustomerKey, iot.IncomingOrderTypeKey,
sum(fs.Sale_Revenue) as Sale_Revenue
FROM [dwh01].[live].DimIncomingOrderType iot
join live.FactSales fs
on iot.IncomingOrderTypeKey = fs.IncomingOrderTypeKey
join live.DimDate d
on d.DateId = fs.PostingDateKey
where d.[year] = #CurrentYear
GROUP BY fs.CustomerKey, iot.IncomingOrderTypeKey
) as x0
) as x1 on x1.CustomerKey = s.CustomerKey
The row_number() function gets only the first row from the result for each customer, and that is with the biggest sale revenue ( order by sale_revenue desc).
I'm trying to run the following query for ssrs reporting services for a data portal in our Prophet 21 database (erp software from Epicor) and I'm running into some errors when trying to input the report in visual basic. I'm getting the following error:
TITLE: Microsoft SQL Server Report Designer
An error occurred while the query design method was being saved. An item with the same key has already been added.
BUTTONS:
OK
SELECT
inv_mast.item_desc,
oe_hdr.company_id,
oe_hdr.order_no,
oe_hdr.validation_status,
oe_hdr.order_date,
oe_hdr.requested_date,
oe_hdr.address_id,
oe_hdr.ship2_name,
oe_hdr.ship2_city,
oe_hdr.ship2_state,
oe_hdr_salesrep.salesrep_id,
p21_view_oe_line.line_no,
p21_view_oe_line.required_date
, inv_mast.item_id,
--p21_view_oe_line.qty_ordered,
p21_view_oe_line.unit_quantity,
p21_view_oe_line.unit_size,
p21_view_oe_line.qty_allocated,
p21_view_oe_line.qty_on_pick_tickets,
p21_view_oe_line.qty_invoiced,
p21_view_oe_line.qty_canceled,
p21_view_oe_line.unit_of_measure,
p21_view_oe_line.disposition,
p21_view_oe_line.unit_price,
CASE p21_view_oe_line.po_cost
WHEN 0 THEN
p21_view_oe_line.sales_cost ELSE
p21_view_oe_line.po_cost
END
oe_line_sales_cost,
po_hdr.supplier_id,
po_hdr.order_date,
po_line.date_due,
po_line.qty_ordered,
po_line.qty_received,
po_line.po_no,
po_hdr.po_class1,oe_hdr.customer_id,
customer.customer_name,
supplier.supplier_name,
oe_hdr.taker,
users.name
,contacts.first_name,
contacts.mi,
contacts.last_name,
p21_view_oe_line.pricing_unit,
p21_view_oe_line.pricing_unit_size,
p21_view_oe_line.qty_staged
, oe_hdr.location_id, location.location_name,
oe_hdr.completed,
oe_hdr.po_no,
customer.currency_id,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
p21_view_oe_line.unit_price_home
END
unit_price_home,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
CASE p21_view_oe_line.po_cost_home
WHEN 0 THEN
p21_view_oe_line.sales_cost_home
ELSE
p21_view_oe_line.po_cost_home
END END
oe_line_sales_cost_home,
company.home_currency_id,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
( p21_view_oe_line.qty_ordered - p21_view_oe_line.qty_invoiced - p21_view_oe_line.qty_canceled - p21_view_oe_line.qty_staged ) * ( p21_view_oe_line.unit_price_home / p21_view_oe_line.pricing_unit_size )
END calc_open_price_home,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
'Home : '
END currency_type
, CASE oe_hdr.job_control_flag
WHEN 'Y'
THEN oe_hdr.job_name
ELSE ''
END job_name,
oe_hdr.order_type,
p21_view_oe_line.user_line_no,
p21_view_prod_order_line_link.prod_order_number
--prod_order_hdr_ud.production_status
FROM oe_hdr
LEFT JOIN p21_view_oe_line ON p21_view_oe_line.order_no = oe_hdr.order_no
left join p21_view_prod_order_line_link ON p21_view_oe_line.oe_line_uid = p21_view_prod_order_line_link.transaction_uid
--left join prod_order_hdr_ud with (NOLOCK) ON p21_view_prod_order_line_link.prod_order_number = prod_order_hdr_ud.prod_order_number
left join prod_order_hdr with (NOLOCK) ON p21_view_prod_order_line_link.prod_order_number = prod_order_hdr.prod_order_number
LEFT JOIN company with (NOLOCK) ON company.company_id = oe_hdr.company_id
LEFT JOIN inv_mast with (NOLOCK) ON inv_mast.inv_mast_uid = p21_view_oe_line.inv_mast_uid
LEFT JOIN oe_hdr_salesrep with (NOLOCK) ON oe_hdr_salesrep.order_number = oe_hdr.order_no
LEFT JOIN contacts with (NOLOCK) ON contacts.id = oe_hdr_salesrep.salesrep_id LEFT JOIN customer ON customer.customer_id = oe_hdr.customer_id AND
customer.company_id = oe_hdr.company_id
LEFT JOIN users with (NOLOCK) ON users.id = oe_hdr.taker
LEFT JOIN location with (NOLOCK) ON location.location_id = oe_hdr.location_id
LEFT JOIN oe_line_po with (NOLOCK) LEFT JOIN po_hdr with (NOLOCK) ON po_hdr.po_no = oe_line_po.po_no
LEFT JOIN po_line with (NOLOCK) ON po_line.po_no = oe_line_po.po_no AND
po_line.line_no = oe_line_po.po_line_number
LEFT JOIN supplier with (NOLOCK) ON supplier.supplier_id = po_hdr.supplier_id
ON oe_line_po.order_number = oe_hdr.order_no AND
oe_line_po.line_number = p21_view_oe_line.line_no
AND
oe_line_po.delete_flag = 'N' AND
oe_line_po.cancel_flag = 'N' AND
oe_line_po.completed = 'N' AND
oe_line_po.connection_type = 'P'
WHERE
( oe_hdr_salesrep.primary_salesrep = 'Y' )
AND ( p21_view_oe_line.delete_flag = 'N' )
AND ( p21_view_oe_line.cancel_flag = 'N' )
AND ( p21_view_oe_line.complete = 'N') AND (( oe_hdr.completed <> 'Y') OR ((oe_hdr.completed = 'Y') ))
AND p21_view_oe_line.parent_oe_line_uid = '0'
AND (oe_hdr.rma_flag = 'N' )
AND ( oe_hdr.projected_order = 'N' )
--and (oe_hdr.order_type <> '1706')
--and (location_name = 'TriNova - Florida')
--AND prod_order_hdr.complete <> 'y'
-- and datediff(day , oe_hdr.order_date, getdate()) >= 5
-- AND ((oe_hdr.order_date + 5) < GETDATE())
-- AND (p21_view_audit_trail_oe_hdr_1319.date_created < dateadd(dd,5,p21_view_audit_trail_oe_hdr_1319.date_created))
--AND p21_view_audit_trail_oe_hdr_1319.date_created > GETDATE()
The errors is because you have two columns with the same name :
oe_hdr.order_date,
po_hdr.order_date,
You need to alias one of them
Same with
po_line.po_no,
oe_hdr.po_no,
Please ensure you format your code well so makes it easier to read
Easiest way to find them is to copy and paste your code into Notepad++ and double click on each column name.. notepad will highlight all instances of that word within the same document..
With the help of some of the users here in stackoverflow, I reached to the following query. The problem is that this query works well in SQL Server, but not in Sybase as it doesn't support LAG(). I have been trying to get it to work but no success.
The query is quite complicated but help in subsituting the LAG() function with something similar would be appreciated.
SELECT created
, bname
, total_share
FROM (
SELECT TT.created
, TT.bname
, TT.total_share
, lag(TT.total_share) OVER (
PARTITION BY TT.bname ORDER BY TT.created
) AS prev_share
FROM (
SELECT DISTINCT t.created AS created
, t.NAME AS bname
, t.total_share
FROM (
SELECT cast(fsp.created AS VARCHAR(19)) AS created
, e.NAME
, e.initials
, fsp.modified
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((fsp.new_price / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS new_share
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((prev / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS old_share
, fs.STATE
, CASE
WHEN fsp.prev_price IS NULL
THEN 0
ELSE fsp.prev_price
END AS prev
, fsp.new_price AS nprice
, (prev - nprice) AS diff
, new_share - old_share AS diff_share
, old_share + diff_share AS total_share
FROM project_manager pm
INNER JOIN dba.project p ON pm.project = p.id
LEFT JOIN dba.contract c ON p.id = c.project
LEFT JOIN dba.contract_line cl ON cl.contract = c.id
LEFT JOIN dba.product pt ON cl.product = pt.id
LEFT JOIN dba.specified_product sp ON sp.product = pt.id
LEFT JOIN dba.frozen_sale fs ON fs.spec_product = sp.id
AND fs.contract = c.id
AND fs.line = cl.idx
LEFT JOIN dba.frozen_sale_split fsp ON fsp.frozen_sale = fs.id
AND fsp.employee = pm.consultant
LEFT JOIN dba.employee e ON fsp.employee = e.person
LEFT JOIN dba.person ps ON fsp.creator = ps.id
WHERE p.id = 50000002735
AND e.NAME IS NOT NULL
) AS t
) TT /* here */
) x
WHERE (
prev_share IS NULL
OR prev_share total_share
)
ORDER BY created
, bname
The following code is untested, but the approach is to use the row_number window function to assign a sequential number (rnum in the code) to each row, ordered by the created value. This is done in the initial CTE. The main query then joins that CTE to itself, with a join condition of a difference of one in the rnum values.
with inp as (
SELECT TT.created
, TT.bname
, TT.total_share
, row_number over(order by TT.created) as rnum
FROM (
SELECT DISTINCT t.created AS created
, t.NAME AS bname
, t.total_share
FROM (
SELECT cast(fsp.created AS VARCHAR(19)) AS created
, e.NAME
, e.initials
, fsp.modified
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((fsp.new_price / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS new_share
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((prev / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS old_share
, fs.STATE
, CASE
WHEN fsp.prev_price IS NULL
THEN 0
ELSE fsp.prev_price
END AS prev
, fsp.new_price AS nprice
, (prev - nprice) AS diff
, new_share - old_share AS diff_share
, old_share + diff_share AS total_share
FROM project_manager pm
INNER JOIN dba.project p ON pm.project = p.id
LEFT JOIN dba.contract c ON p.id = c.project
LEFT JOIN dba.contract_line cl ON cl.contract = c.id
LEFT JOIN dba.product pt ON cl.product = pt.id
LEFT JOIN dba.specified_product sp ON sp.product = pt.id
LEFT JOIN dba.frozen_sale fs ON fs.spec_product = sp.id
AND fs.contract = c.id
AND fs.line = cl.idx
LEFT JOIN dba.frozen_sale_split fsp ON fsp.frozen_sale = fs.id
AND fsp.employee = pm.consultant
LEFT JOIN dba.employee e ON fsp.employee = e.person
LEFT JOIN dba.person ps ON fsp.creator = ps.id
WHERE p.id = 50000002735
AND e.NAME IS NOT NULL
) AS t
) TT
)
SELECT
created
, bname
, total_share
, prev.total_share as prev_share
FROM
inp
left join inp as prev on prev.rnum=inp.rnum-1
and prev.bname=inp.bname
WHERE (
prev.total_share IS NULL
OR prev.total_share total_share
)
ORDER BY
created
, bname
I have the following query (as part of a larger query). I am trying to get the sum results from 2 different data sets within a subquery but I am having trouble trying to encapsulate the two into 1 value. What I have is this:
(Select SUM('Invoiced MTD') from
((Select SUM(CASE WHEN SOH.LASDLVNUM_0 <> '' AND SOH.LASINVNUM_0 <> '' AND MONTH(SOH.SHIDAT_0) = MONTH(GETDATE()) THEN
(SOP.NETPRI_0 * SOQ.QTY_0 * SOH.CHGRAT_0) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SORDER SOH
LEFT OUTER JOIN x3v6.CICPROD.BPCUSTOMER BPC on SOH.BPCORD_0 = BPC.BPCNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERQ SOQ on SOH.SOHNUM_0 = SOQ.SOHNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERP SOP on SOQ.SOHNUM_0 = SOP.SOHNUM_0 and SOQ.SOPLIN_0 = SOP.SOPLIN_0 and SOQ.SOQSEQ_0 = SOP.SOPSEQ_0
LEFT OUTER JOIN x3v6.CICPROD.ITMMASTER ITM on SOP.ITMREF_0 = ITM.ITMREF_0 ))
UNION ALL
((Select SUM(CASE WHEN SIH.INVTYP_0 = 2 and MONTH(SIH.ACCDAT_0) = MONTH(GETDATE()) THEN SID.AMTNOTLIN_0 * (-1) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SINVOICE SIH
Left Outer Join x3v6.CICPROD.SINVOICED SID on SIH.NUM_0 = SID.NUM_0))
as 'T2',
But I am getting an error where the UNION ALL clauses is, and I can't figure it out. Basically I want to combine Sales credit memos with the sales order dollar totals from a seperate table.
Can anyone assist me with this?
What about this ?
Select SUM([Invoiced MTD]) from
(
Select SUM(CASE WHEN SOH.LASDLVNUM_0 <> '' AND SOH.LASINVNUM_0 <> '' AND MONTH(SOH.SHIDAT_0) = MONTH(GETDATE())
THEN (SOP.NETPRI_0 * SOQ.QTY_0 * SOH.CHGRAT_0) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SORDER SOH
LEFT OUTER JOIN x3v6.CICPROD.BPCUSTOMER BPC on SOH.BPCORD_0 = BPC.BPCNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERQ SOQ on SOH.SOHNUM_0 = SOQ.SOHNUM_0
LEFT OUTER JOIN x3v6.CICPROD.SORDERP SOP on SOQ.SOHNUM_0 = SOP.SOHNUM_0 and SOQ.SOPLIN_0 = SOP.SOPLIN_0 and SOQ.SOQSEQ_0 = SOP.SOPSEQ_0
LEFT OUTER JOIN x3v6.CICPROD.ITMMASTER ITM on SOP.ITMREF_0 = ITM.ITMREF_0
UNION ALL
Select SUM(CASE WHEN SIH.INVTYP_0 = 2 and MONTH(SIH.ACCDAT_0) = MONTH(GETDATE())
THEN SID.AMTNOTLIN_0 * (-1) ELSE 0 END) as 'Invoiced MTD'
From x3v6.CICPROD.SINVOICE SIH
Left Outer Join x3v6.CICPROD.SINVOICED SID on SIH.NUM_0 = SID.NUM_0
)T
Does this work? I'm not sure exactly what is causing your issue, but you definitely don't need so many parenthesis. I would also recommend using something that formats/ beautifies your SQL. It's a great way to 1) keep your code looking consistent and 2) flesh out syntax errors.
SELECT SUM(x.invoiced_mtd)
FROM (SELECT SUM(CASE
WHEN soh.lasdlvnum_0 <> '' AND soh.lasinvnum_0 <> '' AND
MONTH(soh.shidat_0) = MONTH(getdate()) THEN
(sop.netpri_0 * soq.qty_0 * soh.chgrat_0)
ELSE
0
END) AS invoiced_mtd
FROM x3v6.cicprod.sorder soh
LEFT OUTER JOIN x3v6.cicprod.bpcustomer bpc
ON soh.bpcord_0 = bpc.bpcnum_0
LEFT OUTER JOIN x3v6.cicprod.sorderq soq
ON soh.sohnum_0 = soq.sohnum_0
LEFT OUTER JOIN x3v6.cicprod.sorderp sop
ON soq.sohnum_0 = sop.sohnum_0
AND soq.soplin_0 = sop.soplin_0
AND soq.soqseq_0 = sop.sopseq_0
LEFT OUTER JOIN x3v6.cicprod.itmmaster itm
ON sop.itmref_0 = itm.itmref_0
UNION ALL
SELECT SUM(CASE
WHEN sih.invtyp_0 = 2 AND
MONTH(sih.accdat_0) = MONTH(getdate()) THEN
sid.amtnotlin_0 * (-1)
ELSE
0
END)
FROM x3v6.cicprod.sinvoice sih
LEFT OUTER JOIN x3v6.cicprod.sinvoiced sid
ON sih.num_0 = sid.num_0) x;
Try using a CTE for the UNION query first. Here is a simplified example with the same structure as your query:
;with cteTest AS (
((select 2 as 'test'))
union all
((select 3 as 'test'))
)
select sum(test) from cteTest
The left out join on dbo.SalespersonProject is causing the value for TranAmt to double. I need to sum the legit TranAmt for projects, but adding in the left outer join and SalesPerson02, causes a match an incorrect doubling.
SELECT ARDoc.SlsperId AR_Doc_Sls_ID
, CASE
WHEN ARTran.TranType = 'CM' THEN SUM(ARTran.TranAmt) * -1
ELSE SUM(ARTran.TranAmt)
END TranAmt
, MAX(CASE
WHEN SalesCommOrder = 1 THEN SalesPersonId
END) Salesperson01
, MAX(ISNULL(CASE
WHEN SalesCommOrder = 1 THEN Percentage
END, .03)) Commission01
, MAX(CASE
WHEN SalesCommOrder = 2 THEN SalesPersonId
END) Salesperson02
, MAX(CASE
WHEN SalesCommOrder = 2 THEN Percentage
END) Commission02
, PJPROJ.project PJ_ID
, PJPROJ.project_desc PJ_Description
, PJPROJ.slsperid SME
, ARDoc.CustId Cust_ID
, CASE
WHEN RTRIM(ARTran.InvtId) = 'GRAPHICS' THEN 1
WHEN RTRIM(ARTran.InvtID) = 'SERVICE CONTRACT' THEN 2
END InvtID
, RTRIM(ARDoc.CustId) + ' ' + Customer.BillName Cust_ID_Name
, CONVERT( DATE, ARTran.TranDate, 101) Doc_Date
, ARTran.TranType Doc_Type
, ARTran.RefNbr
, PJPROJ.start_date
, SUM(ARTran.ExtCost) ExtCost
, SUM(ARTran.UnitPrice) UnitPrice
, SUM(ARTran.Qty) Qty
, (
SELECT SUM(b.eac_amount) [Budg Rev]
FROM pjptdsum b
INNER JOIN pjacct a ON a.acct = b.acct
AND a.acct_type = 'RV'
WHERE ARDoc.ProjectID = b.project) Budget_Rev
, (
SELECT SUM(b.eac_amount) [Budg Rev]
FROM pjptdsum b
INNER JOIN pjacct a ON a.acct = b.acct
AND a.acct_type = 'EX'
WHERE ARDoc.ProjectID = b.project) Budget_EAC
, so.TotMerch SalesOrderTotal
, Salesperson.Name
, ARTran.PerPost
, PJPROJ.manager2
, PJEMPLOY.emp_name
FROM Testnewgroundapp.dbo.ARDoc ARDoc
INNER JOIN Testnewgroundapp.dbo.ARTran ARTran ON ARDoc.CustId = ARTran.CustId
AND ARDoc.RefNbr = ARTran.RefNbr
AND ARDoc.DocType = ARTran.TranType
INNER JOIN Testnewgroundapp.dbo.Customer Customer ON ARDoc.CustId = Customer.CustId --INNER JOIN #CustomerTab ct
LEFT OUTER JOIN Testnewgroundapp.dbo.Salesperson Salesperson ON ARDoc.SlsperId = Salesperson.SlsperId
LEFT OUTER JOIN Testnewgroundapp.dbo.PJPROJ PJPROJ ON ARDoc.ProjectID = PJPROJ.project
LEFT OUTER JOIN Testnewgroundapp.dbo.PJEMPLOY PJEMPLOY ON PJPROJ.manager2 = PJEMPLOY.employee
LEFT OUTER JOIN (
SELECT h.PerPost
, h.SlsperID
, SUM(h.TotMerch) TotMerch
FROM SOShipHeader H
GROUP BY h.PerPost
, h.SlsperID) so ON ARTran.PerPost = so.PerPost
AND ARDoc.SlsperId = so.SlsperID
LEFT OUTER JOIN TestCommissions.dbo.SalespersonProject SalespersonProject ON SalespersonProject.ProjectId = PJPROJ.project --AND SalespersonProject.SalesPerson_Id = #ApplicationUserID
LEFT OUTER JOIN TestCommissions.dbo.SalesPerson AppSalesPerson ON AppSalesPerson.Id = SalespersonProject.SalesPerson_Id
WHERE
(ARTran.TranType = 'CM'
AND ARTran.DrCr = 'D'
OR ARTran.DrCr = 'C'
AND
(ARTran.TranType = 'CS'
OR ARTran.TranType = 'DM'
OR ARTran.TranType = 'IN'
)
)
AND ARTran.TaskID NOT LIKE '%60850'
AND ARTRan.TaskID NOT LIKE '%60900'
AND ARTran.invtid <> 'TSCINC001'
AND ARTran.TranClass NOT IN ('F', 'N', 'T')
AND ARTran.Acct NOT IN ('2590', '2040', '2037')
AND CONVERT(INT, ARTran.Acct) > 1301
AND CONVERT(INT, ARTran.PerPost) BETWEEN 201504 AND 201504
AND ARTran.Rlsed = 1
AND PJPROJ.project IS NOT NULL
AND artran.cpnyid IN ('R', 'A')
GROUP BY ARDoc.SlsperId
, ARDoc.ProjectID
, PJPROJ.project
, PJPROJ.project_desc
, PJPROJ.slsperid
, ARDoc.CustId
, ARTran.InvtId
, Customer.BillName
, ARTran.TranDate
, ARTran.TranType
, ARTran.RefNbr
, PJPROJ.start_date
, so.TotMerch
, Salesperson.Name
, ARTran.PerPost
, ARDoc.CpnyID
, PJPROJ.manager2
, PJEMPLOY.emp_name
HAVING ARDoc.SlsperId = 'bpettit'
ORDER BY ARDoc.SlsperId, ARTran.PerPost, PJPROJ.project
If an extra joined table has two records per one main record, this makes each main record appear twice in the result set. The following grouping and summing will then sum each value of the main record or another joined table twice.
Temporarily remove the grouping and summing, but keep all the joins and look at the result set. You will then probably see what causes this doubling.