Hii are you working today?
- User
Hii are you working today?
- Assistant
Hello! Yes, I'm here and ready to help you. What do you need assistance with today?
- User
Thanks for telling
- Assistant
You're welcome! If there's anything specific you want to talk about or any questions you have, feel free to ask.
- User
I'm working in snowflake with database name DEMO, schema name DS_DEMO and table name TRAINING_DATA_PROD_FEATURE_7_WITH_4_CATEGORY. I have column name MPG_SOLUTIONSELLINGSTAGE with values in it as 6,7,8,9 and count of each values are 32024, 11814, 15438, 23917 respectively. So we can see that the count of each values are not same. Please give me query so that I can remove some rows of 6,8,9 from the column and make it equal to the row of 7 in the column. Means each values count should be equal to 11814 in that column. Please provide me the sql query for the same.
- Assistant
To equalize the counts of the values in the
MPG_SOLUTIONSELLINGSTAGEcolumn in yourTRAINING_DATA_PROD_FEATURE_7_WITH_4_CATEGORYtable to match the count of value7(which is11814), you can use aCTE(Common Table Expression) or a subquery to first identify and limit the rows you want to keep for each of the other values (6, 8, and 9). Then, you can delete the excess rows accordingly.Here’s a SQL query you can use:
WITH ranked_data AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY MPG_SOLUTIONSELLINGSTAGE ORDER BY RANDOM()) AS rn FROM DEMO.DS_DEMO.TRAINING_DATA_PROD_FEATURE_7_WITH_4_CATEGORY WHERE MPG_SOLUTIONSELLINGSTAGE IN (6, 8, 9) ) DELETE FROM DEMO.DS_DEMO.TRAINING_DATA_PROD_FEATURE_7_WITH_4_CATEGORY WHERE (MPG_SOLUTIONSELLINGSTAGE = 6 AND rowid IN (SELECT rowid FROM ranked_data WHERE MPG_SOLUTIONSELLINGSTAGE = 6 AND rn > 11814)) OR (MPG_SOLUTIONSELLINGSTAGE = 8 AND rowid IN (SELECT rowid FROM ranked_data WHERE MPG_SOLUTIONSELLINGSTAGE = 8 AND rn > 11814)) OR (MPG_SOLUTIONSELLINGSTAGE = 9 AND rowid IN (SELECT rowid FROM ranked_data WHERE MPG_SOLUTIONSELLINGSTAGE = 9 AND rn > 11814)); - User
I am getting an error as - Syntax error: unexpected 'DELETE'.
- Assistant
It seems like the DELETE statement structure I provided is not correctly utilizing the proper syntax for Snowflake. In Snowflake, you cannot directly delete from the same table that you are selecting from in a CTE. Instead, you would typically use a temporary table approach, or you can use a combined with a subquery to achieve this.
- User
Now getting error as - Error: invalid identifier 'ROWID'
- Assistant
In Snowflake, there is no
ROWIDcolumn like there is in some other databases (e.g., Oracle). Instead, we need to work with a different approach using the primary keys (if available) or unique identifiers for the rows.If your table does not have a specific primary key or unique identifier, and since you are using the result of the logic, I suggest using a of the original table and the temporary table to determine which records to delete.