0

我有一个具有以下结构的表:

桌子

不幸的是,它sale_date被存储为 INT,我不得不在季度(202001 年将是 Q1)找到一种方法来转换它。转换效果很好,但我还需要包含一些基于此转换的计算列。基本上,我需要计算第一季度每种产品的总价格,以及每个卖家在当年记录的“产品 x”和“产品 y”占总价格的百分比。我知道我可以使用 group by 轻松获得这些,但是我将日期(sale_date)从 INT 转换为季度的方式会影响结果。

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
4

1 回答 1

0

注意:您应该始终为列使用正确的数据类型。会避免很多问题。始终将日期值存储在date数据类型中。

我建议您首先将INT数据类型转换为日期,然后使用DATE函数来计算季度名称。这将是准确的。

下面我将01作为日期添加到 中yyyymm,然后将其设为yyyymmdd,使其成为ISO 8601日期格式(与日期格式无关),然后计算季度值。

declare @table table(sales_date int, product_name varchar(30),seller varchar(30), price int)

insert into @table
VALUES(202001,'Product X', 'Agent1',2320),(202001,'Product X', 'Agent2',1416),
(202004,'Product X', 'Agent1',420)

SELECT seller, product_name,
CONCAT('Q',DATENAME(QUARTER,CONCAT(CAST(sales_date AS VARCHAR(10)),'01'))) as Quarter,
sum(price) as total_sales
from @table
group by seller, product_name,
CONCAT('Q',DATENAME(QUARTER,CONCAT(CAST(sales_date AS VARCHAR(10)),'01')))

+--------+--------------+---------+-------------+
| seller | product_name | Quarter | total_sales |
+--------+--------------+---------+-------------+
| Agent1 | Product X    | Q1      |        2320 |
| Agent1 | Product X    | Q2      |         420 |
| Agent2 | Product X    | Q1      |        1416 |
+--------+--------------+---------+-------------+
于 2020-07-10T10:05:58.857 回答