DateAdd and date fields not working as a criteria for a query - date

The query I am working on has worked before. I don't know the exact date since I inherited it when my co-worker left. Every time I run the query I get a "Data type Mismatch in criteria expression."
SELECT Personnel.Badge, Personnel.First_Name, Personnel.Last_Name, Training.Course, DateAdd("m",[Cert_Duration],[Latest_Course_Date]) AS Cert_Expiration, Personnel.Reports_To
FROM Training INNER JOIN (Personnel INNER JOIN qry_Training_Log_Latest_Course ON Personnel.Badge = qry_Training_Log_Latest_Course.Personnel) ON Training.Training_ID = qry_Training_Log_Latest_Course.Course
WHERE (((DateAdd("m",[Cert_Duration],[Latest_Course_Date]))<DateAdd("m",6,Date())) AND ((Training.Cert_Duration) Is Not Null));
It appears the line
I would appreciate any feedback on this.

This query also triggers "Data type Mismatch in criteria expression."
SELECT DateAdd("m", Null, Date());
Therefore your error is likely caused by Null [Cert_Duration] values in this expression ...
DateAdd("m",[Cert_Duration],[Latest_Course_Date])
You need to revise the query to either ...
Exclude rows with Null [Cert_Duration] values before the DateAdd() is evaluated.
Or substitute something else for Null [Cert_Duration] values in that expression.

Related

T-SQL Error converting data type on join, on non-joining field

A query is written to join data from two tables and group it. If the two lines defining the join are commented out, the query returns correctly. Here is the query (with the join commented out):
SELECT tblTurbineLocations.TurbineLayoutProjectID as ProjectID
,TurbineLayoutNumber
,Count(HubHeight) as NumTurbines
,tblTurbineLocations.WTCode
FROM [TurbineLayout].[dbo].[tblTurbineLocations]
--LEFT OUTER JOIN [TurbineModel].[dbo].[tblTurbineModels]
--ON str(tblTurbineLocations.WTCode) = str(tblTurbineModels.WTCode) --Need to force string conversion to avoid data type conflict.
WHERE tblTurbineLocations.TurbineLayoutProjectID = 2255
AND tblTurbineLocations.TurbineLayoutNumber IN (406, 407)
GROUP BY tblTurbineLocations.TurbineLayoutProjectID ,tblTurbineLocations.TurbineLayoutNumber ,tblTurbineLocations.WTCode
Removing the two commented join lines then attempts a join on the WTCode field. This returns the following error:
Msg 8114, Level 16, State 5, Line 2
Error converting data type nvarchar to float.
The error points to line 2, rather than the line containing the join. The error raises that nvarchar cannot be converted to float. However the column in line 2, tblTurbineLocations.TurbineLayoutProjectID, is not an nvarchar; it is an int:
Reviewing the other columns in the query, none are of type nvarchar save for the joining column, WTCode (nvarchar(11) in one table, nvarchar(5) in the other). Both are cast as strings to avoid a different error (that is resolved by casting as str):
Cannot resolve the collation conflict between "Latin1_General_CI_AS" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.
WTCode is not being cast as a float in the query.
What is the error in my code or my approach?
As indicated by Larnu in the comments:
The issue is that the "str" function is expecting a float, thus is returning the error when it is fed an nvarchar. To solve the collation conflict, COLLATE can be used after the join to confirm what collation should be used for the nvarchar fields. Thus the following works:
SELECT tblTurbineLocations.TurbineLayoutProjectID as ProjectID
,TurbineLayoutNumber
,Count(HubHeight) as NumTurbines
,tblTurbineLocations.WTCode
FROM [TurbineLayout].[dbo].[tblTurbineLocations]
LEFT OUTER JOIN [TurbineModel].[dbo].[tblTurbineModels]
ON tblTurbineLocations.WTCode = tblTurbineModels.WTCode
COLLATE Latin1_General_CS_AS_KS_WS
WHERE tblTurbineLocations.TurbineLayoutProjectID = 2255
AND tblTurbineLocations.TurbineLayoutNumber IN (406, 407)
GROUP BY tblTurbineLocations.TurbineLayoutProjectID ,tblTurbineLocations.TurbineLayoutNumber ,tblTurbineLocations.WTCode

Modify values within a column and row (PSQL)

I get the following error for this query: [22P02] ERROR: invalid input syntax for type numeric: "."
select
date,
row_number () over () as RN,
case when (row_number() over ()) ='8' then '.' else (success/trials) end as "After_1M"
from trials
groupy by date;
Is there another way to indicate that a certain value in a ROWxCOLUMN combination should be adjusted?
Well your description certainly leaves a lot to be desired. But your query only needs slight modification to actually run. First off "groupy by date". I will assume it's just a typo. But a group by without an aggregate function generally doesn't do anything - and this is one of those. But I believe your attempting to get a row count by date. If so the you need the partition by and order by clauses in the in the row_number function. The other issue is in the expression. Each entry in the expression must return the same data type but in case it doesn't. The THEN condition returns character (.) while the ELSE returns a numeric (success/trials) which must define 2 numeric columns to be valid. So which needs to change? I will assume the later. Given this we wind up with:
select date
, row_number() over(partition by date order by trl_date) rn
, case when (row_number() over(partition by date order by trl_date)) = 8
then '.'
else (success/trials)::text
end as "After_1M"
from trials;
Note: Date is a very poor date is a very poor column name. It's a reserved word, as well as a data type.

Update with ISNULL and operation

original query looks like this :
UPDATE reponse_question_finale t1, reponse_question_finale t2 SET
t1.nb_question_repondu = (9-(ISNULL(t1.valeur_question_4)+ISNULL(t1.valeur_question_6)+ISNULL(t1.valeur_question_7)+ISNULL(t1.valeur_question_9))) WHERE t1.APPLICATION = t2.APPLICATION;
I know you cannot update 2 tables in a single query so i tried this :
UPDATE reponse_question_finale t1
SET nb_question_repondu = (9-(COALESCE(t1.valeur_question_4,'')::int+COALESCE(t1.valeur_question_6,'')::int+COALESCE(t1.valeur_question_7)::int+COALESCE(t1.valeur_question_9,'')::int))
WHERE t1.APPLICATION = t1.APPLICATION;
But this query gaves me an error : invalid input syntax for integer: ""
I saw that the Postgres equivalent to MySQL is COALESCE() so i think i'm on the good way here.
I also know you cannot add varchar to varchar so i tried to cast it to integer to do that. I'm not sure if i casted it correctly with parenthesis at the good place and regarding to error maybe i cannot cast to int with coalesce.
Last thing, i can certainly do a co-related sub-select to update my two tables but i'm a little lost at this point.
The output must be an integer matching the number of questions answered to a backup survey.
Any thoughts?
Thanks.
coalesce() returns the first non-null value from the list supplied. So, if the column value is null the expression COALESCE(t1.valeur_question_4,'') returns an empty string and that's why you get the error.
But it seems you want something completely different: you want check if the column is null (or empty) and then subtract a value if it is to count the number of non-null columns.
To return 1 if a value is not null or 0 if it isn't you can use:
(nullif(valeur_question_4, '') is null)::int
nullif returns null if the first value equals the second. The IS NULL condition returns a boolean (something that MySQL doesn't have) and that can be cast to an integer (where false will be cast to 0 and true to 1)
So the whole expression should be:
nb_question_repondu = 9 - (
(nullif(t1.valeur_question_4,'') is null)::int
+ (nullif(t1.valeur_question_6,'') is null)::int
+ (nullif(t1.valeur_question_7,'') is null)::int
+ (nullif(t1.valeur_question_9,'') is null)::int
)
Another option is to unpivot the columns and do a select on them in a sub-select:
update reponse_question_finale
set nb_question_repondu = (select count(*)
from (
values
(valeur_question_4),
(valeur_question_6),
(valeur_question_7),
(valeur_question_9)
) as t(q)
where nullif(trim(q),'') is not null);
Adding more columns to be considered is quite easy then, as you just need to add a single line to the values() clause

MDX query not accepting date values

I'm a SSAS newbie and i'm trying to query a cube to retrieve data against aome measure groups order by date. The date range i wish to specify in my query. The query I'm using is this:-
SELECT
{
[Measures].[Measure1],
[Measures].[Measure2],
[Measures].[Measure3]
}
ON COLUMNS,
NON EMPTY{
[Date].[AllMembers]
}
ON ROWS
FROM (SELECT ( STRTOMEMBER('2/23/2013', CONSTRAINED) :
STRTOMEMBER('3/1/2013', CONSTRAINED) ) ON COLUMNS
FROM [MyCube])
However it gives me the following error
Query (10, 16) The restrictions imposed by the CONSTRAINED flag in the STRTOMEMBER function were violated.
I tried removing the constrained keyword and then even strtomember function. But in each cases i got the following errors respectively
Query (10, 16) The STRTOMEMBER function expects a member expression for the 1 argument. A string or numeric expression was used.
and
*Query (10, 14) The : function expects a member expression for the 1 argument. A string or numeric expression was used.
*
I can understand from the last two errors that i need to include the constraint keyword. But can anyone tell me why this query wont execute?
The string that you pass as the member expression must be a fully-qualified member name, or resolve to one. Use the same format as you did in the SELECT.
For example:
STRTOMEMBER('[Date].[2/23/2013]', CONSTRAINED)
Edit: I just noticed the syntax of your range select looks wrong -- you need to use {...}, not (...).
SELECT {
STRTOMEMBER('2/23/2013', CONSTRAINED) :
STRTOMEMBER('3/1/2013', CONSTRAINED) }
Please execute below script.
Extract your date dimension attribute copy it by right clicking and paste it in STRTOMEMBER value.
It will works fine.
SELECT NON EMPTY { [Measures].[Internet Sales Amount] } ON COLUMNS
FROM ( SELECT ( STRTOMEMBER('[Date].[Date].&[20050701]') :
STRTOMEMBER('[Date].[Date].&[20061007]') ) ON COLUMNS
FROM [Adventure Works])
FROM ( SELECT (
STRTOMEMBER(#FromDateCalendarDate, CONSTRAINED) :
STRTOMEMBER(#ToDateCalendarDate, CONSTRAINED) ) ON COLUMNS

Updating records in Postgres using nested sub-selects

I have a table where I have added a new column, and I want to write a SQL statement to update that column based on existing information. Here are the two tables and the relevant columns
'leagues'
=> id
=> league_key
=> league_id (this is the new column)
'permissions'
=> id
=> league_key
Now, what I want to do, in plain English, is this
Set leagues.league_id to be permissions.id for each value of permissions.league_key
I had tried SQL like this:
UPDATE leagues
SET league_id =
(SELECT id FROM permissions WHERE league_key =
(SELECT distinct(league_key) FROM leagues))
WHERE league_key = (SELECT distinct(league_key) FROM leagues)
but I am getting an error message that says
ERROR: more than one row returned by a subquery used as an expression
Any help for this would be greatly appreciated
Based on your requirements of
Set leagues.league_id to be permissions.id for each value of permissions.league_key
This does that.
UPDATE leagues
SET league_id = permissions_id
FROM permissions
WHERE permissions.league_key = leagues.league_key;
When you do a subquery as an expression, it can't return a result set. Your subquery must evaluate to a single result. The error that you are seeing is because one of your subqueries returns more than one value.
Here is the relevant documentation for pg84: