The below query is my query I have written to generate Weekly Status Report.
In that the Upper parts of the query above 'Union' gives the Overall Status of each BU Name and Product Name.
The other parts of the query gives the detailed analysis of the Overall Status, It gives the results of each project and name of each engineer working on it.
The below query gives me complete results in the database from the beginning till date.
But when the user chooses the date, I want results only from that date till date. Because it is a weekly report.
I want few more column data in the Results like number of parts completed last week and number of parts completed by each engineer this week.
And whenever I add some thing in the code, I get a error to add the column name in group by and I am not getting the desired results if I add it.
From the given from date - 7 days count of parts which are completed.
And by including the above things, the overall status number should match with individual ones
like (+ of all individual = Overall)
select BU.bu_desc as [BU], prod.Product_Desc as [Product Name], NULL as [SC-ID],
'OVERALL PROJECT STATUS' as [Project Name],
NULL as [Requestor], NULL as [Request Date],
case
when BU.bu_desc in ('DSM','Synexis','ALD') then 'GW'
when BU.bu_desc in ('Etch','SRP','FEP') then 'MS'
when BU.bu_desc in ('CMP','MDP') then 'RS'
else 'PT'
end as [PM],
NULL as [SCE],
(count(parts.part_id_num)-count(parts.cancelled_date)) as [Total Parts Requested],
'' as [No. Of Parts Completed Last Week],
'' as [No. Of Parts Completed This Week],
count(parts.analysis_Complete_date) as [Total No.Of Parts Completed],
case
when (((count(parts.part_id_num)-count(parts.cancelled_date))-(count(parts.analysis_Complete_date)))=0) then 100
when ((count(parts.analysis_Complete_date))=0) then 0
else
((count(parts.analysis_Complete_date)*100)/(count(parts.part_id_num)-
count(parts.cancelled_date)))
end as [SC Analysis Completed (%)],
NULL as [Request Completion Date],
NULL as [Committed Date],
NULL as Notes
from scn_project_details as proj
left join scn_part_details as parts on proj.project_id=parts.project_id
left join SCN_BU bu on bu.bu_id=proj.bu_id
left join dbo.SCN_Product_Name prod on prod.Product_Id=proj.Product_Id
where proj.status_id<>12 and (proj.analysis_complete_date between '2014-12-10' and getdate()
or proj.status_id between 4 and 8) and parts.sc_id is not null
group by BU.bu_desc,prod.Product_Desc
union
select BU.bu_desc as [BU], prod.Product_Desc as [Product Name], proj.project_id as [SC-ID],
proj.project_name as [Project Name],usr1.fname+' '+usr1.lname as [Requestor],
proj.created_date as [Request Date],left(proj.pm_id,2) as [PM],
usr2.fname+' '+usr2.lname as [SCE],
(count(parts.part_id_num)-count(parts.cancelled_date)) as [Total Parts Requested],
'' as [No. Of Parts Completed Last Week],
'' as [No. Of Parts Completed This Week],
count(parts.analysis_Complete_date) as [Total No.Of Parts Completed],
case
when (((count(parts.part_id_num)-count(parts.cancelled_date))-(count(parts.analysis_Complete_date)))=0) then 100
when ((count(parts.analysis_Complete_date))=0) then 0
else
((count(parts.analysis_Complete_date)*100)/(count(parts.part_id_num)- count(parts.cancelled_date)))
end as [SC Analysis Completed (%)],
proj.project_completition_date as [Request Completion Date],
proj.original_commit_date as [Committed Date],
NULL as Notes
from scn_project_details as proj
left join scn_part_details as parts on proj.project_id=parts.project_id
left join SCN_users usr1 on proj.created_by=usr1.[user_id]
left join SCN_users usr2 on parts.sc_id=usr2.[user_id]
left join SCN_BU bu on bu.bu_id=proj.bu_id
left join dbo.SCN_Product_Name prod on prod.Product_Id=proj.Product_Id
where proj.status_id<>12 and (proj.analysis_complete_date between '2014-12-10' and getdate()
or proj.status_id between 4 and 8) and parts.sc_id is not null
group by BU.bu_desc,prod.Product_Desc,proj.project_id,proj.project_name,usr1.fname+' '+usr1.lname, proj.created_date,proj.project_completition_date,proj.original_commit_date,
proj.pm_id,usr2.fname+' '+usr2.lname,proj.analysis_complete_date
How can I get the count of parts which are analysed last week and the ones which are done this week.
I want the count for each row in the result, not the total.
(select count(parts1.analysis_Complete_date) from scn_part_details as parts1
where parts1.analysis_Complete_date between '2014-12-10' and getdate()
) as [No. Of Parts Completed Last Week],
(select count(parts1.analysis_Complete_date) from scn_part_details as parts1
where parts1.analysis_Complete_date between '2014-12-01' and '2014-12-09'
) as [No. Of Parts Completed This Week],
This code when included in the query gives me the total count in each row. like 125 in all the rows. But I want individual count.
You can put the whole query into brackets and use SELECT WHERE to apply additional filter conditions, order by etc.
SELECT x.* -- choose fields
FROM (
-- The whole working query comes here
) as x
WHERE x.[Request Completion Date]>'20141201' -- filter
Better create table valued function or view from your basic query for code re-usability.
I finally achieved it by creating a stored procedure and the explanation of it goes as below.
Created a temp table with data and [No. Of Parts Completed Last Week], [No. Of Parts Completed This Week] columns as NULL. And then wrote a update statement to get the count and updated the records. Finally selected the data from the temp table and loaded it in datatable.
Create PROCEDURE [dbo].[SCN_SP_SCE_Weekly_Report]
#startdate as datetime
AS
BEGIN
SET NOCOUNT ON;
declare #date datetime
declare #LastWeekStart datetime
declare #LastWeekEnd datetime
declare #ThisWeekStart datetime
declare #ThisWeekEnd datetime
set #date=(select dateadd(w, -7, #startdate))
set #LastWeekStart=(SELECT DATEADD(DAY, 1 - DATEPART(WEEKDAY, #date), CAST(#date AS DateTime)))
set #LastWeekEnd=(DATEADD(DAY, 7 - DATEPART(WEEKDAY, #date), CAST(#date AS DateTime)))
set #ThisWeekStart=(SELECT DATEADD(DAY, 1 - DATEPART(WEEKDAY, #startdate), CAST(#startdate AS DateTime)))
set #ThisWeekEnd=(DATEADD(DAY, 7 - DATEPART(WEEKDAY, #startdate), CAST(#startdate AS DateTime)))
select * into #a from(
select BU.bu_desc as [BU], prod.Product_Desc as [Product Name], NULL as [SC-ID],
'OVERALL PROJECT STATUS' as [Project Name],'' as [Requestor], NULL as [Request Date],
case
when BU.bu_desc in ('DSM','Synexis','ALD') then 'GW'
when BU.bu_desc in ('Etch','SRP','FEP') then 'MS'
when BU.bu_desc in ('CMP','MDP') then 'RS'
else 'PT'
end as [PM],
'' as [SCE],
(count(parts.part_id_num)-count(parts.cancelled_date)) as [Total Parts Requested],
null as [No. Of Parts Completed Last Week],
null as [No. Of Parts Completed This Week],
count(parts.analysis_Complete_date) as [Total No.Of Parts Completed],
case
when (((count(parts.part_id_num)-count(parts.cancelled_date))-(count(parts.analysis_Complete_date)))=0) then 100
when ((count(parts.analysis_Complete_date))=0) then 0
else
((count(parts.analysis_Complete_date)*100)/(count(parts.part_id_num)-count(parts.cancelled_date)))
end as [SC Analysis Completed (%)],NULL as [Requested Completion Date],
NULL as [Committed Date],NULL as Notes,'' as sc_id
from scn_project_details as proj
left join scn_part_details as parts on proj.project_id=parts.project_id
left join SCN_BU bu on bu.bu_id=proj.bu_id
left join dbo.SCN_Product_Name prod on prod.Product_Id=proj.Product_Id
where proj.status_id<>12 and (proj.analysis_complete_date between #startdate and getdate()
or (proj.status_id >= 4 and proj.status_id < 8)) and parts.sc_id is not null
group by BU.bu_desc,prod.Product_Desc
union
select BU.bu_desc as [BU], prod.Product_Desc as [Product Name], proj.project_id as [SC-ID],
proj.project_name as [Project Name],usr1.fname+' '+usr1.lname as [Requestor],
proj.created_date as [Request Date],left(proj.pm_id,2) as [PM],usr2.fname+' '+usr2.lname as [SCE],
(count(parts.part_id_num)-count(parts.cancelled_date)) as [Total Parts Requested],
null as [No. Of Parts Completed Last Week],
null as [No. Of Parts Completed This Week],
count(parts.analysis_Complete_date) as [Total No.Of Parts Completed],
case
when (((count(parts.part_id_num)-count(parts.cancelled_date))-(count(parts.analysis_Complete_date)))=0) then 100
when ((count(parts.analysis_Complete_date))=0) then 0
else
((count(parts.analysis_Complete_date)*100)/(count(parts.part_id_num)-count(parts.cancelled_date)))
end as [SC Analysis Completed (%)],
proj.project_completition_date as [Requested Completion Date],
proj.original_commit_date as [Committed Date],
NULL as Notes,parts.sc_id as sc_id
from scn_project_details as proj
join scn_part_details as parts on proj.project_id=parts.project_id and parts.sc_id is not null
left join SCN_users usr1 on proj.created_by=usr1.[user_id]
left join SCN_users usr2 on parts.sc_id=usr2.[user_id]
left join SCN_BU bu on bu.bu_id=proj.bu_id
left join dbo.SCN_Product_Name prod on prod.Product_Id=proj.Product_Id
where proj.status_id<>12 and (proj.analysis_complete_date between #startdate and getdate()
or (proj.status_id >= 4 and proj.status_id < 8)) and parts.sc_id is not null
group by BU.bu_desc,prod.Product_Desc,proj.project_id,proj.project_name,usr1.fname+' '+usr1.lname,
proj.created_date,proj.project_completition_date,proj.original_commit_date,
proj.pm_id,usr2.fname+' '+usr2.lname,proj.analysis_complete_date,parts.sc_id ) as t
update a
set a.[No. Of Parts Completed Last Week]=c.cnt
from #a a, (
select count(b.sc_id) as cnt,b.project_id,b.sc_id
from scn_part_details as b
where b.analysis_complete_date between #LastWeekStart and #LastWeekEnd
group by b.project_id,b.sc_id) as c
where a.[SC-ID]=c.project_id
and a.sc_id=c.sc_id
update a
set a.[No. Of Parts Completed This Week]=c.cnt
from #a a, (
select count(b.sc_id) as cnt,b.project_id,b.sc_id
from scn_part_details as b
where b.analysis_complete_date between #ThisWeekStart and #ThisWeekEnd
group by b.project_id,b.sc_id) as c
where a.[SC-ID]=c.project_id
and a.sc_id=c.sc_id
select BU,[Product Name],[SC-ID],[Project Name],Requestor,[Request Date],PM,SCE,
[Total Parts Requested],[No. Of Parts Completed Last Week],[No. Of Parts Completed This Week],
[Total No.Of Parts Completed], [SC Analysis Completed (%)],[Requested Completion Date],
[Committed Date],Notes
from #a
End
GO
Related
I get this error:
Msg 245, Level 16, State 1, Line 5
Conversion failed when converting the nvarchar value 'L NOVAK ENTERPRISES, INC' to data type int.
I've been wrestling with this query for quite a while and just can't figure out in what place that the conversion is being attempted. Using SQL Server 2017.
DECLARE #StartDate AS DateTime
DECLARE #MfgGroupCode AS Varchar(20)
SET #StartDate='2/27/2020'
SET #MfgGroupCode = 'VOLVO_NLA'
SELECT DISTCINT
CT.No_ AS [Contact Number],
CT.Name AS [Contact Name],
UAL.Time AS [Search Date],
UAL.Param1 AS [Search Part],
CT.[E-Mail] AS [Contact Email],
CT.[Phone No_] AS [Contact Phone],
CT.[Company Name] AS [Search By Customer],
(SELECT C.Name
FROM dbo.[Customer] C
WHERE C.No_ = SL.[Sell-to Customer No_]
AND C.Name <> '') AS [Sold To Customer],
SL.[Posting Date] AS [Invoice Date],
SL.[Document No_] AS [Invoice],
SL.Quantity AS [Quantity],
SL.[Unit Price] AS [Unit Price],
SL.Amount AS [Amount],
DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) AS [Interval]
FROM
dbo.[User Action Log] UAL
JOIN
dbo.[User Action Types] UAT ON UAL.[User Action ID] = UAT.ID
JOIN
dbo.[Item] I ON UAL.Param1 = I.[OEM Part Number]
JOIN
dbo.[Contact] CT ON UAL.[Contact No_] = CT.No_
LEFT OUTER JOIN
dbo.[Sales Invoice Line] SL ON UAL.Param1 = SL.[OEM Part Number]
AND SL.[Posting Date] >= #StartDate
WHERE
UAT.Name IN ('SinglePartSearch', 'MultiPartSearch')
AND UAL.[MFG Group Code] = #MfgGroupCode
AND UAL.Time >= #StartDate
AND UAL.Param3 > 0
-- AND DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) < 0 -- Uncomment to see Current Searches with Past Orders
-- AND DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) > -1 -- Uncomment to see Searches resulting in Future Order
AND DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) IS NULL -- Uncomment to See Searches with no Order
ORDER BY
Interval DESC
Thanks to all of your help and questioning, I was able to identify that the culprit is UAL.Param3.
The User Action Log table stores a variety of different "Actions" and the parameters that are affiliated with each type of action (param1, param2, param3). For one action "RequestForAccess", the "L NOVAK" value is perfectly acceptable. For this query, we're looking at the "SinglePartSearch" and "MultiPartSearch" actions, which will only contain numeric values in UAL.Param3
I replaced this line (AND UAL.Param3 > 0) with (AND ISNUMERIC(UAL.Param3) = 1 AND UAL.Param3 <> 0) in the Where clause and it is now returning the results I hoped for.
Let me know if there is a more correct way of doing this and thank you to all who contributed!
I am running SQL Server 2008 R2 (RTM).
I have a SQL query that pulls Dates, Products, Customers and Units:
select
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset
where [Transaction Date] < '2019-03-01' and [Transaction Date] >= '2016-01-01'
group by [Transaction Date], [SKU], [Customer Name]
order by [Transaction Date]
This pulls hundreds of thousands of records and I wanted to determine if a certain transaction was a new order or reorder based on the following logic:
Reorder: That specific Customer has ordered that specific product in the last 6 months
New Order: That specific Customer hasn’t ordered that specific product in the last 6 months
For that I have this formula in Excel that seems to be working:
=IF(COUNTIFS(A$1:A1,">="&DATE(YEAR(A2),MONTH(A2)-6,DAY(A2)),C$1:C1,C2,B$1:B1,B2),"Reorder","New Order")
The formula works when I paste it individually or in a smaller dataset, but when I try to copy paste it to all 500K+ rows, Excel gives up because it loops for each calculation.
This could probably be done in SQL, but I don’t have the knowledge on how to convert this excel formula to SQL, I just started studying it.
You're doing pretty well with the start of your query there. There are three additional functions you're looking to add to your query.
The first thing you'll need is the easiest. GETDATE() simply returns the current date. You'll need that when you're comparing the current date to the transaction date.
The second function is DATEDIFF, which will give you a unit of time between two dates (months, days, years, quarters, etc). Using DATEDIFF, you can say "is this date within the last 6 months". The format for this is pretty easy. It's DATEDIFF(interval, date1, date2).
The thrid function you're looking for is CASE, which allows you to tell SQL to give you one answer if one condition is met, but a different answer if a different condition is met. For your example, you can say "if the difference in days is < 60, return 'Reorder', if not give me 'New Order'".
Putting it all together:
SELECT CASE
WHEN DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 6
THEN 'Reorder'
ELSE 'New Order'
END as ORDER_TYPE
,[Transaction Date] AS DATE
,[SKU] AS PRODUCT
,[Customer Name] AS CUSTOMER
,Qty AS UNITS
FROM DATASET
For additonal examples on CASE, take a look at this site: https://www.w3schools.com/sql/sql_ref_case.asp
For additional examples on DATEDIFF, take a look here: See the
following webpage for examples and a chance to try it out:
https://www.w3schools.com/sql/func_sqlserver_datediff.asp
SELECT CASE
WHEN Datediff(day, [transaction date], Getdate()) <= 180 THEN 'reorder'
ELSE 'Neworder'
END,
[transaction date] AS Date,
[sku] AS Product,
[customer name] AS Customer,
qty AS Units
FROM datase
If I understand correctly, you want to peak at the previous date and make a comparison. This suggests lag():
select (case when lag([Transaction Date]) over (partition by SKU, [Customer Name] order by [Transaction Date]) >
dateadd(month, -6, [Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset d
group by [Transaction Date], [SKU], [Customer Name];
EDIT:
In SQL Server 2008, you can emulate the LAG() using OUTER APPLY:
select (case when dprev.[Transaction Date] >
dateadd(month, -6, d.[Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
d.[Transaction Date] as Date,
d.[SKU] as Product,
d.[Customer Name] as Customer,
sum(d.Qty) as Units
from dataset d outer apply
(select top (1) dprev.*
from dataset dprev
where dprev.SKU = d.SKU and
dprev.[Customer Name] = d.[Customer Name] and
dprev.[Transaction Date] < d.[Transaction Date]
order by dprev.[Transaction Date] desc
) dprev
group by d.[Transaction Date], d.[SKU], d.[Customer Name];
I want to make a waterfall chart (in a reporting app) that shows the additions and resolutions of tasks based on their Opened At and Resolved At timestamps
I have a database on MSSQL Server 2016 that contains a "task" table:
SELECT [SysID], [Opened At], [Resolved At]
FROM task
ORDER BY [Opened At] ASC;
SysID Opened At Resolved At
9086c6254f3d578070a1afee0310c79a 2018-04-30 23:53:25.000 2018-05-01 00:57:46.000
7c86c6254f3d578070a1afee0310c7c8 2018-04-30 23:53:27.000 2018-05-01 01:05:22.000
9d8606254f3d578070a1afee0310c7a9 2018-04-30 23:53:29.000 2018-05-01 01:05:42.000
f986c6254f3d578070a1afee0310c783 2018-04-30 23:53:31.000 2018-05-01 01:14:22.000
45c312e94ffd5780a35d87501310c775 2018-05-01 00:51:22.000 2018-05-01 04:11:48.000
A task is considered "active" if it has an "Opened At" timestamp without a "Resolved At" timestamp. Tasks are not always marked resolved within the day they are opened, so I want to see how many get left over at the end of each day.
I would like to end up with this SQL result, that shows the difference in active tickets at the end of each day:
Date Created Opened Count Closed Count Difference
27/10/2017 17 5 12
28/10/2017 11 13 -2
29/10/2017 10 9 1
30/10/2017 17 12 5
31/10/2017 17 20 -3
1/11/2017 23 19 4
2/11/2017 19 25 -6
3/11/2017 13 30 -17
My current query is
SELECT * FROM (
SELECT
CONVERT(VARCHAR(10), task.[Opened At], 126) AS [Date Opened],
SUM(CASE WHEN [Opened At] IS NOT NULL THEN 1 ELSE 0 END) AS [Opened Count]
FROM task GROUP BY CONVERT(VARCHAR(10), task.[Opened At], 126)
UNION ALL
SELECT CONVERT(VARCHAR(10), task.[Resolved At], 126) AS [Date Resolved],
SUM(CASE WHEN [Resolved At] IS NOT NULL THEN 1 ELSE 0 END) AS [Resolved Count]
FROM task GROUP BY CONVERT(VARCHAR(10), task.[Resolved At], 126)
) t
However, it only ever returns the Date Opened and Opened Count columns. The Opened Count column has incorrect data in it. The query works fine if I just do the single select of Opened At or Closed At without the UNION. The difference should just be Closed Count - Opened Count.
Since a ticket needs to be open before it can be resolved, I want to base the date off the Opened At column.
I've had a look at a number of posts describing the subquery technique used above, but I can't work out why it's not returning the other column. I've explored COUNT(*) OVER (ORDER BY... ) but it all the examples I've seen are for tables where there are distinct events per row. (bank account with debits and credits is a common one, which doesn't match this structure which is more an update to the row to change what the query is counting).
Can anyone help me out with this?
You will just need to group by date. A simple modification in your script will do the trick
SELECT [Date Created]
,sum([Opened Count]) [Opened Count]
,sum([Resolved Count]) [Resolved Count]
,sum([Resolved Count]) - sum([Opened Count]) DifferenceCount
FROM (
SELECT CONVERT(VARCHAR(10), task.[Opened At], 126) AS [Date Created]
,count(*) AS [Opened Count]
,0 [Resolved Count]
FROM task
GROUP BY CONVERT(VARCHAR(10), task.[Opened At], 126)
UNION ALL
SELECT CONVERT(VARCHAR(10), task.[Resolved At], 126) AS [Date Created]
,0 [Opened Count]
,count(*) AS [Opened Count] AS [Resolved Count]
FROM task
GROUP BY CONVERT(VARCHAR(10), task.[Resolved At], 126)
) t
GROUP BY [Date Created]
If I understand correctly, you are looking at isolated days:
how many tasks got opened that day
how many tasks got resolved that day
You are not intersted in how many tasks are actually open at the end of a day (for which we'd have to add up all unresolved tasks opened that day or before).
So it's merely a full outer join of opened tasks per day with resolved tasks per day:
select
coalesce(opened.dt, closed.dt) as day,
coalesce(opened.cnt, 0) as opened_count,
coalesce(resolved.cnt, 0) as resolved_count,
coalesce(opened.cnt, 0) - coalesce(resolved.cnt, 0) as diff
from
(
select convert(date, [Opened At]) as dt, count(*) as cnt
from task
group by convert(date, [Opened At])
) opened
full outer join
(
select convert(date, [Resolved At]) as dt, count(*) as cnt
from task
group by convert(date, [Resolved At])
) resolved on resolved.dt = opened.dt
order by day;
I would go for a full join between the opened and resolved.
But with an additional twist.
Add a Total for those that were opened and resolved on the same day.
Because, if you really want to know how many were resolved on the same day as they were opened?
Then just comparing the opened and closed totals would be misleading.
For example if you have only the tupples ([Opened At],[Resolved At]):
('2018-01-01','2018-01-02'), ('2018-01-02','2018-01-01')
Then on both 'Created At' days the TotalOpened = 1 and TotalClosed = 1, and Diff = 0
Since Diff = 0, one could assume that there were none that got resolved on another day.
But in reality, neither of the 2 tupples were opened and closed on the same day.
Example Snippet:
declare #task table (id int identity(1,1), [Opened At] datetime, [Resolved At] datetime);
insert into #task ([Opened At], [Resolved At]) values
(GetDate()-1.1, GetDate()-1)
,(GetDate()-2, GetDate()-1)
,(GetDate()-3, GetDate()-2)
,(GetDate()-5, GetDate()-4)
;
select
coalesce([OpenedDate],[ClosedDate]) as [Created At],
isnull(TotalOpened,0) as [Opened Count],
isnull(TotalClosed,0) as [Closed Count],
isnull(TotalOpened,0) - isnull(TotalClosed,0) as [Difference],
isnull(TotalSameDayClosure,0) as [SameDayClosure Count]
from
(
select
convert(date,[Opened At]) as [OpenedDate],
count(*) as TotalOpened,
count(case when [Resolved At] is not null and convert(date,[Opened At]) = convert(date,[Resolved At]) then 1 end) as TotalSameDayClosure
from #task
group by convert(date,[Opened At])
) Opened
full join
(
select convert(date,[Resolved At]) as [ClosedDate], count(*) as TotalClosed
from #task
group by convert(date,[Resolved At])
) Closed
on Opened.[OpenedDate] = Closed.[ClosedDate];
I am trying to get the query below to assign a number value to the column 'DESIRED TRANSIT TIME' based on the value in that column - 10 if it starts with A and 5 if it starts with C. From there I want to add that number to REVISED_EX_FACTORY to get a new ex factory. I have never attempted this and using the query below I get the result which is the date plus the text 'DESIRED TRANSIT TIME' - which kind of makes sense since it is a string. How can I get the value in the column instead of the textual name of the column in line 20? I was told converting the datetime values to get rid of the time component was a good way to go.
The ideal result would be to either add 5 or 10 days to the date depending the value in 'DESIRED TRANSIT TIME'
SQL:
USE PDX_SAP_USER
GO
SELECT E.team_member_name [EMPLOYEE],
K.business_segment_desc [BUSINESS SEGMENT],
G.order_status [GPS ORDER STATUS],
H.po_type [PO TYPE],
G.order_no [GPS ORDER NO],
I.po_number [SAP PO NUMBER],
I.shipping_instruct [SAP SHIP MODE],
G.shipping_type [GPS SHIP MODE],
CASE
WHEN I.shipping_instruct LIKE 'A%'
THEN '10'
WHEN I.shipping_instruct LIKE 'C%'
THEN '5'
END [DESIRED TRANSIT TIME],
CONVERT(VARCHAR(12),I.revised_ex_factory,101) [LAST CONFIRMED DATE ],
CONVERT(VARCHAR(12),I.revised_ex_factory,101) + 'DESIRED TRANSIT TIME' AS 'PROPOSED ETA',
CONVERT(VARCHAR(12),S.po_estimated_deliv_date,101) [CURRENT DELIV DATE],
-- 'days_diff'
I.material [MATERIAL],
M.description [DESCRIPTION],
I.stock_category [STOCK CATEGORY],
I.po_ordered_quantity [PO ORDERED QUANTITY],
I.po_recvd_quantity [PO RECVD QUANTITY],
I.po_balance_quantity [PO BALANCE QUANTITY],
I.po_intransit_quantity [PO INTRANSIT QUANTITY],
I.plant_code [PLANT],
I.direct_ship_code [DS CODE],
I.comment [COMMENT]
FROM (SELECT order_no,
order_status,
shipping_type
FROM asagdwpdx_prod.dbo.SimoxOrder1
UNION ALL
SELECT order_no,
order_status,
shipping_type
FROM asagdwpdx_prod.dbo.SimoxOrder2
UNION ALL
SELECT order_no,
order_status,
shipping_type
FROM asagdwpdx_prod.dbo.SimoxOrder3) G
JOIN pdx_sap_user..vw_po_header H ON G.order_no = H.ahag_number
JOIN pdx_sap_user..vw_po_item I ON H.po_number = I.po_number
JOIN pdx_sap_user..vw_po_size S ON I.po_number = S.po_number
AND I.po_item_number = S.po_item_number
JOIN pdx_sap_user..vw_mm_material M ON I.material = M.material
JOIN pdx_sap_user..vw_kd_business_segment K ON M.business_segment_code = K.business_segment_code
JOIN adi_user_maintained..scm_po_employee_name E ON I.po_number = E.po_number
WHERE I.po_balance_quantity > 0
AND I.del_indicator NOT IN ('L','S')
AND H.PO_TYPE NOT IN ('01','UB')
AND I.shipping_instruct IN ('A1','A2','A5','C1','C2','C3')
SAMPLE RESULT:
04/30/2016DESIRED TRANSIT TIME
So you have two options. The first is to duplicate the CASE statement you have a second time, and concatenate that with the date. That's probably the most straight forward, although you will end up duplicating that code. It's a small duplication, but one none the less. If that bothers you, or you need to use it elsewhere in your query as well, you will need to wrap the whole thing in a subquery so you can reference the case statement as though it were a distinct column. e.g.
select
...
DesiredTransitTime =
case
when I.shipping_instruct LIKE 'A%'
then '10'
when I.shipping_instruct LIKE 'C%'
then '5'
end,
ProposedETA = convert(varchar(12),I.revised_ex_factory,101) +
case
when I.shipping_instruct LIKE 'A%'
then '10'
when I.shipping_instruct LIKE 'C%'
then '5'
end
...
or
select
[DESIRED TRANSIT TIME],
[PROPOSED ETA = StringDate + [DESIRED TRANSIT TIME]
...
from
(
select
StringDate = convert(varchar(12), I.revised_ex_factory,101) ,
[DESIRED TRANSIT TIME] =
case
when I.shipping_instruct LIKE 'A%'
then '10'
when I.shipping_instruct LIKE 'C%'
then '5'
end,
...
) a
I have this query in my ssis package and I would like to add a constraint where if the data is more than 4 days old to not add it, how would I add that into this?
SELECT PTA,
Part,
Duns,
YearStart AS BlanketYear,
VIPDoc,
DID,
STATUS = CASE
WHEN STATUS IS NULL
THEN 'Eligible'
ELSE STATUS
END,
[PRTCOMACERT STATUS] AS TMSStatus,
SupplierHTS1 AS HTS,
PrefCrit,
Producer,
NetCost,
CoCountry AS Country,
TracedValue,
Currency,
MaCountry,
VEH,
ENG,
KitPercent,
DateCreated,
DATEDIFF(d, DateCreated, GetDate()) AS AGE
FROM [SourceTempFCA].[dbo].[FCAStatus] g
INNER JOIN [SourceTempFCA].[dbo].[NEW35COMA] t ON g.part = t.PART#PART#
AND g.duns = t.[PRTCOMASUPPLIER #]
AND g.yearstart = t.[PRTCOMAEXP DATE Year]
AND g.VIPDoc = t.[PRTCOMADOC #]
--delete from [SourceTempFCA].[dbo].[FCAStatus]
This is just a SELECT statement so I'm assuming you mean to filter out those rows? Then just do
WHERE DATEDIFF(d, DateCreated, GetDate()) > 4