I have a table with the following structure:
Unfortunately, the sale_date
is stored as INT and I had to find a way to convert it in quarter (202001 will be Q1). The conversion worked well, but I need to include also some calculated columns based on this conversion. Basically, I need to calculate for Q1 the total price for each product, and the percentage from total for "product x" and "product y" recorded by each seller, in the current year. I know that I can obtain these easily using group by, but the way I converted the date (sale_date
) from INT to quarter it's affecting the results.
SELECT
seller,
product_name,
LEFT([sale_date],4) Year,
'Q'+ CAST((CAST(RIGHT(sale_date,2) AS INT)-1 )/3 +1 AS varchar) Quarter,
(price),
price * 100.0 / sum(price) over () as percentage_total,
SUM (price) as total_sales
FROM table1
GROUP BY
LEFT(sale_date,4),
'Q'+ CAST((CAST(RIGHT(sale_date,2) AS INT) -1 )/3 +1 AS varchar),
seller,
product_name,
price