I have got this query (simplified from a detailed query) to return dates as a substring. I want to return a substring which has just the minimum and maximum of the date if more than 1 date else return just the one date.
This is my SQL query:
SELECT
SUBSTRING((SELECT distinct ','+ r.ENTRY AS [text()]
FROM RESULT r
WHERE r.ENTRY IN ('19-09-2023', '20-09-2023', '21-09-2023', '22-09-2023')
AND r.sample_number = 74406
FOR XML PATH (''), TYPE ).value('text()[1]', 'nvarchar(max)'), 2, 1000) [Test Date]
This query returns:
19-09-2023,20-09-2023,21-09-2023,22-09-2023
However, I want just 19/09-22/09/2023
to be returned i.e. min to max date in the above format. If there is only one date then I just want that date returned.
How do I amend the query to get this? I do need it as a substring since this is just one of many other columns returned.
I tried to add a CASE
expression to get the min and max when there are more than 1 r.ENTRY
. That didn't work. I do not have any more ideas.
Thanks
4条答案
按热度按时间2w2cym1i1#
Since you are only interested in the minimum and maximum Date, you can use
MIN()
andMAX()
together withCASE
expression. No string aggregation is requiredCONVERT()
with style105
will return string indd-mm-yyyy
format.igsr9ssn2#
Are you looking for consecutive values of the
entry
column for a specific value of thesample_number
column?Results:
DB Fiddle.
Results for all rows of test data:
DB Fiddle.
brvekthn3#
A slightly more concise version of @Squirrel's excellent answer. You can use
CONCAT_WS
, which concatenates with a separator, and ignores nulls.hmtdttj44#
I have edited the suggested code to work for me. My field is not a date field so I had to use the replace and convert function to convert it to date and then the minimum and maximum works correctly. My working code as below: