If the total or average check in an AI-generated report differs from the source data, first find the rows used in the calculation. Joining tables can repeat the same order multiple times, averaging by branch can remove each branch’s weight, and a missing amount can change the denominator. Asking the model to “recalculate more carefully” does not automatically fix these rules.
This FAQ is for the analyst, report owner, and manager whose AI helps prepare SQL queries for a database. SQL is a query language; this article covers totals, order counts, average order value, and shares. Preparing Excel files, configuring an agent, and accounting revenue recognition require separate solutions.
This material was prepared by Vladimir Lomtev’s AI studio; the next-to-last section describes the publisher’s services. PostgreSQL 18 documentation was checked on November 15, 2026. All numeric examples below are fictional. The SQL blocks are suggested examples for the schema described here: they were not run in PostgreSQL or on company data. This material does not measure the accuracy of any AI model.
Contents
- Where should you start if AI and your standard report show different numbers?
- Why did JOIN increase the order total?
- Can duplicate counting be removed with SUM DISTINCT?
- Why does COUNT show more orders than actually exist?
- Why is the average of averages not equal to the overall average check?
- How do NULLs and zeros change the result?
- Why does the company-wide share differ from the average of department percentages?
- Can the difference be explained by rounding or the date?
- What should you tell the AI to fix the calculation instead of getting a new number at random?
Where should you start if AI and your standard report show different numbers?
Compare the row set, the unit of calculation, and the formula, then look for an arithmetic mismatch. The unit of calculation, or granularity, answers the question: what does one record represent — an order, an item line, a payment, or a customer. If one report treats a row as an order and another as an item line, the same column name “Amount” does not make the calculations comparable.
Ask the query author for a small, permitted slice of exactly the data that went into the aggregation. Aggregation is the reduction of many values into a final result, such as a total or an average. In SQL, the row set is built step by step through FROM, joins, and filters; grouping works with the resulting set. This is the documented order in which a table expression is processed: PostgreSQL: Table Expressions.
| Observed discrepancy | Working hypothesis | What to compare |
|---|---|---|
| The total increased after product attributes were added | The order was repeated when joined with items | Order IDs before and after the join |
| There are more orders than in CRM | Item rows were counted | Rows and unique order IDs |
| The overall average order value differs from the branch average | Branches were given equal weight | The total and order count for each branch |
| The average changed after “filling in blanks” | Missing values were turned into zeros | The number of known amounts and the fill rule |
| Daily totals differ | A different date or time zone was selected | Date field, period boundaries, and time zone |
These are hypotheses for troubleshooting, not a diagnosis from one screenshot. If the SQL and its actual result match the agreed calculation, but the number in the AI’s text answer is different, check the result transfer into the answer. If the SQL result itself differs, the query or metric definition needs to be fixed.
Why did JOIN increase the order total?
JOIN connects rows from tables. If one order corresponds to multiple item lines, the order total can appear multiple times in the result. According to PostgreSQL documentation, INNER JOIN creates a row for each matching combination of records: join rules.
Sample input data: in the orders table there are two records. Order A costs 1,000 RUB, order B costs 3,000 RUB. In the order_items table, A has two items and B has one. orders.id is unique, and order_items.order_id references the order.
| Row after the join | Amount from orders |
|---|---|
| A — item 1 | 1,000 RUB |
| A — item 2 | 1,000 RUB |
| B — item 1 | 3,000 RUB |
| Total of three rows | 5,000 RUB |
For the two original orders, the total is 4,000 RUB. The 1,000 RUB difference came from repeating A. Below is an example query with this error:
SELECT SUM(o.total_rub)
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.id;
If the task is to add up the totals of all orders, in this example it is enough to use orders: there is no need to join items. If you only need orders that contain a product in the service category, you can use an existence check for a matching item:
SELECT SUM(o.total_rub)
FROM orders AS o
WHERE EXISTS (
SELECT 1
FROM order_items AS i
WHERE i.order_id = o.id
AND i.category = 'service'
);
EXISTS answers whether at least one row was found; multiple matching items do not multiply the outer order. This behavior is described in PostgreSQL: Subquery Expressions. This calculates the full total of orders with a service, including the other items. To total only the services themselves, you need the sums of the corresponding line items and a different formula. Mixing up these tasks will again produce the wrong business answer.
Can repeated counting be removed with SUM DISTINCT?
Do not use uniqueness of the sum as a substitute for uniqueness of the order. SUM(DISTINCT total_rub) keeps different expression values, not different orders. This follows from the definition of DISTINCT inside the aggregate: PostgreSQL: Aggregate Expressions.
Counterexample: two independent orders C and D cost 1,000 ₽ each. Their total is 2,000 ₽. But the set of unique sums contains only one value, 1,000, so SUM(DISTINCT total_rub) will return 1,000 ₽. On the earlier orders A and B, this trick would accidentally hide duplication; on identical receipts, it loses a real sale.
Duplicate removal should be based on entity identity and the source of the duplicate. To calculate by orders, restore one record per order key or use an existence condition if the line items are needed only for filtering. If the same order key already has different amounts in the source, first determine whether the records are versions, payments, or a loading error. Picking one amount arbitrarily will hide this problem.
Why does COUNT show more orders than actually exist?
COUNT(*) counts rows. COUNT(column) counts rows with a non-null value in that column, while COUNT(DISTINCT column) counts distinct non-null values. These are different questions asked of the same dataset: COUNT documentation.
In the example with orders A and B, the join returns three rows, but there are two unique order IDs. So COUNT(*) returns 3, while COUNT(DISTINCT o.id) returns 2. The second expression answers the question about the number of orders if id really is their key in the system being considered.
However, the correct order count does not fix the neighboring sum. The expression SUM(o.total_rub) / COUNT(DISTINCT o.id) on the same join would divide the incorrect 5,000 ₽ by 2 and give 2,500 ₽ per order. For the original two orders, the average check is 4,000 / 2 = 2,000 ₽. The numerator and denominator must refer to the same consistent set.
A separate case is LEFT JOIN, which preserves an order even when there are no matching line items. In its result row, the item columns will be NULL, meaning the value is missing. Then COUNT(*) counts the preserved row, while COUNT(i.id) does not count it. The rule for adding such rows is described in the LEFT OUTER JOIN documentation.
Why is the average of averages not equal to the overall average check?
Branches can have different numbers of orders. The average of their averages gives each branch equal weight, while the task “average check across all orders” gives each order equal weight.
Take a separate training dataset not related to orders A and B:
| Branch | Number of orders | Order total | Average check |
|---|---|---|---|
| North | 1 | 1,000 ₽ | 1,000 ₽ |
| South | 3 | 9,000 ₽ | 3,000 ₽ |
| Total | 4 | 10,000 ₽ | 2,500 ₽ |
The average of the two averages is (1,000 + 3,000) / 2 = 2,000 ₽. The overall average check is (1,000 + 9,000) / (1 + 3) = 2,500 ₽. If only precomputed grouped metrics are available, keep the total and the number of orders together. With rounded averages and no weights, the original overall result may be impossible to recover.
Equal branch weighting can make sense on its own — for example, when that is exactly what the departmental comparison task calls for. But such a metric should be called the branch average. For the overall average check, give the AI this instruction: “Divide the total amount of qualifying orders by their total count; do not average the groups’ average checks.”
How do NULL and zeros change the result?
A missing amount and a known zero amount mean different states. PostgreSQL excludes NULL from the inputs to AVG and SUM; the sum of an empty set returns NULL, not zero automatically. These rules are documented in the aggregate function documentation.
For the values 1,000, NULL, 0 two sums are known. The average of the known values is ₽500. If you replace the missing value with zero before averaging, you get 1,000 / 3 ≈ ₽333.33. That is already an assumption about an unknown operation, not a cosmetic formatting choice.
Ask the AI to output the number of rows and the number of known sums separately. If the metric requires a complete set, a missing value may mean the result cannot be published yet. If the data owner confirms that the missing value really encodes a zero amount, the replacement can be built into the calculation rule. The decision depends on the meaning of the field.
Also distinguish between no matching transactions and no data loaded for the period. Showing zero instead of an empty result does not prove the data arrived in full. That requires a separate source readiness flag.
Why does the company-wide share differ from the average of department percentages?
Shares also have weights: the denominator defines them. If departments process different numbers of requests, the average of two percentages and the share of successful requests out of all requests answer different questions.
In the example, department X completed 100 out of 1,000 requests — 10%. Department Y completed 90 out of 300 — 30%. The average of the percentages is 20%, but the overall share is 190 / 1,300 × 100 ≈ 14.62%. In the overall formula, the numerators and their corresponding denominators are added together. Here the categories are assumed to be non-overlapping, with the same definition of a successful request.
If one request appears in both departments, first decide whether you are counting unique requests or department participation in processing. You cannot simply add those denominators without qualification. If a group’s denominator is zero, its percentage needs a separate display rule; zero percent and an undefined share are not the same.
For SQL, also check the division type. PostgreSQL discards the fractional part when dividing integers, so you cannot casually write a share as the ratio of two integer counters. Use a decimal type, for example by casting the numerator to numeric before division, and handle a zero denominator: PostgreSQL mathematical operators.
Could the discrepancy be explained by rounding or the date?
Yes, but first separate a small presentation difference from a change in the calculation itself. Each explanation should map to a specific mechanism.
Rounding individual rows and rounding the total sum can produce different results. For example, three sample values of ₽0.335, rounded to two decimals each, become ₽0.34, for a total of ₽1.02. Their exact sum of ₽1.005, rounded once to two decimals, becomes ₽1.01. This example assumes the round-half-away-from-zero rule. In PostgreSQL, this applies to numeric; the real and double precision types have approximate representation, and rounding rules may differ. See Numeric Types.
Switching to numeric helps define decimal arithmetic explicitly, but it does not decide the rounding moment for you. Agree whether line items, documents, or only the final metric are rounded. Even a precise type with a fixed scale can round a value on write.
For the period, check the event field separately: order creation, payment, or shipment. Then compare time zones and boundaries. For example, November 14, 2026 at 23:30 UTC is November 15 at 02:30 in UTC+03:00. One transaction can fall on different calendar days. PostgreSQL converts the output of timestamp with time zone to the current session time zone; the input time zone is not preserved inside that value: Date/Time Types.
In the proposed period rule, use the start as inclusive and the start of the next period as exclusive, in the explicitly chosen time zone. That way adjacent intervals can be defined without a shared boundary point. This is a recommendation for framing the task; the exact SQL depends on the type and meaning of the date field.
What should I tell the AI so it fixes the calculation instead of producing a random new number?
Provide the table structure, keys, and the definition of the metric. Ask it to first show how the row set is formed, and only then suggest a fix. The names orders and order_items do not prove that one row in each means what the model expects.
Below is a suggested prompt for the AI for a fictional schema. This is a task template; its result on a specific model has not been verified:
Analyze the discrepancy in average order value in the SQL I will attach.
orders: id — unique order key, total_rub — known full-order amount in rubles. One record = one order.
order_items: order_id — reference to orders.id, category — category.
An order can have multiple items.
I need the average order value of full orders that have at least one service item.
All amounts are in the same currency. We are using the already agreed set of orders;
do not add any additional period or status filters for now.
Show which rows the JOIN creates and where the order amount is duplicated.
Suggest a way to select without duplicating orders.
Output the number of orders, the sum, and the average order value formula separately.
Do not calculate the sum of only service items: I need the full order amount.
If the schema or the meaning of the metric is ambiguous, list the questions.
Do not execute queries or change data.
To continue, attach the actual SQL and a small allowed example with keys. If you cannot show the original query, ask to explain the principle on synthetic rows. Before executing the proposed SQL, the analyst should verify the schema, available data, and meaning of the result; the words “do not change” by themselves do not define technical permissions.
For recurring reports, it helps to lock down the formula and allowed relationships in a governed data model. This next level is described in the article on a semantic layer for AI analytics. If the discrepancy appeared earlier while reading the book, return to the material on Excel formulas and sheets for AI.
How the studio helps connect AI with company calculations
Vladimir Lomtev’s AI studio works on data preparation, MVP development, integration, and testing of AI with business systems. For analytical reports, this work may include:
- preparing tables with aligned keys, grain, and metric definitions;
- developing and testing an MVP in which AI calls the agreed calculation and returns an explanation of its result;
- integrating such a process with enterprise data sources.
The first step is to choose one report with a discrepancy, name its owner, the current calculation method, the sources and access constraints, and define the required result. For example, agree on what exactly counts as an order and what average order value should be produced on the permitted set of records. Discuss the task.
Conclusion: how to localize the discrepancy
Start with one disputed number and the rows it came from. Find key duplication after the join, verify the overall population of the numerator and denominator, distinguish missing values from zero, then analyze rounding and the period. The fix should explain the difference with specific records or a calculation rule. After that, move the agreed result into the AI report text.



