Adding a number to a datetime to get new date SQL Server - sql

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

Related

SQL create column for every week (Loop?)

I need to make a report for weekly changes.
This is the code for todays amount
SELECT
[Entry No_],
[Customer No_],
[Posting Date],
[Description],
[Currency Code],
Trans_type = case when [Deposit]=1 then 'Deposit'
when [Imprest]=1 then 'Imprest'
else 'Other' end,
A.Amount
FROM Table1
LEFT JOIN
(
SELECT Distinct [Cust_ Ledger Entry No_],
SUM ([Amount EUR]) as 'amount'
FROM Table2
group by [Cust_ Ledger Entry No_]
having
SUM ([Amount EUR]) <> '0'
)A
on [Entry No_] = A.[Cust_ Ledger Entry No_]
Where
A.Amount is not NULL
Code to generate data for previous week is here (adding only where clause):
SELECT
[Entry No_],
[Customer No_],
[Posting Date],
[Description],
[Currency Code],
Trans_type = case when [Deposit]=1 then 'Deposit'
when [Imprest]=1 then 'Imprest'
else 'Other' end,
A.Amount
FROM Table1
LEFT JOIN
(
SELECT Distinct [Cust_ Ledger Entry No_],
SUM ([Amount EUR]) as 'amount'
FROM Table2
where [posting Date] < '2020-11-23'
group by [Cust_ Ledger Entry No_]
having
SUM ([Amount EUR]) <> '0'
)A
on [Entry No_] = A.[Cust_ Ledger Entry No_]
Where
A.Amount is not NULL
It would be enough to union both queries and then export to Excel and make pivot, but problem is that I need results of last 50 weeks. Is there any smart way to avoid union 50 tables and run one simple code to generate weekly report?
Thanks
it might be easier with sample, but I don't know how to paste table here..
Maybe it is true, i dont need union here, and group by would be enough, but it stills sounds difficult for me :)
Ok. Lets say table has such headers: Project | Country | date | amount
The code below returns amount for todays date
Select
Project,
SUM(amount)
From Table
Group by Project
I actually need todays date and also the results of previous weeks (What was the result on November 22 (week 47), November 15 (week 46) and so on.. total 50 weeks from todays date).
Code for previous week amount is here:
Select
Project,
SUM(amount)
From Table
Where Date < '2020.11.23'
Group by Project
So my idea was to create create 50 codes and join the results together, but i am sure it is a better way to do this. Besides i dont want to edit this query every week and add a new date for it.
So any ideas, to make my life easier?
if I have understood your requirement correctly, all you need to do is extract the week from the date e.g.
Select
Project,
datepart(week, date),
SUM(amount)
From Table
Where Date < '2020.11.23'
Group by Project, datepart(week, date)

How to select max date over the year function

I am trying to select the max date over the year, but it is not working. Any ideas on what to do?
SELECT a.tkinit [TK ID],
YEAR(a.tkeffdate) [Rate Year],
max(a.tkeffdate) [Max Date],
tkrt03 [Standard Rate]
FROM stageElite.dbo.timerate a
join stageElite.dbo.timekeep b ON b.tkinit = a.tkinit
WHERE a.tkinit = '02672'
and tkeffdate BETWEEN '2014-01-01' and '12-31-2014'
GROUP BY a.tkinit,
tkrt03,
a.tkeffdate
Perhaps you only want it by year and not rolled up by calendar date. For SQL server you can try this.
SELECT
…
MaxDate = MAX(a.tkeffdate) OVER (PARTITION BY a.tkinit, YEAR(a.tkeffdate)))
…
Or you could modify the query above to group by the year instead of date-->
GROUP BY a.tkinit,
tkrt03,
YEAR(a.tkeffdate)
You seem to want only one row and all the columns. Use ORDER BY and TOP:
SELECT TOP (1) tr.tkinit as [TK ID],
YEAR(tr.tkeffdate) as [Rate Year],
a.tkeffdate as [Max Date],
tkrt03 as [Standard Rate]
FROM stageElite.dbo.timerate tr JOIN
stageElite.dbo.timekeep tk
ON tk.tkinit = tr.tkinit
WHERE tr.tkinit = '02672' AND
tr.tkeffdate >= '2014-01-01' AND
tr.tkeffdate < '2015-01-01'
ORDER tr.tkeffdate DESC;
Note that I also fixed your date comparisons and table aliases.

Merge two SQL data tables in asp.net website using vb.net in code behind

I can't seem to find a solution that fits.
Here is the situation. I have a two SQL queries from the same table each with a different where clause.
Table A uses this SQL statement:
Select jo.AssemblySeq As Assm,
jo.OprSeq As [OP Center #],
jo.WCCode As WC,
Convert(Varchar, jo.DueDate, 101) As [Due Date],
ja.RequiredQty As Qty,
jo.QtyCompleted As [Qty Comp],
jo.OpComplete As OpComplete
From JobOper jo
Join JobAsmbl ja
On jo.JobNum = ja.JobNum
And jo.AssemblySeq = ja.AssemblySeq
Where jo.JobNum Like '236087.%'
And ja.AssemblySeq <> 0
Order By jo.AssemblySeq;
And returns this data:
Table B uses this SQL query:
Select jo.AssemblySeq As Assm,
jo.OprSeq As [OP Center #],
jo.WCCode As WC,
Convert(Varchar, jo.DueDate, 101) As [Due Date],
jo.QtyPer As QTY,
jo.QtyCompleted As [Qty Comp],
jo.OpComplete As OpComplete
From JobOper jo
Join JobAsmbl ja
On jo.JobNum = ja.JobNum
And jo.AssemblySeq = ja.AssemblySeq
Where jo.JobNum Like '236087.%'
And ja.AssemblySeq = 0
Order By jo.AssemblySeq;
And returns this data:
What I need to do is merge these two tables so that I have columns called Assm, OP Center #, WC, Due Date, Qty, Qty Completed, OpComplete. My problem is that the where clause for the query for table A has ja.AssemblySeq <> 0 and the where clause for the query for table B has ja.AssemblySeq = 0.
I need all the lines from both queries. I am not sure if I need some type of Join or if it would involve sub queries?
A simple UNION ALL will help as below:
Select * from Query1
Union All
Select * from Query2
You don't need to do a UNION ALL at all. You can do this with one single query, without the need to hit the table twice.
Your queries are identical with the exception of the column selected based on the value of ja.AssemblySeq. You can just remove the WHERE clause altogether and make the Qty column a CASE expression.
Select jo.AssemblySeq As Assm,
jo.OprSeq As [OP Center #],
jo.WCCode As WC,
Convert(Varchar, jo.DueDate, 101) As [Due Date],
Case When ja.AssemblySeq = 0
Then jo.QtyPer
Else ja.RequiredQty
End As Qty,
jo.QtyCompleted As [Qty Comp],
jo.OpComplete As OpComplete
From JobOper jo
Join JobAsmbl ja
On jo.JobNum = ja.JobNum
And jo.AssemblySeq = ja.AssemblySeq
Where jo.JobNum Like '236087.%'
Order By jo.AssemblySeq;

Subquery returned more than 1 rows inside case statement

I have been working on a query whereby in a subquery I am selecting the column Cust_Status under certain conditions.
select distinct
C.Cust_Code [Cust #],
C.Cust_Start_Date [Start Date],
C.Cust_End_date [End Date],
(select
Cust_Status = (case
when cast(CUST_UPDATE_DATE_LT as DATE) = cast('2017-01-23 00:00:00' as Date)
then 'V'
when cast(CUST_UPDATE_DATE_LT as DATE) = cast('2017-01-22 00:00:00' as Date)
then 'I'
end)
from tblCustomers) [Cust Status],
M.Machine_ID,
M.Machine_Location
from
tblCustomers C
inner join
tblMachine M on C.Cust_Mach_Pkey = M.Pkey
When I run this query I get an error
subquery returned more than 1 value error.
When I remove the subquery inside case, it's fine. But I am sure there is only 1 record present for both date conditions. So not sure how my subquery returning more than 1 values. Please enlighten me.
I am guessing that you just want to compare the latest date. If so, there are much simpler ways:
select C.Cust_Code as [Cust #], C.Cust_Start_Date as [Start Date],
C.Cust_End_date as [End Date],
(case when max(cast(CUST_UPDATE_DATE_LT as DATE)) = '2017-01-23'
then 'V'
when max(cast(CUST_UPDATE_DATE_LT as DATE)) = '2017-01-22'
then 'I'
end) as Cust_status
M.Machine_ID,
M.Machine_Location
from tblCustomers C inner join
tblMachine M
on C.Cust_Mach_Pkey = M.Pkey
group by C.Cust_Code, C.Cust_Start_Date, C.Cust_End_date,
M.Machine_ID, M.Machine_Location

How to get the desired from the SQL Server Query

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