You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对文档中bills数组的total按id去重求和(DISTINCT SUM)

How to Calculate DISTINCT SUM of total by id

Hey there! Let's tackle this problem where you need to sum the total values but only count each unique id once—even if it appears multiple times in your data. Your example expects 30.0 (20.0 for id "1" + 10.0 for id "2"), and here are a couple of practical ways to get that result depending on your environment:

JavaScript Solution

If you're handling this data in JavaScript (like frontend code or Node.js), you can first deduplicate entries by id, then sum the unique total values:

Using Map (cleaner for unique key handling)

const bills = [ { id: "1", total: 20.0 }, { id: "1", total: 20.0 }, { id: "2", total: 10.0 } ];

// Step 1: Keep only one entry per unique id
const uniqueBills = new Map();
bills.forEach(bill => {
  // Skip if the id is already in the map
  if (!uniqueBills.has(bill.id)) {
    uniqueBills.set(bill.id, bill.total);
  }
});

// Step 2: Sum all unique total values
const distinctSum = Array.from(uniqueBills.values()).reduce((acc, currTotal) => acc + currTotal, 0);

console.log(distinctSum); // Outputs 30.0

Using a Plain Object (simpler alternative)

const bills = [ { id: "1", total: 20.0 }, { id: "1", total: 20.0 }, { id: "2", total: 10.0 } ];

constUniqueEntries = {};
bills.forEach(bill => {
  if (!uniqueEntries[bill.id]) {
    uniqueEntries[bill.id] = bill.total;
  }
});

const distinctSum = Object.values(uniqueEntries).reduce((sum, total) => sum + total, 0);
console.log(distinctSum); // Outputs 30.0

SQL Solution

If this data lives in a database, you can use a subquery to fetch unique id + total pairs first, then sum those values:

SELECT SUM(total) AS distinct_total_sum
FROM (
    -- Subquery returns only one entry per unique id
    SELECT DISTINCT id, total
    FROM your_bills_table
) AS unique_bills;

This query creates a temporary set of unique entries, then sums the total column from that set—exactly what you need to get the 30.0 result.

内容的提问来源于stack exchange,提问作者Chinh Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:27:22