I have a query that I build that pulls back data from multiple tables for a particular location, particular appointment types in a schedule for a particular date range. In the data that is returned, I am pulling the provider of the service, the member who is getting the service and a number of fields that describe things about the member or service appointment. The information will be grouped by the provider. So you will have multiple members/client records per provider for that period.
What I am now being asked to do is to take those results and pull only the latest appointment for those results.
My code is as follows:
SELECT SCSERVICES.servicecode, SCSERVICES.servicename, SCSESSIONS.scheduleid, SCSERVICES.servicetype, SCSERVICECATEGORIES.servicecategory,
SCSCHEDULES.scheduledatefrom, MEMBERS.lname, MEMBERS.fname, SCSCHEDULES.timestart, SCSCHEDULES.schedulestatus,
CASE WHEN MEMBERS.phone1label = '4' THEN MEMBERS.phone1 WHEN MEMBERS.phone2label = '4' THEN MEMBERS.phone2 WHEN MEMBERS.phone3label = '4'
THEN MEMBERS.phone3 WHEN MEMBERS.phone4label = '4' THEN MEMBERS.phone4 END AS MobilePhone, MEMBERS.scancode,
EMPLOYEES.fname AS trainfname, EMPLOYEES.lname AS trainlname, MEMBERS.lastvisit
FROM SCSESSIONS INNER JOIN
SCSERVICES ON SCSESSIONS.serviceid = SCSERVICES.serviceid INNER JOIN
SCSERVICECATEGORIES ON SCSERVICES.servicecategoryid = SCSERVICECATEGORIES.servicecategoryid INNER JOIN
SCSCHEDULES ON SCSESSIONS.scheduleid = SCSCHEDULES.scheduleid INNER JOIN
MEMBERS ON SCSCHEDULES.memid = MEMBERS.memid INNER JOIN
SCSESSION_PROVIDERS ON SCSESSIONS.sessionid = SCSESSION_PROVIDERS.sessionid INNER JOIN
EMPLOYEES ON SCSESSION_PROVIDERS.employeeid = EMPLOYEES.employeeid
WHERE (SCSERVICECATEGORIES.servicecategory = 'Trainers' OR
SCSERVICECATEGORIES.servicecategory = 'Pilates' OR
SCSERVICECATEGORIES.servicecategory = 'Specialty') AND (SCSERVICES.siteid = #rvSite) AND (CAST(SCSCHEDULES.scheduledatefrom AS DATE) BETWEEN
#rvSessionDate AND #rvSessionDateEnd) AND (SCSCHEDULES.schedulestatus = '1') AND (SCSERVICES.servicecode <> 'BREAK')
Results look something like this:
you can use row_number function for that
( for latest scheduledatefrom for a member)
select * from (
SELECT SCSERVICES.servicecode
, SCSERVICES.servicename
, SCSESSIONS.scheduleid
, SCSERVICES.servicetype
, SCSERVICECATEGORIES.servicecategory
, SCSCHEDULES.scheduledatefrom
, MEMBERS.lname
, MEMBERS.fname
, SCSCHEDULES.timestart
, SCSCHEDULES.schedulestatus
, CASE
WHEN MEMBERS.phone1label = '4'
THEN MEMBERS.phone1
WHEN MEMBERS.phone2label = '4'
THEN MEMBERS.phone2
WHEN MEMBERS.phone3label = '4'
THEN MEMBERS.phone3
WHEN MEMBERS.phone4label = '4'
THEN MEMBERS.phone4
END AS MobilePhone
, MEMBERS.scancode
, EMPLOYEES.fname AS trainfname
, EMPLOYEES.lname AS trainlname
, MEMBERS.lastvisit
, row_number() over ( partition by MEMBERS.memid order by SCSCHEDULES.scheduledatefrom desc) rowid
FROM SCSESSIONS
INNER JOIN SCSERVICES
ON SCSESSIONS.serviceid = SCSERVICES.serviceid
INNER JOIN SCSERVICECATEGORIES
ON SCSERVICES.servicecategoryid = SCSERVICECATEGORIES.servicecategoryid
INNER JOIN SCSCHEDULES
ON SCSESSIONS.scheduleid = SCSCHEDULES.scheduleid
INNER JOIN MEMBERS
ON SCSCHEDULES.memid = MEMBERS.memid
INNER JOIN SCSESSION_PROVIDERS
ON SCSESSIONS.sessionid = SCSESSION_PROVIDERS.sessionid
INNER JOIN EMPLOYEES
ON SCSESSION_PROVIDERS.employeeid = EMPLOYEES.employeeid
WHERE (
SCSERVICECATEGORIES.servicecategory = 'Trainers'
OR SCSERVICECATEGORIES.servicecategory = 'Pilates'
OR SCSERVICECATEGORIES.servicecategory = 'Specialty'
)
AND (SCSERVICES.siteid = #rvSite)
AND (
CAST(SCSCHEDULES.scheduledatefrom AS DATE) BETWEEN #rvSessionDate
AND #rvSessionDateEnd
)
AND (SCSCHEDULES.schedulestatus = '1')
AND (SCSERVICES.servicecode <> 'BREAK')
) x
where rowid = 1
Related
i have query below
SELECT #RoleUser = MR.Code FROM MasterRole MR INNER JOIN MasterUsersRole MUR ON MR.Id = MUR.RoleId
INNER JOIN MasterUsers MU ON Mu.UserCode = MUR.UserCode
WHERE MU.UserCode = #UserLoginID
select 1 Num
, MyHistory.ID
, MyHistory.RequestNumber
, MyHistory.FlowID
, MyHistory.FlowProcessStatusID
from
(
select *
from Requests R
inner join
(
--DECLARE #UserLoginID nvarchar(200) = 'dum.testing.3'
select distinct
RequestID
from dbo.RequestTrackingHistory RTH
where IIF(#UserLoginID = 'admin', #UserLoginID, RTH.CreatedBy) = #UserLoginID
OR ( CreatedBy IN
SELECT Mu.UserCode from MasterUsers MU
INNER JOIN MasterUsersRole MUR ON MU.UserCode = MUR.UserCode
INNER JOIN MasterRole MR ON MUR.RoleId = MR.Id
WHERE MR.Code = #RoleUser
)
)
) RT on R.ID = RT.RequestID
) as MyHistory
inner join MasterFlow F on MyHistory.FlowID = F.ID
inner join
(
select FP.ID
, FP.Name
, FP.AssignType
, FP.AssignTo
, FP.IsStart
, case FP.AssignType
when 'GROUP' then
G.Name
end as 'AssignToName'
from MasterFlowProcess FP
left join dbo.MasterRole G on FP.AssignTo = G.ID and FP.AssignType = 'GROUP'
) FP on MyHistory.FlowProcessID = FP.ID
inner join MasterFlowProcessStatus FPS on MyHistory.FlowProcessStatusID = FPS.ID
left join MasterFlowProcessStatusNext FPSN on FPS.ID = FPSN.ProcessStatusFlowID
left join MasterFlowProcess FPN on FPSN.NextProcessFlowID = FPN.ID
left JOIN MasterRole MR ON MR.Id = FPN.AssignTo
left join MasterUsersRole MUR on MR.Id = MUR.RoleId
left join MasterUsers MURO on MUR.UserCode = MURO.UserCode
inner join MasterUsers UC on MyHistory.CreatedBy = UC.UserCode
left join MasterUsers UU on MyHistory.UpdatedBy = UU.UserCode
LEFT JOIN RequestMT RMT ON MyHistory.ID = RMT.RequestID
LEFT JOIN RequestGT RGT ON MyHistory.ID = RGT.RequestID
left join (SELECT sum(QtyCU) countQty , RequestId from dbo.RequestGTDetail where IsActive = 1 group by RequestId) RGTD on RGTD.RequestId = RGT.RequestId
left join (SELECT sum(QtyPCS) countQty , RequestId from dbo.RequestMTDetail where IsActive = 1 group by RequestId) RMTD on RMTD.RequestId = RMT.RequestId
left join (SELECT COUNT(IIF(returnable = 0, returnable, null)) countReturnable , RequestId from dbo.RequestMTDetail group by RequestId) RMTR on RMTR.RequestId = RMT.RequestId
left JOIN dbo.MasterDistributor md ON md.Code = RGT.CustId or md.Code = RMT.CustId
left JOIN dbo.MasterUsersDistributor MUD ON MUD.UserCode = MURO.UserCode AND md.Code = MUD.DistributorCode
LEFT JOIN dbo.MasterReason MRMT ON RMT.ReasonId = MRMT.Id
LEFT JOIN dbo.MasterReason MRGT ON RGT.ReasonId = MRGT.Id
LEFT JOIN dbo.MasterDistributorGroup MDG ON MDG.Id = MD.GroupId
OUTER APPLY dbo.FnGetHistoryApproveDate(MyHistory.Id) AS x
where REPLACE(FPS.Name, '#Requestor', uc.Name) <> 'DRAFT'
AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
i want to add some logic in where clause
this line
==> AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
it depend on the #RoleUser variable, if #RoleUser IN ('A','B') then where clause above is executed, but if #RoleUser Not IN ('A','B') where clause not executed
i,m trying this where clause
AND IIF(#RoleUser IN ('A','B'), MUD.DistributorCode, #RoleUser) IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = IIF(#RoleUser IN ('A','B'), #UserLoginID, NULL))
it didn't work, only executed if #RoleUser IS ('A','B') other than that it return 0 record
any help or advice is really appreciated
thank you
The cleanest way I'm implemented these kind of crazy rules is a
holderTable
and a countVariable against the holder table.
I'll give a generic examples.
This is a "approach" and "philosophy", not a specific answer....with complex WHERE clauses.
DECLARE #customerCountryCount int
DECLARE #customerCountry TABLE ( CountryName varchar(15) )
if ( "the moon is blue on tuesday" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Honduras" UNION ALL SELECT "Malaysia"
END
if ( "favorite color = green" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Greenland" UNION ALL SELECT "Peru"
END
SELECT #customerCountryCount = COUNT(*) FROM #customerCountry
Select * from dbo.Customers c
WHERE
(#customerCountryCount = 0)
OR
( exists (select null from #customerCountry innerVariableTable where UPPER(innerVariableTable.CountryName) = UPPER(c.Country) ))
)
This way, instead of putting all the "twisted logic" in an overly complex WHERE statement..... you have "separation of concerns"...
Your inserts into #customerCountry are separated from your use of #customerCountry.
And you have the #customerCountryCount "trick" to distinguish when nothing was used.
You can add a #customerCountryNotExists table as well, and code it to where not exists.
As a side note, you may want to try using a #temp table (instead of a #variabletable (#customerCountry above)... and performance test these 2 options.
There is no "single answer". You have to "try it out".
And many many variables go into #temp table performance (from a sql-server SETUP, not "how you code a stored procedure". That is way outside the scope of this question.
Here is a SOF link to "safe" #temp table usage.
Temporary table in SQL server causing ' There is already an object named' error
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 want to select only the first record from each group. So basically I only want the data for first processing date column and don't want the rest of the date for each product.
My current code as below
SELECT
C.AccountID as ABN_ACC ,
C.ProductSymbol,
C.ProductShortName,
S.ReactorProduct AS REC_PROD,
C.CurrencyCode AS PROD_CCY,
C.CountryOfPayment AS PAYCONTRY,
C.DividendValueCur AS PAYCCY,
C.DividendValue AS DIV_AMNT,
CONCAT ((IIF (C.QuantitySettledNoTax_LS = 'S' ,(-1*C.QuantitySettledNoTax),C.QuantitySettledNoTax )),(IIF(C.QuantitySettledTax_LS = 'S',(-1*C.QuantitySettledTax),QuantitySettledTax))) AS DIVQTY ,
C.ExdividendDate AS EXDATE,
C.Recorddate AS RECDATE,
C.DividendPayDate AS PAYDATE
From "LiquidCDW". [Staging].[CA_CorporateActions] AS C
RIGHT JOIN "LiquidCDW".[Staging].[POS_SettledPositions] AS P ON C.Recorddate = P.ProcessingDate AND C.AccountID = p.AccountID AND C.ProductSymbol = P.ProductSymbol AND C.DividendValueCur = P.CurrencyCode
INNER JOIN "LiquidCDW".[Transformation].[Mapping_Product_ABNReactor] AS S ON C.ProductSymbol = S.ReactorProduct AND S.ValidTo IS NULL AND S.ProductType = 'E' AND c.DividendValueCur = S.Currency
where C.ExdividendDate >= '20210201'
ORDER by C.ProductSymbol , C.CurrencyCode
One approach uses ROW_NUMBER:
WITH cte AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY C.ProductSymbol ORDER BY processingDate) rn,
C.AccountID AS ABN_ACC,
C.ProductSymbol,
C.ProductShortName,
S.ReactorProduct AS REC_PROD,
C.CurrencyCode AS PROD_CCY,
C.CountryOfPayment AS PAYCONTRY,
C.DividendValueCur AS PAYCCY,
C.DividendValue AS DIV_AMNT,
CONCAT((IIF(C.QuantitySettledNoTax_LS = 'S',
(-1*C.QuantitySettledNoTax), C.QuantitySettledNoTax)),
(IIF(C.QuantitySettledTax_LS = 'S',
(-1*C.QuantitySettledTax),QuantitySettledTax))) AS DIVQTY,
C.ExdividendDate AS EXDATE,
C.Recorddate AS RECDATE,
C.DividendPayDate AS PAYDATE
FROM [LiquidCDW].[Staging].[CA_CorporateActions] AS C
RIGHT JOIN "LiquidCDW".[Staging].[POS_SettledPositions] AS P
ON C.Recorddate = P.ProcessingDate AND
C.AccountID = p.AccountID AND
C.ProductSymbol = P.ProductSymbol AND
C.DividendValueCur = P.CurrencyCode
INNER JOIN [LiquidCDW].[Transformation].[Mapping_Product_ABNReactor] AS S
ON C.ProductSymbol = S.ReactorProduct AND
S.ValidTo IS NULL AND
S.ProductType = 'E' AND
C.DividendValueCur = S.Currency
WHERE
C.ExdividendDate >= '20210201'
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY ProductSymbol, CurrencyCode;
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..
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.