Create a value adding two columns together - sql

I am attempting to define and new column called End Year that is the calculation of another column plus a number representing number of years. For some reason my script does not recognize the new column called Allocation Year using the excerpt below SQL statement in SQL Server 2008. Note that Contract Year is an existing column that is identified in the non-redacted full script:
,[Allocation Type] =
CASE
WHEN left([contract type] ,1)'1' = THEN 'O&M'
ELSE 'N/A'
END
,[Allocation Year] =
CASE
WHEN [Contract Year]='XXXX' THEN '0'
ELSE CAST ([Contract Year] AS INT)
END
,[End Year] =
CASE
WHEN [Allocation Type]='O&M' THEN [Allocation Year] + 6
END

Columns are named with the AS keyword (which can also be elided in many cases), not with the = operator.
SQL Server does not let you reference other columns or aliases in a SELECT clause - you have to use a subquery:
Like so:
SELECT
*,
CASE WHEN [Allocation Type] = 'O&M'
THEN [Allocation Year Temp] + 6
ELSE NULL
END AS [Allocation Year]
FROM
(
SELECT
CASE WHEN LEFT( [Contract type], 1 ) = '1'
THEN 'O&M'
ELSE 'N/A'
END AS [Allocation Type],
CASE WHEN [Contract Year] = 'XXXX'
THEN '0'
ELSE CAST( [Contract Year] AS int )
END AS [Allocation Year Temp],
*
FROM
....
)

If you want to put everything in one select query, then try this one. Hope this helps. Thanks.
,[End Year] =
CASE
WHEN left([contract type] ,1)='1' THEN
(CASE
WHEN [Contract Year]='XXXX' THEN 6
ELSE (CAST ([Contract Year] AS INT) + 6 )
END)
END

You cannot reference computed columns in the SELECT statement. You'll have to repeat the calculation (or use subqueries like Dai suggested):
,[Allocation Type] =
CASE
WHEN left([contract type] ,1)='1' THEN 'O&M'
ELSE 'N/A'
END
,[Allocation Year] =
CASE
WHEN [Contract Year]='XXXX' THEN 0
ELSE CAST ([Contract Year] AS INT)
END
,[End Year] =
CASE
WHEN left([contract type] ,1)='1' THEN (CASE
WHEN [Contract Year]='XXXX' THEN 0
ELSE CAST ([Contract Year] AS INT)
END) + 6
END

Related

SQL Error with CASE WHEN Error on From when using GETDATE

I have a query that is giving me an error. The error is below. Please help.
The Created Date field is NVARCHAR type. Everything in the dbo.UNIQUE_PARTS_LIST table is NVARCHAR
14 The data types datetime and date are incompatible in the subtract operator.
DECLARE #LookBack60 as FLOAT
Set #LookBack60= -60
select distinct part.Part_Num, part.[Part Description], part.[Part Type],
CASE
WHEN
(cast(Part.[Created Date] as date) <= DATEADD(MONTH,#LookBack60,GETDATE()))
THEN 'Not Needed'
ELSE
(getdate() - cast(Part.[Created Date] as date))
END as 'Intermediate',
CASE
WHEN
(cast(Part.[Created Date] as date) <= DATEADD(MONTH,#LookBack60,GETDATE()))
THEN 'Not Needed'
ELSE
(getdate() - cast(Part.[Created Date] as date)) / (365/12)
END as 'FINAL',
from dbo.UNIQUE_PARTS_LIST part
WHERE part.[Part Type] = 'Consumable'
order by part.Part_Num asc
This is solved. I changed it to DATEDIFF.

Insert into table when the day is Monday

Is there a way in which I can insert data from one table into another when today is Monday?
I tried making something like the below, using CASE WHEN, however it doesn't quite work right, any help would be welcomed
INSERT INTO [dbo].[WF_All]
SELECT (CASE WHEN (DATENAME(WEEKDAY,FLOOR(convert(float,getdate()))))='MONDAY' THEN
(
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
)
ELSE NULL END )
yes , like this :
INSERT INTO [dbo].[WF_All]
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
WHERE DATENAME(WEEKDAY,GETDATE()) = 'Monday'
or
... WHERE DATEPART(WEEKDAY, GETDATE()) = 2 --Monday
Is this what you want.
if datename(weekday,getdate()) = 'MONDAY' then
INSERT INTO [dbo].[WF_All] (
-- column names go here
)
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]

How can I use Sum, Cast and Partition by functions together?

How can I use Sum, Cast and Partition by functions together?
I get error.
Conversion failed when converting the nvarchar value '693.41' to data
type int."
I tried this
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Full query is at the below.
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],[Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
First, identify the rows that have problems. You are converting to an int, so:
select price
from Testing2
where try_convert(int, price) is null and price is not null;
At least some of the values will have decimal points (as in your example). To see if this is the only problem, I would suggest converting to a decimal next:
select price
from Testing2
where try_convert(decimal(20, 4), price) is null and price is not null;
If this returns nothing, you are set. If not, you will need to figure out how to address these exceptions.
Then, I would phrase the calculation using decimals and not floats:
SUM(TRY_CAST([total price] AS DECIMAL(20, 4))) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Monetary amounts should generally be represented using fixed-point values rather than approximate floating point values. The issue with floating point values is that information may be lost. Consider this example with reals:
select cast(1000000 as real) + cast(0.01 as real),
cast(1000000 as decimal(20, 4)) + cast(0.01 as decimal(20, 4))
Integer will not have decimal values, and it will throw an error.
If I use this, similar to the example you have.
Declare #val nvarchar(10) = '10.24'
select cast (#val as int)
I get this following error.
Msg 245, Level 16, State 1, Line 3
Conversion failed when converting the nvarchar value '10.24' to data type int.
Now to avoid this error, I can round the digit to 0 decimal places and convert as Int. Also, I would recommend to use Try_Cast to avoid any cases of actual nvarchar values(it would convert it to null) if you are using sql server 2012 or more.
Declare #val nvarchar(10) = '10.24'
select Try_cast (round(#val,0) as int) as valuen
Output, I think this will work in your sum function.
valuen
10
Why don't you cast it in inner query with decimal(16,9) instead of int
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM([total price]) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],cast([Total Price] as decimal(16,9)) as [Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
If you have a combination of string and number as your column value and you want to sum up the number. For SQL Server 2012+ you can use TRY_CAST or TRY_CONVERT to avoid any casting errors.
TRY_CAST (Transact-SQL)
In your scenario, you are not using proper data type for casting, you have values like 693.41 which can't be casted to INT, instead you should use DECIMAL datatype.
One more suggestion, instead of using NOT LIKE, better use <> in SQL Server like following.
Change
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
to
([Date] <> '0' OR JOB# <> '0' OR [JOB TYPE] <> '0')
One possible solution is to firstly convert the nvarchar value to decimal and then to integer:
CAST(CAST([total price] AS FLOAT) AS INT)
However, in this way the decimal part is lost if it matters to you.

SQL Case statement copying an excel formula

I have an excel report I am trying to convert to an SSRS report using a stored proc. In the existing excel (not written by me) has a formula as follows
=IF( [Date TCY Vacated]="",0,IF([Date TCY Tenanted]="",Summary!$B$3 - ( [Date TCY Vacated]+1), IF( ( [Date TCY Tenanted] -1)- ( [Date TCY Vacated] +1) <0,0, ( [Date TCY Tenanted] -1)- ( [Date TCY Vacated] +1) ) ))
I am trying to convert this into a sql case statement.
I'm expecting this to be an INT so I can sum the column up to get total days vacant from the property
Case When [Date TCY Vacated] Is Null Then '0'
else case when [Date TCY Tenanted] = '' then #End - ([Date TCY Vacated]+1)
else case when ([Date TCY Tenanted] - 1) - ([Date TCY Vacated] +1) < 0 then 0
else Convert(Varchar(30),[Date TCY Tenanted],120) - Convert(Varchar(30),[Date TCY Vacated],120) end end end as 'Void Days'
Tried that but not working, I'm trying to add sample data but unsure how. All fields are date fields, expected results would be 2018-02-14 - 2018-02-12 = 2 (days).
I think the reason you are having problems is that you are using standard mathematical operators to work with dates.
The below example is based on your provided samples with some tweaks to use date functions instead. It may not perfectly reflect your desired outcome but hopefully will take you most of the way there:
CREATE TABLE #a ([Date TCY Vacated] DATE, [Date TCY Tenanted] DATE)
INSERT INTO #a ([Date TCY Vacated], [Date TCY Tenanted])
VALUES ('2018-02-10', '2018-02-08')
,(NULL, '2018-02-08')
,('2018-02-10', NULL)
,('2018-02-10', '2018-02-28')
DECLARE #End DATE = GETDATE()
SELECT *,
CASE WHEN [Date TCY Vacated] IS NULL
THEN 0
ELSE CASE WHEN [Date TCY Tenanted] IS NULL
THEN DATEDIFF(d, #End, DATEADD(d, 1, [Date TCY Vacated]))
ELSE CASE WHEN DATEADD(d, -1, [Date TCY Tenanted]) < DATEADD(d, 1, [Date TCY Vacated])
THEN 0
ELSE DATEDIFF(d, DATEADD(d, -1, [Date TCY Tenanted]), DATEADD(d, 1, [Date TCY Vacated]))
END
END
END
FROM #a
In particular this code uses DATEADD and DATEDIFF instead of '+' and '-' to ensure all operations occur in days.
Not a Case statement, but a SQL version of your Excel function. It should work in SSRS
Declare #tcyv Int = 1
Declare #tcyt Int = ''
Declare #summ Int = 300
Select iif(#tcyv = '', 0,
iif(#tcyt = '', #summ - (#tcyv+1),
iif(((#tcyt-1) - (#tcyv+1)) < 0, 0,
(#tcyt-1) - (#tcyv+1)))) As x
With the CASE statement:
Select Case When #tcyv = '' Then 0
When #tcyt = '' Then #summ - (#tcyv+1)
When((#tcyt-1) - (#tcyv+1)) < 0 Then 0
Else (#tcyt-1) - (#tcyv+1) End As x
Result:
298

Multiple Case Statements return Different Columns

Problem: I am doing multiple case statments, however it returns only as one column. I would like multiple columns returned.
Current Code
declare #currentweek as nvarchar(10)
declare #1stweek as nvarchar(10)
declare #2ndweek as nvarchar(10)
set #currentweek= convert(varchar(10),dateadd(ww,0,GETDATE()),110)
set #1stweek= convert(varchar(10),dateadd(ww,1,GETDATE()),110)
select
case
when [date] < #currentweek then 'R'
when [date] > #currentweek and [date]<#1stweek then 'R'
else null
end [current week],[first week]
What I am trying to see is multiple columns. If the condition is met then the value R will be placed in either the [first week] or [current week] column.
Thanks
You need to do two different Case statements - one for each column:
select case when [date] < #currentweek then 'R'
else null
end as [current week],
case when [date] > #currentweek
and [date] < #1stweek then 'R'
else null
end as [first week]