Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 475 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting the minimum of two values in SQL

#11
This works for up to 5 dates and handles nulls. Just couldn't get it to work as an Inline function.

CREATE FUNCTION dbo.MinDate(@Date1 datetime = Null,
@Date2 datetime = Null,
@Date3 datetime = Null,
@Date4 datetime = Null,
@Date5 datetime = Null)
RETURNS Datetime AS
BEGIN
--USAGE select dbo.MinDate('20120405',null,null,'20110305',null)
DECLARE @Output datetime;

WITH Datelist_CTE(DT)
AS (
SELECT @Date1 AS DT WHERE @Date1 is not NULL UNION
SELECT @Date2 AS DT WHERE @Date2 is not NULL UNION
SELECT @Date3 AS DT WHERE @Date3 is not NULL UNION
SELECT @Date4 AS DT WHERE @Date4 is not NULL UNION
SELECT @Date5 AS DT WHERE @Date5 is not NULL
)
Select @Output=Min(DT) FROM Datelist_CTE;

RETURN @Output;
END;

Reply

#12
```SQL
SELECT (WHEN first > second THEN second ELSE first END) the_minimal FROM table
```
Reply

#13
For SQL Server 2022+ (or MySQL or PostgreSQL 9.3+), a better way is to use the `LEAST` and `GREATEST` functions.

SELECT GREATEST(A.date0, B.date0) AS date0,
LEAST(A.date1, B.date1, B.date2) AS date1
FROM A, B
WHERE B.x = A.x

With:

- `GREATEST(value [, ...])` : Returns the **largest** (maximum-valued) argument from values provided
- `LEAST(value [, ...])` Returns the **smallest** (minimum-valued) argument from values provided


Documentation links :

- MySQL

[To see links please register here]

- Postgres

[To see links please register here]

- SQL Server

[To see links please register here]



Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through