0

I am working with Netezza SQL.

I have the following table ("my_table"):

  id year var1 var3 date_1
1  1 2017    1    1    NA
2  1 2018    0    1    NA
3  1 2019    1    1    NA
4  2 2017    0    1    NA
5  2 2018    1    1    NA
6  3 2017    1    1    NA
7  3 2018    1    1    NA
8  3 2019    0    1    NA

I have the following query:

WITH cte1 AS (
    SELECT
        id,
        year,
        SUM(var1) AS var1mod,
        date_1
    FROM my_table
    WHERE var3 = 1
    GROUP BY id, year, date1
),

cte2 AS ( SELECT id FROM cte1 WHERE var1mod = 0 ),

cte3 AS ( SELECT id, COUNT(DISTINCT year) AS year_count FROM cte1 WHERE id IN (SELECT id FROM cte2) AND date_1 IS NULL GROUP BY id ),

cte4 AS ( SELECT id, MIN(year) AS min_year FROM cte1 GROUP BY id )

SELECT year_count, COUNT(*) AS count_per_year FROM cte3 WHERE id IN (SELECT id FROM cte4 WHERE min_year = 2000) GROUP BY year_count;

My Question:

  • In the above query, I am running this for min_year = 2000 and var1mod = 0
  • Is it possible to run this query for all possible combinations of min_year and var1mod?

Currently, I have manually copy/pasted this query multiple times and used a series of UNION ALL statements to accomplish this task - but can someone please show me how I can aggregate this query to run it for all possible combinations of min_year and var1mod?

Thanks!

stats_noob
  • 143
  • 7

0 Answers0