技术问询:如何在Tableau中创建本年及上年销售额的计算字段?
Alright, let's break this down step by step—no jargon, just straightforward instructions for both 本年销售额总和 and 上年销售额总和 calculated fields.
一、创建「本年销售额总和」计算字段
This one's pretty straightforward, but let's make sure we cover all bases:
- Open your Tableau workbook and confirm your data source includes a sales amount field (e.g.,
[销售额]) and a date field (e.g.,[订单日期]). - In the left-hand Data pane, right-click any blank area and select Create Calculated Field (or go to the top menu:
Analysis > Create Calculated Field). - Name the field something clear, like
本年销售额总和. - Paste (or type) this formula into the editor—adjust field names to match your data:
Quick breakdown:SUM(IF YEAR([订单日期]) = YEAR(TODAY()) THEN [销售额] ELSE 0 END)YEAR([订单日期])extracts the year from each order's dateYEAR(TODAY())grabs the current calendar year- We only sum sales where these two years match; all other dates contribute 0 to the total
- Click OK, and your new calculated field will show up in the Data pane—drag it to your view to use it.
If you're working with a pre-filtered view (e.g., you already have a year filter set to the current year), you can simplify this to just SUM([销售额])—but the formula above works even if your view includes multiple years.
二、创建「上年销售额总和」计算字段
This has two common use cases, so I'll cover both:
Scenario 1: Fixed previous calendar year (e.g., 2023 if current year is 2024)
Use this if you always want the total sales from the immediate prior calendar year:
- Open the calculated field editor again, name it
上年销售额总和. - Use this formula:
The only difference here isSUM(IF YEAR([订单日期]) = YEAR(TODAY()) - 1 THEN [销售额] ELSE 0 END)YEAR(TODAY()) - 1, which subtracts 1 from the current year to target the prior one.
Scenario 2: Dynamic previous year (matches the year in your view)
If you need the prior year relative to whatever year is displayed in your view (e.g., if your view shows 2022, this returns 2021 sales), use this approach:
- First, make sure you have a year dimension in your view (drag
[订单日期]to the Rows/Columns shelf, then right-click it and select Discrete > Year). - Create a new calculated field named
上年销售额总和(动态)with this formula:
Or if you want a fixed calculation that doesn't depend on the view's order, use a level of detail (LOD) expression:SUM(LOOKUP([销售额], -1)){FIXED YEAR([订单日期]) - 1: SUM([销售额])}
Quick Notes to Avoid Headaches
- Double-check that your date field is recognized as a Date type in Tableau. If not, right-click the field > Change Data Type > Date.
- If your data has a standalone
[年份]field instead of a full date, you can simplify the formulas (e.g.,SUM(IF [年份] = YEAR(TODAY()) THEN [销售额] ELSE 0 END)). - Test the fields by dragging them to a view alongside your raw sales data—you should see the totals match your expectations.
内容的提问来源于stack exchange,提问作者Sunitha Nagalapur

