We help IT Professionals succeed at work.
Get Started

Redshift INSERT INTO SELECT DISTINCT FROM cte

ttist25
ttist25 asked
on
53 Views
Last Modified: 2021-04-21
Hopefully that title explains it well enough but...

I'm working in a Redshift instance and I have a CTE that pulls fields from a couple tables and uses dense_rank to add an id for the grouped rows.  It seems to be working fine because I can select rows from my CTE and the results appear as I would expect.  

Next, I'm trying to insert the distinct rows from that CTE into an existing table.  That's where all hell breaks loose.  Well, maybe not all hell but definitely an error. :)

I'm still a noob w/ Redshift so I'm not sure how to do temp tables or I'd give some DDL here but, here is essentially what the code looks like:

WITH cte_MyCTE AS (
    SELECT 
        tbl1.[MyPID],
        tbl1.[MyDate],
        tbl2.[MyNumber],
        tbl2.[MyOtherNumber],
        DENSE_RANK() OVER(ORDER BY tbl1.[MyPID], tbl1.[MyNumber], DATEADD(HOUR, (DATEDIFF(HOUR, '1900-01-01 00:00:00.000', tbl1.[MyDate]/3)*3, '1900-01-01 00:00:00.000')) AS [MyGrpID]
FROM Table1 AS tbl1
LEFT JOIN Table2 AS tbl2
)
INSERT INTO Table3
SELECT DISTINCT
    [MyGrpID],
    [MyPID],
    [MyNumber],
    [MyOtherNumber]
FROM cte_MyCTE

Open in new window



Redshift says
SQL Error [500310] [421601]: [Amazon] (500310) Invalid operation: syntax error at or near "INSERT"

I'm stuck.  any ideas would be greatly appreciated!
Comment
Watch Question
CERTIFIED EXPERT
Most Valuable Expert 2012
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE