Casting a String Column to 3 Digit scale in Hive Query Language - sql

I have a select statement as follows
SELECT t5.Name AS ProductName
, CAST (t5.salerevenue AS DECIMAL(20,3)) AS Revenue
, CASE WHEN t5.PreviousRevenue <> 0 THEN CAST(t5.PresentRevenue/t5.PreviousRevenue*100 AS STRING)
ELSE 'NA'
END AS RevenueTrend
I want to cast the RevenueTrend as a decimal with maximum 3 point scale (20.123)
I have to cast it as String because WHEN t5.PreviousRevenue <> 0 is not met I have to show it as 'NA'
I tried doing it as follows
CASE WHEN t5.PreviousRevenue <> 0 THEN CAST((CAST(t5.PresentRevenue/t5.PreviousRevenue*100) AS DECIMAL(20,3)) AS STRING)
ELSE 'NA'
END AS RevenueTrend
but I am getting a syntax error.
The revenue part is projected as expected. I want the revenuetrend part also to be projected like revenue. Is there any way to achieve this?

Try converting first to a decimal, then to a string:
SELECT . . .
(CASE WHEN t5.PreviousRevenue <> 0
THEN CAST(CAST(t5.PresentRevenue/t5.PreviousRevenue*100 AS DECIMAL(20,3)) as string)
ELSE 'N/A'
END) AS RevenueTrend

Related

SQL Select Case Conversion failed when converting the varchar value to data type int

With the help of case statement, I would like to get the result as "Non Revenue" in Geodept column where the value is 0
Simple case statement - (gives conversion error)
case when GeoDeptId = 0 then 'Non Revenue' else GeoDeptId end
So tried as below but getting value as 0 again
convert(int, case when IsNumeric(convert(int, rd.GeoDeptId ))= 0 then convert (varchar(14),'Non Revenue') else rd.GeoDeptId
end ),
So tried as below but getting value as 0 again
convert(int, case when IsNumeric(convert(int, rd.GeoDeptId ))= 0 then convert (varchar(14),'Non Revenue') else rd.GeoDeptId
end )
Cast the GeoDeptId to text:
CASE WHEN GeoDeptId = 0 THEN 'Non Revenue' ELSE CAST(GeoDeptId AS varchar(max)) END
The source of your error is that all branches of a CASE expression must have the same type. Since it is not possible for 'Non Revenue' to be cast to an integer, therefore we can convert the GeoDeptId to text.

SPARK SQL CASE WHEN > 0

I have been struggling with this for about 3 hours.
Running Spark 1.6
Trying to get this to work in the spark SQl context. evt_acct_app_id is an integer, why is this not working, in sql this is easy. I tried multiple variations of this, remove apostrophe and etc.
CASE evt_acct_app_id
WHEN evt_acct_app_id > '0' THEN '001'
ELSE '002'
END
AS EVNT_SUBTYPE_CD,
Keep getting this error:Got this unknown exception:
org.apache.spark.sql.AnalysisException: cannot resolve 'CASE evt_acct_app_id WHEN (cast(evt_acct_app_id as double) > cast(0 as double)) THEN 001 ELSE 002'
due to data type mismatch: key and WHEN expressions should all be same type or coercible to a common type;
Don't use single quotes if you are comparing to an integer:
(CASE WHEN evt_acct_app_id > 0 THEN '001'
ELSE '002'
END) as EVNT_SUBTYPE_CD,
In addition, when you have expressions for comparison, the correct syntax for CASE does not have a column name after the CASE.
Try below:
CASE
WHEN evt_acct_app_id > '0' THEN '001'
ELSE '002'
END
AS EVNT_SUBTYPE_CD,
Try this:
def evtChange(d:Column) = {when(d > 0,"001").otherwise("002")}
data.select( evtChange($"evt_acct_app_id").as("EVNT_SUBTYPE_CD") )

How to round this result in SQL SELECT statement

I need a method to round the result returned from the following statement:
CASE
WHEN 0 <> (sod.XDFFLT - sod.DUEQTY)
THEN (sod.XDFFLT - sod.DUEQTY)
ELSE ''
END AS Balance
Which resides in this SELECT statement.
SELECT TOP (10000) som.ORDNUM
,som.NAME
,som.ADDR1
,som.ADDR2
,som.CITY
,som.STATE
,som.ZIPCD
,som.CNTRY
,som.CUSTPO
,COALESCE(cpd.CUSTPRT, sod.PRTNUM) AS CustomerSku
,cpd.CUSTPRT
,som.CUSTID
,sod.PRTNUM
,ps.PMDES1
,sod.CURQTY
,sod.DUEQTY
,sod.XDFFLT
,sod.SHPQTY
,CASE
WHEN 0 <> (sod.XDFFLT - sod.DUEQTY)
THEN (sod.XDFFLT - sod.DUEQTY)
ELSE ''
END AS Balance
,sod.LINNUM + sod.DELNUM AS LineDelNum
,CASE
WHEN 12 <= len(sod.UDFREF)
THEN substring(sod.UDFREF, 9, 4)
ELSE sod.UDFREF
END AS Skid
Replace the CASE with this:
,CASE
WHEN 0 <> (sod.XDFFLT - sod.DUEQTY)
THEN ROUND((sod.XDFFLT - sod.DUEQTY), <number_of_decimals>)
ELSE NULL
END AS Balance
Make sure to replace the <number_of_decimlas> with the appropriate number of decimals you want the number to be rounded to.
greater than 0 will return a number which is rounded on the right side of the comma (decimal point)
less than 0 will return a number which is rounded on the left side of the comma (decimal point)
Also, don't use a blank string in the ELSE clause of your case since this will cause a datatype missmatch and generate an error (a CASE must return a single datatype). Hence, it is better to replace this with NULL, since your first condition will always return a number.

SQL Server : ignore strings in SUM function

I do a sum function over a column. But the column can have string values also. I want SQL Server to ignore the string values and sum only the string values.
Eg: column can have values like 16000Euro or 2588, or 3671.
The input is from user and I cant change validation in the app to integer
I have tried this but still shows error:
SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1
THEN Summe
ELSE 0
END) AS total_Euro
So how can I ignore the string values when doing sum operation?
The error I get is:
Error converting nvarchar value '2588. 'in the int data type.
EDIT: I want SQL to ignore such string values and sum what it can.. The main aim is that Query should not throw any error
Try the below Query, it will work perfectly :)
SELECT SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe + '.0e0') = 1
THEN Summe
ELSE 0
END) AS total_Euro FROM TableName
IsNumeric returns 1 if the varchar value can be converted to ANY number type (includes int, bigint, decimal, numeric, real & float) Values like 1e4,1., 2.0 will create the issue if the above check to bypass these values is not added.
You should not name column same as a keyword in SQL Server , if this cannot be avoided you can escape column name by enclosing in square bracketes [Sum] as shown below
SELECT SUM(CASE WHEN Type = 202 AND ISNUMERIC([Sum]) = 1 THEN [Sum] ELSE 0 END) AS total_Euro
Try this
SUM(CASE WHEN Type = 202 AND case when Sum not like '%[^0-9]%' THEN Sum END ELSE 0 END) AS total_Euro
or
SUM(CASE WHEN Type = 202 AND ISNUMERIC(Sum+'.e0') = 1 THEN Sum ELSE 0 END) AS total_Euro
Try this:
SUM (CASE
WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1 THEN CAST(summe AS DECIMAL(9,2))
ELSE 0 END) AS TotalEuro
I don't know if you do this SUM for one column or what, but also you can filter out what you need and then sum:
SELECT SUM(Summe) AS total_Euro
FROM someTable
WHERE Type_New = 202 AND ISNUMERIC(Summe) = 1
ISNUMERIC function considers strings that contain large numeric (e.g., 9223372036854775808), decimals (e.g., 12.4), currency figures (e.g., $123), and floating-point values (e.g., 1E2) to be strings that can be converted to a numeric data type.
Now to calculate Sum you will have to convert string to an integer[ this assumption is based on
sample data you have posted] but fact is string can be numeric but might not be convertible to an integer; the ISNUMERIC function is limited in the sense that it can tell you only whether the string can be converted to any numeric data type.
So if your column doesn't have string data like 1E3 or 12.4 or $123 which are numeric but not integers you can simply cast the target column to int as below and calculate the sum :
select SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1
THEN CAST(Summe AS INT)
ELSE 0
END) AS total_Euro
FROM test
else you shoudl go for a more generic function which as discussed here..
http://sqlmag.com/t-sql/can-i-convert-string-integer

SQL Server: casting the column datatype

SQL Server 2005/ 2008
I have kept a CASE condition for a SQL query which results Float /Numeric Value. One of the CASE condition is to say N/A. I kept the piece of code.
For column : Compliance - Possible values could be N/A,100.0,99.1 ... ( nvarchar, float ).
select
x.MemberName, x.DOB, x.FilePath,
x.Medication, x.NDC, x.Directions,
x.Name, x.Strength, x.GenericName,
x.QtyOrdered, x.DaysSupply, x.DateFilled,
CASE WHEN x.test = 0 THEN 'N/A'
WHEN compliance > 100.0 THEN '100.0'
ELSE CAST(FLOOR(compliance * 10)/10.0 AS DECIMAL(3, 1))
END AS [Compliance]
Above syntax spills error as ..
Msg 8114, Level 16, State 5, Line 10
Error converting data type varchar to numeric.
How should I type cast the field ?
CASE is an expression that returns a single result and regardless of the path it always needs to result in the same data type (or implicitly convertible to the same data type). Try:
...
CASE
WHEN x.test = 0 THEN 'N/A'
WHEN compliance > 100.0 THEN '100.0'
ELSE CONVERT(VARCHAR(5), CAST(FLOOR(compliance *10)/10.0 AS DECIMAL(3,1)))
END AS as [Compliance];
You're not consistent in your CASE statement - you need to provide the same data type as result for all options.
CASE WHEN x.test = 0 THEN 'N/A'
WHEN compliance > 100.0 THEN '100.0'
ELSE CAST(FLOOR(compliance * 10)/10.0 AS DECIMAL(3, 1))
END AS [Compliance]
Since the first two options return a string ('N/A' or '100.0'), your last option also must return a string value:
CASE WHEN x.test = 0 THEN 'N/A'
WHEN compliance > 100.0 THEN '100.0'
ELSE CAST(CAST(FLOOR(compliance * 10)/10.0 AS DECIMAL(3, 1)) AS VARCHAR(20))
END AS [Compliance]