select ' \''||
CAST(NVL(X.TYPE,'') AS VARCHAR(50))||'\
\''||CAST(NVL(X.ID_1,'') AS VARCHAR(50))||'\
- \''||
---CAST(NVL(X.ID_2,'') AS VARCHAR(50))
CASE WHEN X.ID_2 IS NOT NULL
THEN X.ID_2
WHEN X.ID_2 IS NULL
THEN 'NULL' END
||'\ '
from
( select ....)
select query returns value for three columns.
Above code gives o/p as 'R'32 - 'NULL
Expected is 'R 32 - NULL'
Can someone help
Using CONCAT and COALESCE:
SELECT *,
CONCAT('\'',COALESCE(X.TYPE,''), ' ' ,
COALESCE(X.ID_1::TEXT, ''), ' - ' ,
COALESCE(X.ID_2::TEXT, 'NULL'), '\'') AS res
FROM (SELECT 'R' AS TYPE, 32::INT AS ID_1, NULL AS ID_2) AS X;
Output:
#Rahul, I believe you are looking for something like this? The escaped apostrophes were the culprit from Lukasz's answer.
SELECT
CONCAT(
COALESCE(X.TYPE,'')
, CHAR(32) /* <-- ADDS A SPACE */
, COALESCE(X.ID_1::TEXT, '')
, CHAR(32), CHAR(45), CHAR(32) /* <-- ADDS A SPACE DASH SPACE */
, COALESCE(X.ID_2::TEXT, 'NULL')
) AS res
FROM (SELECT 'R' AS TYPE, 32::INT AS ID_1, NULL AS ID_2) AS X
;
Returns:
R 32 - NULL
January-2016
August-2017
November-2018
January-2018
August-2018
November-2018
This is my date format how to increment month by 1 ?
DECLARE #Str VARCHAR(20) = 'January-2016'
SELECT FORMAT(DATEADD(MONTH , 1 ,
DATEFROMPARTS(RIGHT(#Str, 4) , DATEPART (MONTH, REPLACE(#Str , '-' , ' 01 ')) , 1)
)
, 'MMMM-yyyy')
Result: February-2016
You can just replace the dash with ' 1 ', as long as you explicitly use English:
SET LANGUAGE us_english;
DECLARE #s varchar(67) = 'January-2016';
SELECT TRY_CONVERT(date, REPLACE(#s, '-', ' 1 '));
So then add a month:
SELECT DATEADD(MONTH, 1, <try_convert expression>);
I have a query on SQL Server that's finding wrong results based on a datetime condition.
SET LANGUAGE Português
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
i9_parcelaBase.i9_data_vencimento,
i9_parcelaBase.i9_data_limite_envio_nf,
i9_parcelaBase.i9_status_atual,
i9_processo_statusBase.i9_status,
i9_processo_statusBase.i9_name
--i9_nota_fiscalBase.i9_nota_fiscalid as ID
from i9_parcelaBase
left join i9_processo_statusBase
on i9_parcelaBase.i9_status_atual = i9_processo_statusBase.i9_processo_statusId
where i9_processo_statusBase.i9_entidade = 100000002
and i9_parcelaBase.i9_data_vencimento between CONVERT(varchar(10), year(getdate())-1) + '-' + CONVERT(varchar(10), month(getdate())+1) + '-1'
and CONVERT(varchar(10), year(getdate())) + '-' + CONVERT(varchar(10), month(getdate())) + '-1'
order by i9_data_vencimento asc
Basically, Month that's receiving data without '0' before (when necessary).
Sample:
Actual return: '2017-6-1'
Expected return '2017-06-01'
Can anyone help me to solve this problem?
By the look of your query, i9_data_vencimento is expected to end with just -1, not -01. You can cast the string into a date, then recast it back as a string as a way to format it:
select distinct
CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10),
DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
CONVERT( VARCHAR(10), CONVERT( DATETIME, i9_parcelaBase.i9_data_vencimento ), 120 ) AS i9_data_vencimento,
:
:
Also, considering that i9_data_vencimento is just a string, and assuming it always ends with '1' in the format 'yyyy-mm-1', you could use a LEFT function to strip off the last character and replace it with '01':
SELECT DISTINCT
:
LEFT(i9_parcelaBase.i9_data_vencimento, 8) + '01' AS i9_data_vencimento,
:
Below is the query which I am trying to run:
SELECT
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS A,
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS B,
DATEDIFF(HOUR, CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00')), CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00'))) as DateDiffernce
Output is:
A B DateDiffernce
2016-12-01 02:00:00.000 2016-12-01 02:00:00.000 0
Let's take 12/1/2016 here the format is DD/MM/YYYY. After using convert function it is getting changed to YYYY-MM-DD which is fine the problem is places are changed i.e 12/1/2016 to 2016-12-01 12 which was the date is shifted or considered as month - which should not happen.
I even tried another query to restrict this conversion which didn't help:
SELECT
CONVERT(DATETIME, CONVERT(CHAR(10), '12/1/2016', 112)
+ ' ' + CONVERT(CHAR(8), '2:00:00', 108))
Kindly help..
Please check #Panagiotis Kanavos comment. He is right. Your query would work fine. Please change the time value like the below to get the DateDifference value.
SELECT CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103) AS A
,CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103) AS B
,DATEDIFF(HOUR, CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103), CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103)) AS DateDiffernce
Hello All Thankyou for your inputs, i was able to solve the issue by
using following code
SET DATEFORMAT YDM
Cheers!! Enjoy coding
Let's say I have a table like this in SQL Server:
Id City Province Country
1 Vancouver British Columbia Canada
2 New York null null
3 null Adama null
4 null null France
5 Winnepeg Manitoba null
6 null Quebec Canada
7 Seattle null USA
How can I get a query result so that the location is a concatenation of the City, Province, and Country separated by ", ", with nulls omitted. I'd like to ensure that there aren't any trailing comma, preceding commas, or empty strings. For example:
Id Location
1 Vancouver, British Columbia, Canada
2 New York
3 Adama
4 France
5 Winnepeg, Manitoba
6 Quebec, Canada
7 Seattle, USA
I think this takes care of all of the issues I spotted in other answers. No need to test the length of the output or check if the leading character is a comma, no worry about concatenating non-string types, no significant increase in complexity when other columns (e.g. Postal Code) are inevitably added...
DECLARE #x TABLE(Id INT, City VARCHAR(32), Province VARCHAR(32), Country VARCHAR(32));
INSERT #x(Id, City, Province, Country) VALUES
(1,'Vancouver','British Columbia','Canada'),
(2,'New York' , null , null ),
(3, null ,'Adama' , null ),
(4, null , null ,'France'),
(5,'Winnepeg' ,'Manitoba' , null ),
(6, null ,'Quebec' ,'Canada'),
(7,'Seattle' , null ,'USA' );
SELECT Id, Location = STUFF(
COALESCE(', ' + RTRIM(City), '')
+ COALESCE(', ' + RTRIM(Province), '')
+ COALESCE(', ' + RTRIM(Country), '')
, 1, 2, '')
FROM #x;
SQL Server 2012 added a new T-SQL function called CONCAT, but it is not useful here, since you still have to optionally include commas between discovered values, and there is no facility to do that - it just munges values together with no option for a separator. This avoids having to worry about non-string types, but doesn't allow you to handle nulls vs. non-nulls very elegantly.
select Id ,
Coalesce( City + ',' +Province + ',' + Country,
City+ ',' + Province,
Province + ',' + Country,
City+ ',' + Country,
City,
Province,
Country
) as location
from table
This is a hard problem, because the commas have to go in-between:
select id, coalesce(city+', ', '')+coalesce(province+', ', '')+coalesce(country, '')
from t
seems like it should work, but we can get an extraneous comma at the end, such as when country is NULL. So, it needs to be a bit more complicated:
select id,
(case when right(val, 2) = ', ' then left(val, len(val) - 1)
else val
end) as val
from (select id, coalesce(city+', ', '')+coalesce(province+', ', '')+coalesce(country, '') as val
from t
) t
Without a lot of intermediate logic, I think the simplest way is to add a comma to each element, and then remove any extraneous comma at the end.
Use the '+' operator.
Understand that null values don't work with the '+' operator (so for example: 'Winnepeg' + null = null), so be sure to use the ISNULL() or COALESCE() functions to replace nulls with an empty string, e.g.: ISNULL('Winnepeg','') + ISNULL(null,'').
Also, if it is even remotely possible that one of your collumns could be interpreted as a number, then be sure to use the CAST() function as well, in order to avoid error returns, e.g.: CAST('Winnepeg' as varchar(100)).
Most of the examples so far neglect one or more pieces of this. Also -- some of the examples use subqueries or do a length check, which you really ought not to do -- just not necessary -- though your optimizer might save you anyway if you do.
Good Luck
ugly but it will work for MS SQL:
select
id,
case
when right(rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,'')),1)=',' then left(rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,'')),LEN(rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,'')))-1)
else rtrim(coalesce(city + ', ','') + coalesce(province + ', ','') + coalesce(country,''))
end
from
table
I know it's an old question, but should someone should stumble upon this today, SQL Server 2017 and later has the STRING_AGG function, with the WITHIN GROUP option :
with level1 as
(select id,city as varcharColumn,1 as columnRanking from mytable
union
select id,province,2 from mytable
union
select id,country,3 from mytable)
select STRING_AGG(varcharColumn,', ')
within group(order by columnRanking)
from level1
group by id
Should empty strings exist aside of nulls, they should be excluded with some WHERE clause in level1.
Here is an option:
SELECT (CASE WHEN City IS NULL THEN '' ELSE City + ', ' END) +
(CASE WHEN Province IS NULL THEN '' ELSE Province + ', ' END) +
(CASE WHEN Country IS NULL THEN '' ELSE Country END) AS LOCATION
FROM MYTABLE