select, avg statement not working - sql-server

I have a table called Employee with about 17 different columns on it. One of those columns is called age. I am suppose to write up a statement that will get the average age of all the employees with an AS in the statement. Here is the statement I have written up and unfortunately I continue to get an error message. Also, I am new at this so please don't beat me to hard...lol.
SELECT AVG(Age) AS Average_Age FROM Employee
I get below error..
msg 8117, state 16, line 1 invalid syntax for operand avg.
I believe the message is telling me that the avg is trying to calculate, but cannot do it.
Why did I see this done on a youtube video and it work perfectly for the person who created it? While I did the same exact statement I got it wrong...can someone explain that?
Update as Per comments:
Error Message:
Operand data type varchar is invalid for avg operator.

If age is a varchar column you can try
SELECT AVG(cast(Age as int)) AS Average_Age FROM Employee
( but you may want to think about changing the datatype )

Related

SQL compilation error: syntax error line 1 at position 8 unexpected '-'

I am getting the SQL compilation error: syntax error line 1 at position 8 unexpected '-'.
sql query is :
INSERT INTO table_name(col_names) values();
position 8 is I of "INTO"
I am stuck with this tried searching the character from notepad++, but couldn't find.
You example of "it breaks" need to be reproducible. So you need to paste you not-working code (which is clear you don't want to) or toy sql that has the problem. It should look like:
create table toy_example(col_names text);
-- this works yippie!
insert into toy_example(col_names) values ('this is a value');
-- but this
insert into toy_example(col_names) values ();
/*
Syntax error: unexpected ')'. (line 22)
*/
because as it stands:
I have some SQL it gives me a error
002020 (21S01): SQL compilation error:
Insert value list does not match column list expecting 3 but got 1
my code looks like:
SELECT 1;
cannot really be worked with.
From your toy example your list of columns doesn't match the number of columns in your values clause. You're trying to insert 0 values into some number of columns.
You need something like
INSERT INTO table_name(col_1, col_2, col_3) values(1, 'hello', 'world');
I'm getting a similar, less than helpful error when I try something similar to your code. I think the parser is simply not able to comprehend a values clause with no input, so it's not even managing to figure out where the issue is, and it's just giving a generic "there's something wrong with your insert" error.
Thanks, #David Garrison and #Simeon Pilgrim for the time you put into answering my question.
The cause of my error was: I was using a Postgres data type: INTERVAL in my subquery with hyphen in it.
select CAST((DATE_TRUNC('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY') AS -
DATE
so , snowflake was not compatible with the hyphen above, but it was not showing the error in the correct line number while compiling the SQL instead it was showing the error in the first line INSERT INTO as explained in my question.(I think its a bug in snowflake)
So to make it compatible in snowflake , I used :
select CAST(LAST_DAY((DATE_TRUNC('MONTH', CURRENT_DATE))) AS DATE);
INTERVAL will work in snowflake but without hyphen, that is : INTERVAL '30 DAYS',
but this is not fair with the month of February, so I used LAST_DAY function.
and the query went fine :D

Error converting data type when using multiple WHERE statements

I have a SQL query that works fine when the WHERE statement contains only one statement, but not when it contains both statements at the same time. When I use both WHERE statements, I get "Error converting data type to varchar to numeric." (The error is occurring in the second SELECT statement, not in the CTE).
This code is what I want:
;WITH cte_1 as(
SELECT EVENT_ID
,CLIENT_ID
,convert(varchar(10), E.STARTDATE, 101) as R106_DATE
FROM SCEVENT
WHERE STARTDATE>='06/01/2016' AND STARTDATE<='06/30/2016'
and SVC_ID=106
)
SELECT R.*
,convert(varchar(10), S.BEG_DATE, 101) as SVC_DATE
,S.UNIT_ID
FROM cte_1 R
JOIN CDCLSVC S
on R.CLIENT_ID=S.CLIENT_ID
WHERE R106_DATE<=BEG_DATE
and UNIT_ID=251
If I include one or the other WHERE statements, it works fine. But if I have both of those statements, I get an error.
(The desired result is a list of people who had a service at unit 251 after they had a service code (SVC_ID) 106.)
Thoughts?
I changed the code so that it's not converting the date until after the match (excellent point, #JonathanShields) but I kept getting the error message.
I ended up changing my date range to a longer period of time, and suddenly it worked. I guess there were no records in the given time frame that met both criteria, but instead of returning a result of 0 records it gave me the error message.
Thanks for everyone's help.

how to check for a null value in t-sql

I want to check for a value in a table to see if it's null.
If so, I just want output to be '0.000'; otherwise, I'd like the actual value which must be converted to a varchar field.
The definition of the column in the database is decimal(10,3).
When I run my below query (pertinent part of the query), I get an error message:
Error converting data type varchar to numeric.
Here is my t-sql syntax that is getting the error. How do I correct it?
isnull(nullif(Ryder_Price,'0.000'),convert(varchar(max),Ryder_Price))
EDIT
Here is the full SELECT statement:
Select '4'+','
+','+Case when Country_Code= 1 then 'USA' else 'CAN' End
+','+
+','+isnull(nullif(Ryder_Price,'0.000'),convert(varchar(max),Ryder_Price))
+','+isnull(nullif(Ryder_Price,'0.000'),convert(varchar(max),Ryder_Price))
+','+isnull(nullif(Ryder_Price,'0.000'),convert(varchar(max),Ryder_Price))
+','+
+','+'01/01/1900'
+','+'01/01/2099'PartMaster_String
,4 ord,part_no
, RIGHT('000'+convert(varchar(3),ATA_SYSCode),3)+'-'+RIGHT('000'+convert(varchar(3),ATA_Asmcode),3)+'-'+RIGHT('000'+convert(varchar(3),ATA_Partcode),3) taskstring
From tbl_CPM_PARTS_MASTER_PTC
The reason for the error message is that it is possible for the line you posted to simply have Ryder_Price as a value, which is a decimal type. And then you are trying to concatenate it to a string.
To acheive your stated goal:
I want to check for a value in a table to see if it's null.
If so, I just want output to be '0.000'; otherwise, I'd like the
actual value which must be converted to a varchar field.
Try this:
convert(varchar(max),isnull(Ryder_Price,'0.000'))

"Adding a value to a 'datetime' column caused an overflow."

In the MSDN is clearly said that:
The date argument cannot be incremented to a value outside the range of its data type. In the following statements, the number value that is added to the date value exceeds the range of the date data type. The following error message is returned: "Adding a value to a 'datetime' column caused overflow."
And the example:
SELECT DATEADD(year,2147483647, '2006-07-31');
SELECT DATEADD(year,-2147483647, '2006-07-31');
which causes the error:
"Adding a value to a 'datetime' column caused overflow."
This seem right. But why I get the same error executing this SQL statement:
SELECT DATEDIFF(YY,'1013-12-12',DATEADD(YY,-300,getdate()))
more specific and only:
SELECT DATEADD(YY,-300,getdate())
First google result for 'sql datetime range'. January 1, 1753. That's your lower bound.
A comment on the question added this trivia about the origin of this lower bound.
If you do the DateTime conversion with a field use a case statement in the conversion to check if the field is bigger than 1 OR 1000000 then you should not have this problem anymore.
I am getting same error during compare 2 dates.
I have solved with using datetime2 datatype.
For ex.
select * from TableA where Convert(datetime2,GETUTCDATE()) <= Convert(datetime2,Expirydate)

Encountering SQL Error not having to do with my query... what can I do to get to my data?

I'm trying to run this query:
select * from activity where id = 9348927
And I receive this error:
Conversion failed when converting the varchar value '04 30' to data type int.
Note that I still receive this error when I change * to id, which doesn't make any sense to me. I don't receive the error when I run this:
select top 32 * from activity where id = 9348927
I'm pretty sure this means that some of the data on the 33rd row is in a format that SQL Server doesn't like. Is there any way I can get it to ignore the error and display my data anyway?
EDIT: id is varchar(10)
This usually means that the id column is not a number datatype, but varchar.
9348927 is a number (int) and datatype precedence means the the string value '04 30' is converted to int. Standard SQL behaviour.
Try this:
select * from activity where id = '9348927'
Incidently, the implicit conversion means any index on id will not be used. Compare query plans.
The best way to "work around" this is to fix your data and column type. Otherwise, do the comparison as string which is what id most likely is.

Resources