Calculated columns計算欄

Finance asks for the amount invoiced on every order line, grouped into size bands. The table stores prices and rates, not the invoiced amount, so the query has to calculate it. This chapter builds new columns from existing ones, names them, sorts rows into bands and works with dates, and shows how a formula that looks right taxes the wrong amount.

財務部要求列出每一行訂單的發票金額,並按金額大小分組。表中只存放價格和比率,沒有發票金額,所以查詢要自行計算。本章會用現有的欄建立新欄、為它們命名、把行歸入不同組別、進行日期計算,並說明一條看似正確的公式如何對錯誤的金額徵稅。

Builds on 先修內容
Chapter 2
Reading time 閱讀時間
About 30 minutes
Tables 數據表
lineitem
Runs in 執行環境
Your browser

What did we actually invoice?我們實際開出了多少發票?

Finance is preparing a report on order sizes. For every order line it wants the amount the customer was invoiced: the list price, less the discount, plus tax. It also wants each line marked small, medium or large, so it can see how much of the business comes from small lines. The figures will be reconciled against the accounts, so they have to be right to the cent.

財務部正在準備一份關於訂單規模的報告。它要求列出每一行訂單向客戶開出的發票金額:標價減去折扣,再加上稅。它亦希望每一行標明屬於小、中或大額,以便看到有多少生意來自小額訂單行。這些數字會與賬目對賬,所以必須準確到每一分。

lineitem has one row per order line. Here are the 6 lines of order 1:

lineitem 每一行代表一行訂單。以下是第 1 號訂單的 6 行:

l_linenumberl_quantityl_extendedpricel_discountl_tax
117.0024710.350.040.02
236.0056688.120.090.06
38.0012301.040.100.02
428.0025816.560.090.06
524.0027389.760.100.04
632.0033828.800.070.02

6 rows

Column 欄Holds 存放內容
l_quantityNumber of units ordered 訂購數量
l_extendedpriceQuantity × unit price, before discount and tax: an amount 數量 × 單價,未扣折扣、未加稅:是一個金額
l_discountDiscount as a rate: 0.04 means 4% 折扣率:0.04 代表 4%
l_taxTax as a rate: 0.02 means 2% 稅率:0.02 代表 2%

The invoiced amount is not stored anywhere. It has to be calculated from these columns, and the first thing to notice is that two of them are rates and one is an amount.

發票金額沒有儲存在任何地方,必須用這些欄計算出來。首先要留意的是:其中兩欄是比率,一欄是金額。

In Excel: formula columns and IF在 Excel 中:公式欄與 IF

In Excel you would add a column with a formula such as =C2*(1-D2)*(1+E2), fill it down, and add another with =IF(F2<10000,"small",IF(F2<50000,"medium","large")) for the band. SQL works the same way in principle: you write an expression, and it is worked out for each row. The comparison stops working in three places.

在 Excel 中,你會新增一欄,寫入 =C2*(1-D2)*(1+E2) 之類的公式並向下填滿,再新增一欄用 =IF(F2<10000,"small",IF(F2<50000,"medium","large")) 分組。SQL 的原理相同:你寫一條運算式,數據庫逐行計算。這個比較在三個地方不再成立。

  • An Excel formula lives in each cell. Someone can type a number over one of them, or forget to fill the formula down to new rows, and the column still looks consistent. A SQL expression is written once and applied to every row. Nothing is stored: the result is recalculated from the current data each time the query runs.

    Excel 的公式存在於每一個儲存格中。有人可能在其中一格直接輸入數字,或忘記把公式填到新加的行,而這一欄看起來仍然一致。SQL 的運算式只寫一次,套用到每一行。結果不會被儲存,每次執行查詢都會根據當前數據重新計算。

  • An Excel formula can refer to any cell. A SQL expression sees only the columns of the row it is working on. Comparing a row with the one above it needs other tools, which Chapter 13 introduces.

    Excel 公式可以引用任何儲存格。SQL 運算式只能看到它正在處理的那一行的欄。要把一行與上一行比較,需要其他工具,第 13 章會介紹。

  • Months are counted differently. Excel’s DATEDIF counts complete months. A common SQL function counts something else, as Section 6 shows.

    月數的計算方法不同。Excel 的 DATEDIF 計算完整的月數,而一個常用的 SQL 函數計算的是另一樣東西,第 6 節會說明。

Calculating from columns用欄進行計算

After SELECT you can write a calculation as well as a column name. The usual operators work: +, -, * and /, with multiplication and division before addition and subtraction, and parentheses to change that.

SELECT 後面除了欄名,也可以寫計算。常用的運算符都可以使用:+、-、* 和 /;乘除先於加減,可以用括號改變次序。

l_linenumberl_extendedprice(l_extendedprice * l_discount)(l_extendedprice * (1 - l_discount))
124710.35988.414023721.9360
256688.125101.930851586.1892
312301.041230.104011070.9360
425816.562323.490423493.0696
527389.762738.976024650.7840
633828.802368.016031460.7840

6 rows

  • l_extendedprice * l_discount is the discount in money. A rate times an amount gives an amount.

    l_extendedprice * l_discount 是以金額計算的折扣。比率乘以金額,得出的是金額。

  • l_extendedprice * (1 - l_discount) is the price after the discount. Without the parentheses, l_extendedprice * 1 - l_discount would subtract a rate of a few hundredths from an amount of thousands.

    l_extendedprice * (1 - l_discount) 是扣除折扣後的價格。如果沒有括號,l_extendedprice * 1 - l_discount 會從數以萬計的金額中減去一個只有百分之幾的比率。

  • Every row gets its own result, and the table itself is unchanged.

    每一行各自得出結果,表本身沒有任何改變。

The result columns are named after the calculation, which is hard to read. The next section fixes that. First, one difference between databases that catches people out:

結果欄以計算式命名,很難閱讀,下一節會處理這個問題。在此之前,先看一個常令人出錯的數據庫差異:

(7 / 2)(7 // 2)
3.53

1 row

Naming and rounding the result為結果命名和四捨五入

AS gives a result column a name, called an alias. ROUND(x, 2) rounds to two decimal places, as an invoice does:

AS 為結果欄命名,這個名稱稱為別名(alias)。ROUND(x, 2) 會像發票一樣四捨五入至兩個小數位:

l_linenumberlist_pricenet_priceinvoiced
124710.3523721.9424196.37
256688.1251586.1954681.36
312301.0411070.9411292.35
425816.5623493.0724902.65
527389.7624650.7825636.82
633828.8031460.7832090.00

6 rows

  • Aliases are for people reading the result. Use lower case and underscores, and say what the number is, not how it was calculated.

    別名是給閱讀結果的人看的。用小寫和底線,說明這個數字是甚麼,而不是它如何計算出來。

  • An alias exists only in the result. In most databases you cannot use it in WHERE in the same query; DuckDB allows it, PostgreSQL and SQL Server do not. Chapter 4 explains the order in which the parts of a query run, which is the reason.

    別名只存在於結果中。在大多數數據庫中,同一條查詢的 WHERE 不能使用它;DuckDB 容許,PostgreSQL 和 SQL Server 則不容許。第 4 章會解釋查詢各部分的執行次序,這就是原因所在。

  • The calculation keeps more decimal places than the columns it starts from. Round at the end, not in the middle: rounding the net price and then adding tax to the rounded figure can move the result by a cent.

    計算結果的小數位比原本的欄更多。四捨五入應放在最後,而不是中途:先把淨價四捨五入,再在四捨五入後的數字上加稅,結果可能相差一分。

Putting rows into bands把行分組歸類

CASE chooses a value according to conditions, like Excel’s IF. It checks each WHEN in order, returns the value after the first one that is true, and uses ELSE if none is. Finance’s bands are under 10,000, 10,000 to under 50,000, and 50,000 or more. Order 7 has lines in all three:

CASE 按條件選擇一個值,就像 Excel 的 IF。它按次序檢查每個 WHEN,返回第一個成立的條件後面的值;如果全部不成立,就使用 ELSE。財務部的分組是:少於 10,000、10,000 至少於 50,000、50,000 或以上。第 7 號訂單三個組別都有:

l_linenumberinvoicedband
119803.47medium
212112.03medium
381904.34large
443291.28medium
550157.64large
657397.46large
77219.49small

7 rows

Across all 60,175 lines there are 8,519 small, 36,013 medium and 15,643 large. Chapter 4 shows how to count them with one query.

在全部 60,175 行中,小額有 8,519 行,中額有 36,013 行,大額有 15,643 行。第 4 章會說明如何用一條查詢計算這些數目。

  • The order of the WHEN clauses matters. Write the “under 50,000” test first and every small line is caught by it: the “small” band would have 0 lines, and no error would say so.

    WHEN 子句的次序很重要。如果先寫「少於 50,000」的測試,所有小額行都會先被它捕捉:「小額」組別會變成 0 行,而且不會有任何錯誤提示。

  • Because the first true WHEN wins, the second test does not need to repeat “at least 10,000”. Each band starts where the one before it ends, so no line falls in two bands or in none.

    由於第一個成立的 WHEN 優先,第二個測試不必重複寫「至少 10,000」。每個組別從上一個組別結束的地方開始,所以不會有任何一行同時屬於兩組,或不屬於任何一組。

  • Without ELSE, a row that matches no WHEN gets NULL, a value meaning “nothing”. Chapter 5 is about NULL.

    如果沒有 ELSE,不符合任何 WHEN 的行會得到 NULL,一個代表「沒有值」的值。第 5 章專門討論 NULL。

Calculating with dates日期計算

Subtracting one date from another gives the number of days between them, and adding a whole number to a date moves it forward by that many days. How long did each line of order 1 take to arrive?

兩個日期相減,得出相隔的日數;日期加上一個整數,會把日期向後推相應的日數。第 1 號訂單的每一行用了多少天送達?

l_linenumberl_shipdatel_receiptdatetransit_daysship_plus_30
11996-03-131996-03-2291996-04-12
21996-04-121996-04-2081996-05-12
31996-01-291996-01-3121996-02-28
41996-04-211996-05-16251996-05-21
51996-03-301996-04-0121996-04-29
61996-01-301996-02-0341996-02-29

6 rows

Days are unambiguous. Months are not, because they have different lengths. DuckDB has two functions that answer different questions:

日數沒有歧義,月數卻有,因為每個月的長度不同。DuckDB 有兩個函數,回答的是不同的問題:

daysmonth_boundarieswhole_months
110

1 row

From 31 January to 1 February is 1 day. date_diff counts how many times the calendar crosses into a new month, so it gives 1. date_sub counts complete months, like Excel’s DATEDIF, and gives 0. Other databases have their own functions with their own rules. Before reporting “months between” two dates, check which of these the function computes, on a pair of dates where the answers differ.

1 月 31 日至 2 月 1 日相隔 1 天。date_diff 計算日曆跨入新月份的次數,所以得出 1。date_sub 計算完整的月數,與 Excel 的 DATEDIF 相同,得出 0。其他數據庫有各自的函數和規則。在報告兩個日期之間「相隔多少個月」之前,先用一對答案會不同的日期,確認函數計算的是哪一種。

Which amount is taxed?稅按哪個金額計算?

Back to the invoiced amount. Two analysts write the formula. The first takes the discount off and then adds tax to what is left: l_extendedprice * (1 - l_discount) * (1 + l_tax). The second writes what the request says, list price less discount plus tax, in one bracket: l_extendedprice * (1 - l_discount + l_tax). Both look reasonable. On order 1:

回到發票金額。兩位分析師各自寫公式。第一位先扣除折扣,再對餘下的金額加稅:l_extendedprice * (1 - l_discount) * (1 + l_tax)。第二位照着要求的字面意思,把「標價減折扣加稅」寫在同一個括號內:l_extendedprice * (1 - l_discount + l_tax)。兩條公式看起來都合理。以第 1 號訂單為例:

l_linenumberl_extendedpricel_discountl_taxtax_after_discounttax_on_list_price
124710.350.040.0224196.3724216.14
256688.120.090.0654681.3654987.48
312301.040.100.0211292.3511316.96
425816.560.090.0624902.6525042.06
527389.760.100.0425636.8225746.37
633828.800.070.0232090.0032137.36

6 rows

Every line differs. On line 2 the first formula gives 54681.36 and the second 54987.48, 306.12 more. The second formula calculates the tax on the list price, before the discount, so the customer pays tax on money it was never charged. The difference on each line is price × discount × tax, so it appears on every line that has both a discount and a tax: 48,741 of the 60,175. Over the whole table:

每一行都不同。第 2 行的第一條公式得出 54681.36,第二條得出 54987.48,多了 306.12。第二條公式按扣除折扣前的標價計稅,等於客戶為從未被收取的金額交稅。每一行的差額是「價格 × 折扣率 × 稅率」,所以凡是同時有折扣和稅的行都會出現差額:60,175 行中有 48,741 行。就整張表而言:

tax_after_discounttax_on_list_price
2127397347.042131695684.59

1 row

SUM adds up a column over all rows; Chapter 4 covers it. Taxing the list price overstates the amount invoiced by 4,298,338, about 0.2%. That is too small to notice by looking at the total, and too large to pass a reconciliation: the report will not agree with the accounts, and someone will spend days finding out why.

SUM 把一欄所有行的值相加,第 4 章會介紹。按標價計稅,會把發票總額高估 4,298,338,約 0.2%。這個差額小得看總數時不會察覺,卻大得無法通過對賬:報告與賬目對不上,有人要花上幾天才找到原因。

Note what the problem is not. Applying the tax first and the discount second, l_extendedprice * (1 + l_tax) * (1 - l_discount), gives exactly the same result as the first formula, because multiplication can be done in any order. What matters is the amount each rate applies to. That is a business rule, not a matter of SQL: the TPC-H specification, like most sales taxes, charges tax on the discounted price, and the first formula reproduces the original data exactly (2,127,397,347 in the clean table).

要留意問題並不在哪裏。先加稅、後扣折扣,即 l_extendedprice * (1 + l_tax) * (1 - l_discount),結果與第一條公式完全相同,因為乘法的次序可以調換。關鍵在於每個比率套用在哪個金額上。這是業務規則,而不是 SQL 的問題:TPC-H 規範和大多數銷售稅一樣,按折扣後的價格計稅,而第一條公式與原始數據完全吻合(乾淨表中為 2,127,397,347)。

When AI writes the query當 AI 替你寫查詢

Ask an AI assistant for “list price minus discount plus tax for each line” and either formula may come back, depending on how the request is worded. A worse one also appears: l_extendedprice - l_discount + l_tax, which treats the rates as amounts. It subtracts a few hundredths from each price, and its total of 2,152,189,176 is almost the gross 2,152,189,760, overstating the amount invoiced by 24,791,829. All three run without an error.

如果你要求 AI 助手計算「每一行的標價減折扣加稅」,視乎措辭,上面兩條公式都可能出現。還有一條更差的:l_extendedprice - l_discount + l_tax,它把比率當作金額,只從每個價格中減去百分之幾,總數 2,152,189,176 幾乎等於未扣折扣的總額 2,152,189,760,把發票總額高估了 24,791,829。三條公式都能順利執行,不會報錯。

The assistant cannot tell from column names whether a number is a rate or an amount, or which amount a tax applies to. This adds the third item to the checklist: for every column in a calculation, know its unit, and test the formula against one case calculated by hand.

助手無法從欄名判斷一個數字是比率還是金額,也不知道稅應按哪個金額計算。這為清單加上第三項:計算中用到的每一欄,都要知道它的單位,並用一個人手計算的例子測試公式。

  • What does one row represent? (Chapter 1)

    一行代表甚麼?(第 1 章)

  • Does a text filter match every spelling the column actually holds? (Chapter 2)

    文字篩選是否涵蓋這一欄實際存在的所有寫法?(第 2 章)

  • Is each column in a calculation a rate, an amount, days or months, and does the formula reproduce one case worked out by hand? (Chapter 3)

    計算中的每一欄是比率、金額、日數還是月數?公式能否重現一個人手計算的例子?(第 3 章)

Check your understanding自我測驗

  1. For each line of order 1, show the discount in money, rounded to the cent, largest first. Which line received the largest discount?

    列出第 1 號訂單每一行以金額計算的折扣,四捨五入至分,由大至小排列。哪一行得到最大的折扣?

    Answer 答案
    l_linenumberdiscount_amount
    25101.93
    52738.98
    62368.02
    42323.49
    31230.10
    1988.41

    6 rows

    Line 2. You can sort by an alias: ORDER BY runs after the result columns have been calculated.

    第 2 行。你可以按別名排序:ORDER BY 在結果欄計算完成後才執行。

  2. The shortest transit time in lineitem, receipt date minus ship date, is -3 days. Find some of those lines. What does a negative transit time mean?

    lineitem 中最短的運送時間(收貨日期減發貨日期)是 -3 天。找出其中幾行。運送時間為負數代表甚麼?

    Answer 答案
    l_orderkeyl_linenumberl_shipdatel_receiptdatetransit_days
    70721995-01-121995-01-09-3
    154351997-03-141997-03-11-3
    227921993-06-091993-06-06-3

    3 rows

    The goods were received before they were shipped, which is impossible. 104 lines are like this: a data-entry error. The calculation is correct; the data is not. Chapter 17 asks whether such rows should be fixed, flagged or left alone.

    貨物在發出之前已經收到,這是不可能的。有 104 行是這樣,屬於數據輸入錯誤。計算本身沒有錯,錯的是數據。第 17 章會討論這類行應該修正、標記還是保留不理。

  3. Write a CASE that labels each line of order 34 “on time” if it was received by its commit date and “late” otherwise. The data runs to 1998-08-02. Is the result right?

    寫一個 CASE,如果第 34 號訂單的某一行在承諾日期或之前收到,就標為「on time」,否則標為「late」。數據截至 1998-08-02。結果正確嗎?

    Answer 答案
    l_linenumberl_commitdatel_receiptdatedelivery
    11998-09-14NULLlate
    21998-10-16NULLlate
    31998-09-20NULLlate

    3 rows

    No. None of the lines has been received yet, and the earliest commit date, 1998-09-14, is after the data ends, so none of them can be late. The receipt date is NULL, the condition is not true, and ELSE labels every line “late”. 1,874 lines in the table have no receipt date. Chapter 5 shows how to handle them.

    不正確。這些行都尚未收貨,而最早的承諾日期 1998-09-14 在數據截止日之後,所以沒有一行可能遲到。收貨日期是 NULL,條件不成立,於是 ELSE 把每一行都標為「late」。表中有 1,874 行沒有收貨日期,第 5 章會說明如何處理。

Sources 資料來源

  • Practice data derived from the TPC-H benchmark of the Transaction Processing Performance Council, generated with tpchgen-cli at scale factor 0.01. The TPC-H specification’s Query 1 defines the charge on a line as l_extendedprice * (1 - l_discount) * (1 + l_tax).
  • DuckDB, Date functions: date_diff counts partition boundaries; date_sub counts complete intervals.
  • Queries run with DuckDB-WASM. Every result and figure on this page was produced with the same build.

How this tutorial was made: AI Diligence Statement