Kata 5kyu

You need to create a function that calculates the number of weekdays (Monday through Friday) between two dates inclusively.

The function should be named weekdays accept two arguments of type DATE and return an INTEGER value.

weekdays(DATE, DATE) INTEGER

The order of arguments shouldn’t matter. To illustrate both of the following queries

SELECT weekdays('2016-01-01', '2016-01-10');
SELECT weekdays('2016-01-10', '2016-01-01');

should produce the same result

weekdays
----------
6
(1 row)

Solution:

create or replace function weekdays(DATE, DATE) 
returns int as $$
begin
return count(days)::int
from generate_series(least($1, $2),greatest($1, $2), '1 day')
as days
where extract(DOW from days) NOT IN (0,6);
end;
$$ language plpgsql;

Official Solution:

-- Replace with your code
create or replace function weekdays(_start date, _finish date)
returns integer
as
$$

select count(*) filter (where extract(dow from g.d) between 1 and 5)::int as weekdays
from generate_series(least(_start, _finish), greatest(_start, _finish), interval '1 day') as g(d);

$$ language sql;

Link

Reference

--

--

--

My homepage to record my thought processes for solving SQL and Algorithm questions

Recommended from Medium

Top 5 Reasons Why People Are Migrating From Teradata to Snowflake

Understanding Other People's Solutions Are One Of The Most Valuable Lessons

Creating Tags For Resources in Single Account and Multiple Accounts Using Cloud-Custodian

How To Set Up an OpenVPN Server on Ubuntu

Coding Terms | OBJECT RELATIONAL MODEL ORM

How to use CouchDB as Cache Database in your app (3/3)

Version Controlling | NoSql

The best reference guide to master Classes in Python in 2021.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Isabelle

Isabelle

In love with telling stories with data

More from Medium

SQL Introduction 1

An internal hard drive

Embedded SQL and Dynamic SQL a

Few tips to write an effective SQL query.

SQL Window Function Visualized