Skip to content
Advertisement

How to combine results from a query into columns of a new table

I have a list of dates, and I am trying to find the number of expired / nearly expired and OK dates and build a new table showing these.

The easiest method for me is to simply, query my database three times and build the expected results in the my app. I am just wondering if SQL would be more cleaner.

I have only managed to produce three distinct correct results, but I need to the final result to be in it’s own table.

I have a SQLFiddle showing what I have done so far http://www.sqlfiddle.com/#!18/c7b1a/1

My table is

Data is

The SQL I have come up with so far is

However, this will obviously show three seperate results.

Ideally, I want each result in a column of a new table

My expected result would be

Where Expired = 1 because first SQL query returns 1

Where Due = 2 because second SQL query returns 2

Where OK = 3 because third SQL query returns 3

Advertisement

Answer

Use conditional aggregation with case when expression

DEMO

OUTPUT:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement