# 関連レコードの集計

**URL:** <https://community.cybozu.dev/t/topic/118>\
**Category:** kintone 開発相談\
**Created:** [2022 年 9 月 28 日午前 5:26 UTC](https://community.cybozu.dev/t/topic/118 "2022-09-28T05:26:26Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![Legacy\_Account54](https://avatars.discourse-cdn.com/v4/letter/l/3e96dc/32.png) [@Legacy\_Account54](https://community.cybozu.dev/u/Legacy_Account54)\
**Post date:** [2022 年 9 月 28 日午前 5:26 UTC](https://community.cybozu.dev/t/topic/118/1 "2022-09-28T05:26:26Z")

</div>

お世話になっております。

関連レコード集計についてお教えいただければと思います。

条件なしで集計をしたいのですが下記の投稿を参考にして作りましたがうまくいきません。

[https://developer.cybozu.io/hc/ja/articles/203030394-%E9%96%A2%E9%80%A3%E3%83%AC%E3%82%B3%E3%83%BC%E3%83%89%E3%81%AE%E9%A0%85%E7%9B%AE%E3%82%92%E6%9D%A1%E4%BB%B6%E4%BB%98%E3%81%8D%E3%81%A7%E9%9B%86%E8%A8%88](https://community.cybozu.dev/hc/ja/articles/203030394-%E9%96%A2%E9%80%A3%E3%83%AC%E3%82%B3%E3%83%BC%E3%83%89%E3%81%AE%E9%A0%85%E7%9B%AE%E3%82%92%E6%9D%A1%E4%BB%B6%E4%BB%98%E3%81%8D%E3%81%A7%E9%9B%86%E8%A8%88)

仕入小計の下に仕入の請求金額の合計を入れたいです。

レコード条件は受注番号にしています。

よろしくお願いします。

&nbsp;

&nbsp;

&nbsp;

/\*  
&nbsp;\* total related records  
&nbsp;\* Copyright (c) 2022 Cybozu  
&nbsp;\*  
&nbsp;\* Licensed under the MIT License  
\*/  
(() =\> {  
&nbsp; ‘use strict’;

&nbsp; const events = [  
&nbsp; &nbsp; ‘app.record.detail.show’,  
&nbsp; &nbsp; ‘app.record.edit.show’  
&nbsp; ];  
&nbsp; kintone.events.on(events, (event) =\> {  
&nbsp; &nbsp; const clientRecordId = event.recordId;  
&nbsp; &nbsp; const relatedAppId = kintone.app.getRelatedRecordsTargetAppId(‘仕入’);  
&nbsp; &nbsp; const query = `受注番号=“${clientRecordId}” ;  
&nbsp; &nbsp; const outputFields = [‘請求金額’];  
&nbsp; &nbsp; const appUrl = kintone.api.url(‘/k/v1/records’);

&nbsp; &nbsp; const params = {  
&nbsp; &nbsp; &nbsp; ‘app’: relatedAppId,  
&nbsp; &nbsp; &nbsp; ‘query’: query,  
&nbsp; &nbsp; &nbsp; ‘fields’: outputFields  
&nbsp; &nbsp; };

&nbsp; &nbsp; const elementId = ‘totalAmount’;

&nbsp; &nbsp; kintone.api(appUrl, ‘GET’, params, (resp) =\> {  
&nbsp; &nbsp; &nbsp; let amount = 0;  
&nbsp; &nbsp; &nbsp; for (let i = 0; i \< resp.records.length; i++) {  
&nbsp; &nbsp; &nbsp; &nbsp; amount += parseFloat(resp.records[i].請求金額.value);  
&nbsp; &nbsp; &nbsp; }

&nbsp; &nbsp; &nbsp; const divTotalAmount = document.createElement(‘div’);  
&nbsp; &nbsp; &nbsp; const wString = String(amount.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ‘$1,’));  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.fontWeight = ‘bold’;  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.textAlign = ‘right’;  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.fontSize = 12;  
&nbsp; &nbsp; &nbsp; divTotalAmount.innerHTML = `¥${wString}-`;  
&nbsp; &nbsp; &nbsp; kintone.app.record.getSpaceElement(elementId).appendChild(divTotalAmount);  
&nbsp; &nbsp; &nbsp; return event;  
&nbsp; &nbsp; });  
&nbsp; });  
})();

---

<div class="post-metadata">

**Author:** ![Legacy\_Account1177](https://avatars.discourse-cdn.com/v4/letter/l/77aa72/32.png) [@Legacy\_Account1177](https://community.cybozu.dev/u/Legacy_Account1177)\
**Post date:** [2022 年 9 月 28 日午前 6:20 UTC](https://community.cybozu.dev/t/topic/118/2 "2022-09-28T06:20:32Z")

</div>

```
   const query = `受注番号="${clientRecordId}" ;

```

この部分のバッククォートが閉じていないようです。

```
  const query = `受注番号="${clientRecordId}"`;

```

こちらに直せば問題ないはずです。

---

<div class="post-metadata">

**Author:** ![Legacy\_Account54](https://avatars.discourse-cdn.com/v4/letter/l/3e96dc/32.png) [@Legacy\_Account54](https://community.cybozu.dev/u/Legacy_Account54)\
**Post date:** [2022 年 9 月 29 日午前 12:14 UTC](https://community.cybozu.dev/t/topic/118/3 "2022-09-29T00:14:31Z")

</div>

ご回答ありがとうございます。

ただ、集計できませんでした。

参考にした投稿のアプリを使用するとうまくいったのですが、はじめからつくるからアプリを作りました。

うまくいかないのと関係ありますでしょうか。

よろしくお願いします。

&nbsp;

---

<div class="post-metadata">

**Author:** ![Legacy\_Account1177](https://avatars.discourse-cdn.com/v4/letter/l/77aa72/32.png) [@Legacy\_Account1177](https://community.cybozu.dev/u/Legacy_Account1177)\
**Post date:** [2022 年 9 月 29 日午前 2:55 UTC](https://community.cybozu.dev/t/topic/118/4 "2022-09-29T02:55:06Z")

</div>

KAN さま

サンプルのアプリでは動作したということは、新たに作成したアプリの

①関連レコード一覧のフィールドコード（サンプルだと「仕入」となっているもので、フィールド名ではありません）  
②スペースのID（サンプルだと「totalAmount」となっているもので、スペース右上の歯車から設定）  
③クエリ（サンプルだと「`受注番号="${clientRecordId}"` 」となっているもので、これは「参照先アプリの『受注番号』というフィールドコードの値と、現在のアプリの『レコード番号』が一致」していることを意味します）

いずれかに問題があるのではないかと思います。

---

<div class="post-metadata">

**Author:** ![Legacy\_Account54](https://avatars.discourse-cdn.com/v4/letter/l/3e96dc/32.png) [@Legacy\_Account54](https://community.cybozu.dev/u/Legacy_Account54)\
**Post date:** [2022 年 9 月 29 日午前 5:37 UTC](https://community.cybozu.dev/t/topic/118/5 "2022-09-29T05:37:49Z")

</div>

おそらく③の部分に問題があるのだと思います。

条件としては、参照先アプリの「受注番号」と現在のアプリの「受注番号」が一致するとしたいです。

現在のアプリの「受注番号」は文字列でフィールドコードも「受注番号」と設定しています。

&nbsp;

&nbsp;

&nbsp;

---

<div class="post-metadata">

**Author:** ![Legacy\_Account1177](https://avatars.discourse-cdn.com/v4/letter/l/77aa72/32.png) [@Legacy\_Account1177](https://community.cybozu.dev/u/Legacy_Account1177)\
**Post date:** [2022 年 9 月 29 日午前 7:40 UTC](https://community.cybozu.dev/t/topic/118/6 "2022-09-29T07:40:41Z")

</div>

KAN さま

```
 constquery =`受注番号="${clientRecordId}"`;

```

この部分を

```
 constquery =`受注番号="${event.record['受注番号'].value}"`;

```

このように変更すれば可能かと思います。

---

<div class="post-metadata">

**Author:** ![Legacy\_Account54](https://avatars.discourse-cdn.com/v4/letter/l/3e96dc/32.png) [@Legacy\_Account54](https://community.cybozu.dev/u/Legacy_Account54)\
**Post date:** [2022 年 9 月 29 日午前 7:57 UTC](https://community.cybozu.dev/t/topic/118/7 "2022-09-29T07:57:00Z")

</div>

できました！

ありがとうございます。

---

<div class="post-metadata">

**Author:** ![Legacy\_Account54](https://avatars.discourse-cdn.com/v4/letter/l/3e96dc/32.png) [@Legacy\_Account54](https://community.cybozu.dev/u/Legacy_Account54)\
**Post date:** [2022 年 10 月 6 日午前 2:19 UTC](https://community.cybozu.dev/t/topic/118/8 "2022-10-06T02:19:21Z")

</div>

先日はありがとうございました。

何度も申し訳ないのですが、またわからないことがあるので追加で質問があります。

関連レコードごとの合計は出せたのですが、2つの関連レコードの合計を数値フィールドの金額から引く計算をしたいです。

&nbsp;

粗利益の横にスペースフィールドで要素ID totalAmount2 があります。

そちらに反映させたいのですがどこに、どのようなコードを追加すればいいでしょうか。

よろしくお願いいたします。

---

<div class="post-metadata">

**Author:** ![Legacy\_Account1177](https://avatars.discourse-cdn.com/v4/letter/l/77aa72/32.png) [@Legacy\_Account1177](https://community.cybozu.dev/u/Legacy_Account1177)\
**Post date:** [2022 年 10 月 6 日午前 2:43 UTC](https://community.cybozu.dev/t/topic/118/9 "2022-10-06T02:43:51Z")

</div>

KAN さま

＞2つの関連レコードの合計を数値フィールドの金額から引く計算

添付されている画像だと「100,000 - 58,500」という計算でしょうか？  
2つ目の関連レコードの合計をどのようにして求めているかで回答が変わるので、現在のコードを頂いても問題ありませんか？

---

<div class="post-metadata">

**Author:** ![Legacy\_Account54](https://avatars.discourse-cdn.com/v4/letter/l/3e96dc/32.png) [@Legacy\_Account54](https://community.cybozu.dev/u/Legacy_Account54)\
**Post date:** [2022 年 10 月 6 日午前 3:00 UTC](https://community.cybozu.dev/t/topic/118/10 "2022-10-06T03:00:24Z")

</div>

[mls-hashimoto](https://community.cybozu.dev/hc/ja/profiles/385013133091-mls-hashimoto) 様

ご回答の計算式で合っています。

その答えを出したいのですが、現在はスペースフィールドですが、計算フィールドでも構いません。

仕入と外注を同時に計算するコードがわからないので2つコードを使用しています。

わかりづらく申し訳ありません。

&nbsp;

/\*  
&nbsp;\* total related records  
&nbsp;\* Copyright (c) 2022 Cybozu  
&nbsp;\*  
&nbsp;\* Licensed under the MIT License  
\*/  
(() =\> {  
&nbsp; ‘use strict’;

&nbsp; const events = [  
&nbsp; &nbsp; ‘app.record.detail.show’,  
&nbsp; &nbsp; ‘app.record.edit.show’  
&nbsp; ];  
&nbsp; kintone.events.on(events, (event) =\> {  
&nbsp; &nbsp; const clientRecordId = event.recordId;  
&nbsp; &nbsp; const relatedAppId = kintone.app.getRelatedRecordsTargetAppId(‘仕入’);  
&nbsp; &nbsp; const query = `受注番号="${event.record['受注番号'].value}"`;  
&nbsp; &nbsp; const outputFields = [‘請求金額’];  
&nbsp; &nbsp; const appUrl = kintone.api.url(‘/k/v1/records’);

&nbsp; &nbsp; const params = {  
&nbsp; &nbsp; &nbsp; ‘app’: relatedAppId,  
&nbsp; &nbsp; &nbsp; ‘query’: query,  
&nbsp; &nbsp; &nbsp; ‘fields’: outputFields  
&nbsp; &nbsp; };

&nbsp; &nbsp; const elementId = ‘totalAmount’;

&nbsp; &nbsp; kintone.api(appUrl, ‘GET’, params, (resp) =\> {  
&nbsp; &nbsp; &nbsp; let amount = 0;  
&nbsp; &nbsp; &nbsp; for (let i = 0; i \< resp.records.length; i++) {  
&nbsp; &nbsp; &nbsp; &nbsp; amount += parseFloat(resp.records[i].請求金額.value);  
&nbsp; &nbsp; &nbsp; }

&nbsp; &nbsp; &nbsp; const divTotalAmount = document.createElement(‘div’);  
&nbsp; &nbsp; &nbsp; const wString = String(amount.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ‘$1,’));  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.fontWeight = ‘bold’;  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.textAlign = ‘right’;  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.fontSize = 12;  
&nbsp; &nbsp; &nbsp; divTotalAmount.innerHTML = `¥${wString}-`;  
&nbsp; &nbsp; &nbsp; kintone.app.record.getSpaceElement(elementId).appendChild(divTotalAmount);  
&nbsp; &nbsp; &nbsp; return event;  
&nbsp; &nbsp; });  
&nbsp; });  
})();

&nbsp;

* * *

/\*  
&nbsp;\* total related records  
&nbsp;\* Copyright (c) 2022 Cybozu  
&nbsp;\*  
&nbsp;\* Licensed under the MIT License  
\*/  
(() =\> {  
&nbsp; ‘use strict’;

&nbsp; const events = [  
&nbsp; &nbsp; ‘app.record.detail.show’,  
&nbsp; &nbsp; ‘app.record.edit.show’  
&nbsp; ];  
&nbsp; kintone.events.on(events, (event) =\> {  
&nbsp; &nbsp; const clientRecordId = event.recordId;  
&nbsp; &nbsp; const relatedAppId = kintone.app.getRelatedRecordsTargetAppId(‘外注’);  
&nbsp; &nbsp; const query = `受注番号_0="${event.record['受注番号'].value}"`;  
&nbsp; &nbsp; const outputFields = [‘請求金額’];  
&nbsp; &nbsp; const appUrl = kintone.api.url(‘/k/v1/records’);

&nbsp; &nbsp; const params = {  
&nbsp; &nbsp; &nbsp; ‘app’: relatedAppId,  
&nbsp; &nbsp; &nbsp; ‘query’: query,  
&nbsp; &nbsp; &nbsp; ‘fields’: outputFields  
&nbsp; &nbsp; };

&nbsp; &nbsp; const elementId = ‘totalAmount1’;

&nbsp; &nbsp; kintone.api(appUrl, ‘GET’, params, (resp) =\> {  
&nbsp; &nbsp; &nbsp; let amount = 0;  
&nbsp; &nbsp; &nbsp; for (let i = 0; i \< resp.records.length; i++) {  
&nbsp; &nbsp; &nbsp; &nbsp; amount += parseFloat(resp.records[i].請求金額.value);  
&nbsp; &nbsp; &nbsp; }

&nbsp; &nbsp; &nbsp; const divTotalAmount = document.createElement(‘div’);  
&nbsp; &nbsp; &nbsp; const wString = String(amount.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ‘$1,’));  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.fontWeight = ‘bold’;  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.textAlign = ‘right’;  
&nbsp; &nbsp; &nbsp; divTotalAmount.style.fontSize = 12;  
&nbsp; &nbsp; &nbsp; divTotalAmount.innerHTML = `¥${wString}-`;  
&nbsp; &nbsp; &nbsp; kintone.app.record.getSpaceElement(elementId).appendChild(divTotalAmount);  
&nbsp; &nbsp; &nbsp; return event;  
&nbsp; &nbsp; });  
&nbsp; });  
})();

---

<div class="post-metadata">

**Author:** ![Legacy\_Account1177](https://avatars.discourse-cdn.com/v4/letter/l/77aa72/32.png) [@Legacy\_Account1177](https://community.cybozu.dev/u/Legacy_Account1177)\
**Post date:** [2022 年 10 月 6 日午前 4:34 UTC](https://community.cybozu.dev/t/topic/118/11 "2022-10-06T04:34:08Z")

</div>

2つ分のスクリプトをまとめました。以下でお試し下さい。

```
(() => {
  'use strict';

  kintone.events.on([
  'app.record.detail.show', 'app.record.edit.show'
], async (event) => {
  let record = event.record;
  let relatedTables = [
    {
      body: {
        app: kintone.app.getRelatedRecordsTargetAppId('仕入'),
        query: `受注番号 = "${record['受注番号'].value}"`,
        fields: ['請求金額']
      },
      spaceId: 'totalAmount'
    },
    {
      body: {
        app: kintone.app.getRelatedRecordsTargetAppId('外注'),
        query: `受注番号_0 = "${record['受注番号'].value}"`,
        fields: ['請求金額']
      },
      spaceId: 'totalAmount1'
    }
  ];
  let billingAmount = Number(record['請求金額'].value);

    for (let table in relatedTables) {
    await kintone.api(kintone.api.url('/k/v1/records', true), 'GET', relatedTables[table].body).then((resp) => {
      let amount = resp.records.reduce((prev, record) => {
        return prev += Number(record['請求金額'].value);
      }, 0);

        billingAmount -= amount;

        let divTotalAmount = document.createElement('div');
      let wString = String(amount.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'));

        divTotalAmount.style.fontWeight = 'bold';
      divTotalAmount.style.textAlign = 'right';
      divTotalAmount.style.fontSize = 12;
      divTotalAmount.innerHTML = `¥${wString}-`;
      kintone.app.record.getSpaceElement(relatedTables[table].spaceId).appendChild(divTotalAmount);
    });
  };

    let divBillingAmount = document.createElement('div');
  let wString = String(billingAmount.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'));

    divBillingAmount.style.fontWeight = 'bold';
  divBillingAmount.style.textAlign = 'right';
  divBillingAmount.style.fontSize = 12;
  divBillingAmount.innerHTML = `¥${wString}-`;
  kintone.app.record.getSpaceElement('totalAmount2').appendChild(divBillingAmount);

    return event;
});
})();

```

---

<div class="post-metadata">

**Author:** ![Legacy\_Account54](https://avatars.discourse-cdn.com/v4/letter/l/3e96dc/32.png) [@Legacy\_Account54](https://community.cybozu.dev/u/Legacy_Account54)\
**Post date:** [2022 年 10 月 6 日午前 5:23 UTC](https://community.cybozu.dev/t/topic/118/12 "2022-10-06T05:23:39Z")

</div>

できました！

一つにまとめていただきありがとうございます！

&nbsp;

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex015/uploads/cybozu/original/1X/d5c841c3c5a6cb66eed514001c1b45147c9e1f4f.png) [@system](https://community.cybozu.dev/u/system)\
**Post date:** [2024 年 6 月 6 日午前 1:00 UTC](https://community.cybozu.dev/t/topic/118/13 "2024-06-06T01:00:44Z")

</div>

クローズされました: 2024 年 6 月 6 日午前 1:00 UTC

このトピックはベストアンサーに選ばれた返信から 3 日が経過したので自動的にクローズされました。新たに返信することはできません。
