등급별 가격 할인 계산
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
코딩 수준: 초급
기간: 10분
프로젝트 유형: 맞춤 함수
목표
- 솔루션의 기능을 이해합니다.
- 솔루션 내에서 Apps Script 서비스가 하는 역할을 이해합니다.
- 스크립트를 설정합니다.
- 스크립트를 실행합니다.
이 솔루션 정보
고객에게 단계별 가격 시스템을 제공하는 경우 이 맞춤 함수를 사용하면 가격의 할인 금액을 더 쉽게 계산할 수 있습니다.
기본 제공 함수 SUMPRODUCT
를 사용하여 단계별 가격 책정을 계산할 수 있지만 SUMPRODUCT
를 사용하는 것은 이 솔루션의 맞춤 함수보다 더 복잡하고 유연성이 떨어집니다.

작동 방식
단계별 가격 책정 모델은 구매한 수량에 따라 상품 또는 서비스 비용이 낮아지는 것을 의미합니다.
예를 들어 0~500달러 범위로 10% 할인되는 등급과 501~1,000달러 범위로 20% 할인되는 등급이 있다고 가정해 보겠습니다.
할인을 계산해야 하는 총 가격이 $700인 경우 스크립트에서 처음 $500에 10% 를 곱하고 나머지 $200에 20%를 곱하여 총 할인이 $90가 됩니다.
지정된 총 가격에 대해 스크립트는 등급 가격표에서 지정된 등급을 통해 루프합니다. 총 가격 중 등급에 속하는 부분은 해당 등급의 연결된 백분율 값과 곱해집니다. 결과는 각 등급의 계산 합계입니다.
Apps Script 서비스
이 솔루션은 다음 서비스를 사용합니다.
- 스프레드시트 서비스: 지정된 값을 가져와 각 등급의 할인율을 곱할 값의 부분을 계산합니다.
기본 요건
이 샘플을 사용하려면 다음 기본 요건이 필요합니다.
- Google 계정 (Google Workspace 계정의 경우 관리자 승인이 필요할 수 있음)
- 인터넷에 액세스할 수 있는 웹브라우저
스크립트 설정
아래 버튼을 클릭하여 등급별 요금 맞춤 함수 스프레드시트의 사본을 만드세요. 이 솔루션의 Apps Script 프로젝트는 스프레드시트에 첨부되어 있습니다.
사본 만들기
스크립트 실행
- 복사한 스프레드시트의 16번째 행에 있는 표에는 Software as a Service (SaaS) 제품의 샘플 가격 계산이 표시되어 있습니다.
- 할인 금액을 계산하려면
C20
셀에 =tierPrice(C19,$B$3:$D$6)
을 입력합니다. 최종 가격이 C21
셀에 업데이트됩니다. 소수점 쉼표를 사용하는 지역에 있는 경우 대신 =tierPrice(C19;$B$3:$D$6)
를 입력해야 할 수 있습니다.
코드 검토
이 솔루션의 Apps Script 코드를 검토하려면 아래의 소스 코드 보기를 클릭하세요.
수정사항
필요에 따라 맞춤 함수를 원하는 만큼 수정할 수 있습니다. 아래는 맞춤 함수 결과를 수동으로 새로고침하는 선택적 추가 기능입니다.
캐시된 결과 새로고침
내장 함수와 달리 Google은 성능을 최적화하기 위해 사용자 정의 함수를 캐시합니다. 따라서 계산되는 값과 같은 맞춤 함수 내에서 항목을 변경해도 즉시 업데이트가 강제되지 않을 수 있습니다. 함수 결과를 수동으로 새로고침하려면 다음 단계를 따르세요.
- 삽입
> 체크박스를 클릭하여 빈 셀에 체크박스를 추가합니다.
- 체크박스가 있는 셀을 맞춤 함수의 추가 매개변수로 추가합니다. 예를 들어
D20
셀에 체크박스를 추가하는 경우 C20
셀의 tierPrice()
함수를 =tierPrice(C19,$B$3:$D$6,D20)
로 업데이트합니다.
- 체크박스를 선택하거나 선택 해제하여 맞춤 함수 결과를 새로고침합니다.
참여자
이 샘플은 Google Developer Expert의 도움을 받아 Google에서 유지관리합니다.
다음 단계
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-31(UTC)
[null,null,["최종 업데이트: 2025-08-31(UTC)"],[[["\u003cp\u003eThis Google Apps Script custom function simplifies tiered pricing calculations in Google Sheets, offering a more straightforward approach than using \u003ccode\u003eSUMPRODUCT\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe function calculates discounts by iterating through pricing tiers, applying the corresponding percentage discount to the portion of the total price falling within each tier.\u003c/p\u003e\n"],["\u003cp\u003eTo use the function, you need to provide the total price and a table specifying the pricing tiers, start and end values, and discount percentages.\u003c/p\u003e\n"],["\u003cp\u003eThe script utilizes the Spreadsheet service to access and process data within the sheet.\u003c/p\u003e\n"],["\u003cp\u003eYou can manually refresh the custom function's results by adding a checkbox and including its cell reference as an additional parameter in the function call.\u003c/p\u003e\n"]]],[],null,["# Calculate a tiered pricing discount\n\n**Coding level** : Beginner \n\n**Duration** : 10 minutes \n\n**Project type** : [Custom function](/apps-script/guides/sheets/functions)\n\nObjectives\n----------\n\n- Understand what the solution does.\n- Understand what the Apps Script services do within the solution.\n- Set up the script.\n- Run the script.\n\nAbout this solution\n-------------------\n\nIf you offer a tiered pricing system for your customers, this custom function\nmakes it easier to calculate the discount amounts for your prices.\n\nThough you could use the built-in function `SUMPRODUCT` to make a tiered pricing\ncalculation, using `SUMPRODUCT` is more complex and less flexible than this\nsolution's custom function.\n\n### How it works\n\nA tiered pricing model means that the cost of goods or services goes down\nbased on the quantity purchased.\n\nFor example, imagine you have two tiers, one that ranges from $0-$500 and is\ndiscounted by 10% and one that ranges from $501-$1,000 and is discounted by 20%.\nIf the total price you need to calculate a discount for is $700, the script\nmultiplies\nthe first $500 by 10% and the remaining $200 by 20%, for a total discount of\n$90.\n\nFor a given total price, the script loops through the specified tiers in the\ntier pricing table. For each portion of the total price that falls\nwithin a tier, that portion is multiplied by the tier's associated percent\nvalue. The result is the sum of each tier's calculation.\n\n### Apps Script services\n\nThis solution uses the following service:\n\n- [Spreadsheet service](/apps-script/reference/spreadsheet)--Takes the given value and calculates what portion of the value to multiply by each tier's percent discount.\n\nPrerequisites\n-------------\n\nTo use this sample, you need the following prerequisites:\n\n- A Google Account (Google Workspace accounts might require administrator approval).\n- A web browser with access to the internet.\n\nSet up the script\n-----------------\n\nClick the button below to make a copy of the **Tier pricing custom function**\nspreadsheet. The Apps Script project for\nthis solution is attached to the spreadsheet.\n\n[Make a copy](https://docs.google.com/spreadsheets/d/13X-3pz8P_sfAyNqUJrGe0HdgzKARIMxC6Y6xZDAF7M0/copy)\n\nRun the script\n--------------\n\n1. In your copied spreadsheet, the table at row 16 shows a sample price calculation for a Software as a Service (SaaS) product.\n2. To calculate the discount amount, in cell `C20`, enter `=tierPrice(C19,$B$3:$D$6)`. The final price updates in cell `C21`. If you're in a location that uses decimal commas, you might need to enter `=tierPrice(C19;$B$3:$D$6)` instead.\n\nReview the code\n---------------\n\nTo review the Apps Script code for this solution, click **View source code**\nbelow: \n\n#### View source code\n\n### Code.gs\n\n\u003cbr /\u003e\n\nsolutions/custom-functions/tier-pricing/Code.js \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/solutions/custom-functions/tier-pricing/Code.js) \n\n```javascript\n// To learn how to use this script, refer to the documentation:\n// https://developers.google.com/apps-script/samples/custom-functions/tier-pricing\n\n/*\nCopyright 2022 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Calculates the tiered pricing discount. \n * \n * You must provide a value to calculate its discount. The value can be a string or a reference\n * to a cell that contains a string.\n * You must provide a data table range, for example, $B$4:$D$7, that includes the \n * tier start, end, and percent columns. If your table has headers, don't include\n * the headers in the range.\n * \n * @param {string} value The value to calculate the discount for, which can be a string or a \n * reference to a cell that contains a string.\n * @param {string} table The tier table data range using A1 notation.\n * @return number The total discount amount for the value.\n * @customfunction\n * \n */\nfunction tierPrice(value, table) {\n let total = 0;\n // Creates an array for each row of the table and loops through each array.\n for (let [start, end, percent] of table) {\n // Checks if the value is less than the starting value of the tier. If it is less, the loop stops.\n if (value \u003c start) {\n break;\n }\n // Calculates the portion of the value to be multiplied by the tier's percent value.\n let amount = Math.min(value, end) - start;\n // Multiplies the amount by the tier's percent value and adds the product to the total.\n total += amount * percent;\n }\n return total;\n}\n```\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nModifications\n-------------\n\nYou can edit the custom function as much as you'd like to fit your needs. Below\nis an optional addition to manually refresh custom function results. \n\n#### Refresh cached results\n\n\nUnlike built-in functions, Google caches custom functions to optimize\nperformance. Therefore, if you change something within your custom\nfunction, such as a value that's being calculated, it might not immediately\nforce an update. To refresh the function result manually, take the following\nsteps:\n\n1. Add a checkbox to an empty cell by clicking **Insert** \\\u003e **Checkbox**.\n2. Add the cell that has the checkbox as an extra parameter of the custom function. For example, if you add a checkbox to cell `D20`, update the `tierPrice()` function in cell `C20` to `=tierPrice(C19,$B$3:$D$6,D20)`.\n3. Check or uncheck the checkbox to refresh the custom function results.\n\nContributors\n------------\n\nThis sample is maintained by Google with the help of Google Developer Experts.\n\nNext steps\n----------\n\n- [Custom functions in Google Sheets](/apps-script/guides/sheets/functions)\n- [Extending Google Sheets](/apps-script/guides/sheets)"]]