

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Lieferdaten des Verkäufers werden eingespeist AWS Marketplace
<a name="data-feed-service"></a>

AWS Marketplace bietet Datenfeeds als Mechanismus zum Senden strukturierter up-to-date Produkt- und Kundeninformationen von AWS Marketplace Systemen an Amazon S3 S3-Buckets des Verkäufers für ETL (Extrahieren, Transformieren und Laden) zwischen unternehmenseigenen Business Intelligence-Tools. Daten-Feeds sammeln Dateien mit kommagetrennten Werten (CSV) und senden sie an einen verschlüsselten Amazon S3 S3-Bucket, den Sie bereitstellen. Datenfeeds werden innerhalb eines Tages generiert und enthalten Daten von 24 Stunden des Vortags. Die folgenden Abschnitte bieten einen Überblick über Datenfeeds und erklären, wie Sie auf sie zugreifen und sie verwenden können. In den nachfolgenden Abschnitten werden die einzelnen Datenfeeds beschrieben. 

Die Transaktionsdaten werden in einer bitemporalen Struktur bereitgestellt und angehängt, sodass Verkäufer Daten entlang von zwei Zeitlinien mit Zeitstempeln für beide speichern und abfragen können
+ Gültige Zeit: wann eine Tatsache in der realen Welt eingetreten ist („was Sie wussten“)
+ Systemzeit: wann diese Tatsache in der Datenbank aufgezeichnet wurde („als Sie es wussten“).

Datenfeeds werden täglich um Mitternacht UTC nach einer Aktualisierung vom Vortag bereitgestellt, die 24 Stunden an Daten vom Vortag enthält. Ein Update kann so definiert werden, dass ein Kunde ein Abonnement abschließt, einem Kunden eine Rechnung ausgestellt wird oder die Zahlung AWS auszahlt.

**Topics**
+ [

# Speicherung und Struktur von AWS Marketplace Datenfeeds
](data-feed-details.md)
+ [

# Zugriff auf Datenfeeds
](data-feed-accessing.md)
+ [

# Sammeln und Analysieren von Daten mit Datenfeeds
](data-feed-using.md)
+ [

# Übersicht über Datenfeed-Tabellen
](data-feed-joining.md)
+ [

# Beispiele für Datenfeed-Abfragen
](data-feed-full-examples.md)
+ [

# Datenfeeds
](data-feeds.md)

# Speicherung und Struktur von AWS Marketplace Datenfeeds
<a name="data-feed-details"></a>

AWS Marketplace bietet Datenfeeds als Mechanismus zum Senden strukturierter up-to-date Produkt- und Kundeninformationen von AWS Marketplace Systemen an Amazon S3 S3-Buckets des Verkäufers für ETL (Extrahieren, Transformieren und Laden) zwischen unternehmenseigenen Business Intelligence-Tools. Dieses Thema enthält weitere Informationen zur Struktur und Speicherung von Datenfeeds.

Daten-Feeds sammeln Dateien mit kommagetrennten Werten (CSV) und senden sie an einen verschlüsselten Amazon S3 S3-Bucket, den Sie bereitstellen. Die CSV-Dateien weisen folgende Merkmale auf:
+ Sie entsprechen den [4180-Standards](https://tools.ietf.org/html/rfc4180).
+ Die Zeichencodierung ist UTF-8 ohne BOM.
+ Kommas werden als Trennzeichen zwischen Werten verwendet.
+ Felder werden durch doppelte Anführungszeichen als Escape-Zeichen umgangen. 
+ `\n` ist das Zeilenvorschubzeichen.
+ Datumsangaben werden in der Zeitzone UTC gemeldet, weisen das Datums- und Zeitformat ISO 8601 auf und sind auf 1 Sekunde genau.
+ Alle Werte für `*_period_start_date` und `*_period_end_date` sind einschließend. Dies bedeutet, dass `23:59:59` der letzte mögliche Zeitstempel für jeden Tag ist. 
+ Allen monetären Feldern wird ein Währungsfeld vorangestellt. 
+ Monetäre Felder verwenden einen Punkt (`.`) als Dezimaltrennzeichen und sie verwenden kein Komma (,) als Tausendertrennzeichen. 

Datenfeeds werden wie folgt generiert und gespeichert:
+ Datenfeeds werden innerhalb eines Tages generiert und enthalten Daten von 24 Stunden des Vortags. 
+ Im Amazon S3 S3-Bucket sind die Datenfeeds im folgenden Format nach Monaten geordnet:

  `bucket-name/data-feed-name_version/year=YYYY/month=MM/data.csv`
+ Wenn die einzelnen täglichen Datenfeeds generiert werden, werden sie an die vorhandene CSV-Datei für diesen Monat angehängt. Wenn ein neuer Monat beginnt, wird für jeden Datenfeed eine neue CSV-Datei generiert. 
+ Informationen in Datenfeeds werden vom 01.01.2010 bis 30.04.2020 (einschließlich) per Backfill ergänzt und stehen in der [CSV-Datei](#data-feed-details) im Unterordner `year=2010/month=01` zur Verfügung.

  Möglicherweise sind Ihnen Fälle aufgefallen, in denen die Datei des aktuellen Monats für einen bestimmten Datenfeed nur Spaltenüberschriften und keine Daten enthält. Dies bedeutet, dass es für diesen Monat keine neuen Einträge für den Feed gab. Dies kann bei Datenfeeds der Fall sein, die seltener aktualisiert werden, wie z. B. beim Produktfeed. In diesen Fällen sind Daten im per Backfill gefüllten Ordner verfügbar. 
+ In Amazon S3 können Sie eine [Amazon S3 S3-Lebenszyklusrichtlinie](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-lifecycle.html) erstellen, um zu verwalten, wie lange Dateien im Bucket aufbewahrt werden sollen. 
+ Sie können Amazon SNS so konfigurieren, dass Sie benachrichtigt werden, wenn Daten an Ihren verschlüsselten Amazon S3 S3-Bucket geliefert werden. Informationen zur Konfiguration von Benachrichtigungen finden Sie unter [Erste Schritte mit Amazon SNS im Amazon](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html) *Simple Notification Service Developer Guide*.

## Datenhistorisierung
<a name="data-feed-historization"></a>

Jeder Datenfeed enthält Spalten, die den Verlauf der Daten dokumentieren. Mit Ausnahme von `valid_to` sind diese Spalten allen Datenfeeds gemeinsam. Sie sind als allgemeines Verlaufsschema enthalten und beim Abfragen der Daten nützlich. 


| Spaltenname  | Beschreibung  | 
| --- | --- | 
| valid\$1from | Das erste Datum, für das der Wert für den Primärschlüssel in Bezug auf Werte für andere Felder gültig ist. | 
| valid\$1to | Diese Spalte wird nur im [Adressdatenfeed](data-feed-address.md) angezeigt und ist immer leer. | 
| insert\$1date | Das Datum, an dem ein Datensatz in den Datenfeed eingefügt wurde. | 
| update\$1date | Das Datum, an dem der Datensatz zuletzt aktualisiert wurde.  | 
| delete\$1date | Diese Spalte ist immer leer. | 

Im Folgenden sehen Sie ein Beispiel für diese Spalten. 


|  valid\$1from  |  valid\$1to  |  insert\$1date  |  update\$1date  |  delete\$1date  | 
| --- | --- | --- | --- | --- | 
|  2018-12-12T 02:00:00 Z  |   |  2018-12-12T 02:00:00 Z  |  2018-12-12T 02:00:00 Z  |   | 
|  29.03.2019 UM 03:00:00 UHR Z  |   |  29.03.2019 UM 03:00:00 Z  |  29.03.2019 UM 03:00:00 Z  |   | 
|  29.03.2019 UM 03:00:00 Z  |   |  29.03.2019 UM 03:00:00 Z  |  28.04.2019 UM 03:00:00 Z  |   | 

*Das `update_date` Feld `valid_from` und das Feld bilden zusammen ein bitemporales Datenmodell.* Das `valid_from` Feld, so wie es benannt ist, gibt an, ab wann das Element gültig ist. Wenn das Element bearbeitet wurde, kann es mehrere Datensätze im Feed enthalten, die jeweils ein anderes`update_date`, aber dasselbe `valid_from` Datum haben. Um beispielsweise den aktuellen Wert für ein Element zu ermitteln, würden Sie in der Liste der Datensätze mit dem aktuellsten `update_date` Datum den Datensatz mit dem neuesten `valid_from` Datum suchen.

Im obigen Beispiel wurde der Datensatz ursprünglich am 12.12.2018 erstellt. Er wurde dann am 29.03.2019 geändert (z. B. wenn sich die Adresse im Datensatz geändert hat). Später, am 28.04.2019, wurde die Adressänderung korrigiert (sie hat sich also nicht geändert, `valid_from` aber sie hat sich geändert). `update_date` Durch die Korrektur der Adresse (ein seltenes Ereignis) wird der Datensatz rückwirkend gegenüber dem ursprünglichen `valid_from` Datum geändert, sodass dieses Feld nicht geändert wurde. Eine Abfrage nach dem neuesten Datensatz `valid_from` würde zwei Datensätze zurückgeben. Der Datensatz mit dem neuesten `update_date` gibt Ihnen den aktuellen Datensatz.

# Zugriff auf Datenfeeds
<a name="data-feed-accessing"></a>

Mit können Sie Datenfeeds als Mechanismus verwenden AWS Marketplace, um strukturierte up-to-date Produkt- und Kundeninformationen aus AWS Marketplace Systemen und Amazon S3 S3-Buckets für ETL (Extrahieren, Transformieren und Laden) zwischen unternehmenseigenen Business Intelligence-Tools zu senden. Sie müssen Ihre Umgebung so konfigurieren, dass sie Datenfeeds in einen verschlüsselten Amazon S3 S3-Bucket empfängt. In diesem Thema erfahren Sie, wie Sie auf Datenfeeds zugreifen und sich von ihnen abmelden können.

**Topics**
+ [

## Greifen Sie auf einen Datenfeed zu
](#data-feed-accessing-procedure)
+ [

## Richtlinien für Datenfeeds
](#data-feed-policies)
+ [

## Datenfeeds abbestellen
](#data-feed-unsubscribing)

## Greifen Sie auf einen Datenfeed zu
<a name="data-feed-accessing-procedure"></a>

1. Weisen Sie einen Business Intelligence- oder Dateningenieur mit SQL- und ETL-Erfahrung (Extrahieren, Transformieren, Laden) zu. Diese Person benötigt auch Erfahrung in der Einrichtung APIs.

1. Richten Sie einen Amazon Simple Storage Service-Bucket und ein Abonnement für die Datenfeeds ein. Verwenden Sie die AWS Verkäuferkonto-ID, die Ihren Marketplace-Produktangeboten zugeordnet ist. Sehen Sie [sich dazu dieses YouTube Video](https://www.youtube.com/watch?v=heCsZdOT-hw) an oder folgen Sie den nachstehenden Schritten.

   Das Video und die Schritte erklären, wie Sie eine [CloudFormation Vorlage](https://s3.amazonaws.com/aws-marketplace-reports-resources/DataFeedsResources.yaml) verwenden, die die Konfiguration vereinfacht.

   1. Öffnen Sie einen Webbrowser und melden Sie sich beim [AWS Marketplace Management Portal](https://aws.amazon.com/marketplace/management/)an. Gehen Sie dann zu [Kundendatenspeicher einrichten](https://aws.amazon.com/marketplace/management/reports/data-feed-configuration).

   1. Wählen Sie **Ressourcen mit CloudFormation Vorlage erstellen**, um die Vorlage in der CloudFormation Konsole in einem anderen Fenster zu öffnen.

   1. Geben Sie in der Vorlage Folgendes an und wählen Sie dann **Next (Weiter)**:
      + Stack-Name — Die Sammlung von Ressourcen, die Sie erstellen, um den Zugriff auf Datenfeeds zu ermöglichen.
      + Amazon S3 S3-Bucket-Name — Der Bucket zum Speichern von Datenfeeds.
      + (Optional) Amazon SNS SNS-Themenname — Das Thema für den Empfang von Benachrichtigungen beim Amazon Simple Storage Service-Bucket.

   1. Bestätigen Sie Ihre Eingaben auf der Seite **Review (Überprüfen)** und wählen Sie **Create Stack (Stapel erstellen)**. Dadurch wird eine neue Seite mit dem CloudFormation Status und den Details geöffnet.

   1. Kopieren Sie vom Tab **Ressourcen** die Amazon-Ressourcennamen (ARNs) für die folgenden Ressourcen von der CloudFormation Seite in die Felder auf der Seite [Kundendatenspeicher AWS Marketplace einrichten](https://aws.amazon.com/marketplace/management/reports/data-feed-configuration):
      + Amazon S3 S3-Bucket zum Speichern von Datenfeeds
      + AWS KMS Schlüssel zum Verschlüsseln des Amazon S3 S3-Buckets
      + (Optional) Amazon SNS SNS-Thema für den Empfang von Benachrichtigungen bei der AWS Lieferung neuer Daten an den Amazon S3 S3-Bucket

   1. Wählen Sie auf der Seite **Set up customer data storage (Kundendatenspeicher) einrichten** die Option **Submit (Absenden)**.

   1. (Optional) Bearbeiten Sie die mit der CloudFormation Vorlage erstellten Richtlinien. Weitere Details finden Sie unter [Richtlinien für Datenfeeds](#data-feed-policies).

      Sie haben nun Datenfeeds abonniert. Wenn das nächste Mal Datenfeeds generiert werden, können Sie auf die Daten zugreifen.

1. Verwenden Sie einen ETL-Vorgang (Extrahieren, Transformieren, Laden), um die Datenfeeds mit Ihrem Data Warehouse oder Ihrer relationalen Datenbank zu verbinden.
**Anmerkung**  
Datentools haben unterschiedliche Funktionen. Sie müssen einen Business Intelligence- oder Dateningenieur hinzuziehen, um die Integration so einzurichten, dass sie den Funktionen Ihres Tools entspricht.

1. Um SQL-Abfragen auszuführen oder zu erstellen, konfigurieren Sie die Datenfeeds so, dass Primär- und Fremdschlüssel in Ihrem Datentool durchgesetzt werden. Jeder Datenfeed stellt eine eindeutige Tabelle dar, und Sie müssen alle Datenfeeds im Datenschema mit den Entitätsbeziehungen einrichten. Weitere Informationen zu den Tabellen und Entitätsbeziehungen finden Sie [Übersicht über Datenfeed-Tabellen](data-feed-joining.md) in diesem Handbuch.

1. Richten Sie Amazon Simple Notification Service ein, um Ihr Data Warehouse oder Ihre relationale Datenbank automatisch zu aktualisieren. Sie können Amazon SNS SNS-Benachrichtigungen so konfigurieren, dass Benachrichtigungen gesendet werden, wenn Daten aus jedem einzelnen Feed an einen Amazon S3 S3-Bucket gesendet werden. Diese Benachrichtigungen können genutzt werden, um das Seller Data Warehouse automatisch zu aktualisieren, wenn neue Daten über Datenfeeds eingehen, sofern das Seller Data Tool diese Funktion unterstützt. Weitere Informationen finden Sie unter [Erste Schritte mit Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html) im *Amazon Simple Notification Service Developer Guide*.

   Beispiel für eine Benachrichtigung:

   ```
   {
           "mainExecutionId": "1bc08b11-ab4b-47e1-866a-9c8f38423a98",
           "executionId": "52e862a9-42d2-41e0-8010-810af84d39b1",
           "subscriptionId": "27ae3961-b13a-44bc-a1a7-365b2dc181fd",
           "processedFiles": [],
           "executionStatus": "SKIPPED",
           "errors": [],
           "feedType": "[data feed name]"
           }
   ```

   Benachrichtigungen können die folgenden `executionStatus` Status haben:
   + `SKIPPED`— Der Verkäufer hat keine neuen Daten für diesen Tag.
   + `COMPLETED`— Wir haben den Feed mit neuen Daten geliefert.
   + `FAILED`— Bei der Feed-Lieferung ist ein Problem aufgetreten.

1. Überprüfen Sie das Setup, indem Sie SQL-Abfragen ausführen. Sie können die [Beispielabfragen in diesem Handbuch](https://docs.aws.amazon.com/marketplace/latest/userguide/data-feed-full-examples.html) oder die Abfragen GitHub unter [ https://github.com/aws-samples/aws-marketplace-api-samples/](https://github.com/aws-samples/aws-marketplace-api-samples/tree/main/seller-data-feeds/queries)verwendentree/main/seller-data-feeds/queries.
**Anmerkung**  
Die Beispielabfragen in diesem Handbuch wurden für AWS Athena geschrieben. Möglicherweise müssen Sie die Abfragen für die Verwendung mit Ihren Tools ändern.

1. Ermitteln Sie, wo Geschäftsanwender Daten konsumieren möchten. Beispielsweise ist Folgendes möglich:
   + Exportieren Sie CSV-Daten aus Ihrem Data Warehouse oder Ihrer SQL-Datenbank.
   + Connect Sie Ihre Daten mit einem Visualisierungstool wie PowerBI oder Tableau.
   + Ordnen Sie Daten Ihren CRM-, ERP- oder Finanztools wie Salesforce, Infor oder Netsuite zu.

Weitere Informationen zu CloudFormation Vorlagen finden Sie unter [Arbeiten mit CloudFormation Vorlagen](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html) im *AWS CloudFormation Benutzerhandbuch*.

## Richtlinien für Datenfeeds
<a name="data-feed-policies"></a>

Wenn Ihr Amazon S3 S3-Bucket anhand der CloudFormation Vorlage erstellt wird, erstellt es Richtlinien für den Zugriff, die an diesen Bucket, den AWS KMS Schlüssel und das Amazon SNS SNS-Thema angehängt sind. Die Richtlinien ermöglichen es dem AWS Marketplace Berichtsservice, mit den Datenfeed-Informationen in Ihren Bucket und Ihr SNS-Thema zu schreiben. Jede Richtlinie hat einen Abschnitt wie den folgenden (dieses Beispiel stammt aus dem Amazon S3 S3-Bucket).

```
        {
            "Sid": "AwsMarketplaceDataFeedsAccess",
            "Effect": "Allow",
            "Principal": {
                "Service": "reports.marketplace.amazonaws.com"
            },
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject",
                "s3:GetEncryptionConfiguration",
                "s3:GetBucketAcl",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket",
                "arn:aws:s3:::amzn-s3-demo-bucket/*"
            ]
        },
```

In dieser Richtlinie wird der `reports.marketplace.amazonaws.com` Service Principal AWS Marketplace verwendet, um Daten in den Amazon S3 S3-Bucket zu übertragen. Sie haben das *amzn-s3-demo-bucket* in der CloudFormation Vorlage angegeben.

Wenn der AWS Marketplace Berichtsservice Amazon S3 oder Amazon SNS aufruft, stellt er den ARN der Daten bereit, die er in den Bucket schreiben möchte. AWS KMS Um sicherzustellen, dass die einzigen Daten, die in Ihren Bucket geschrieben werden, Daten sind, die in Ihrem Namen geschrieben wurden, können Sie dies `aws:SourceArn` in der Bedingung der Richtlinie angeben. Im folgenden Beispiel müssen Sie die durch die *account-id* ID für Ihre ersetzen AWS-Konto.

```
        {
           "Sid": "AwsMarketplaceDataFeedsAccess",
           "Effect": "Allow",
           "Principal": {
                "Service": "reports.marketplace.amazonaws.com"
            },
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject",
                "s3:GetEncryptionConfiguration",
                "s3:GetBucketAcl",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket",
                "arn:aws:s3:::amzn-s3-demo-bucket/*"
            ,
            "Condition": {
                "StringEquals": {
                        "aws:SourceAccount": "account-id",
                        "aws:SourceArn": ["arn:aws:marketplace::account-id:AWSMarketplace/SellerDataSubscription/DataFeeds_V1",
                        "arn:aws:marketplace::account-id:AWSMarketplace/SellerDataSubscription/Example-Report"]
                        }
                }
        },
```

## Datenfeeds abbestellen
<a name="data-feed-unsubscribing"></a>

Öffnen Sie einen Webbrowser und melden Sie sich beim [AWS Marketplace Management Portal](https://aws.amazon.com/marketplace/management/) an. Rufen Sie dann die [Kontaktseite](https://aws.amazon.com/marketplace/management/contact-us/) auf, um eine Abmeldeanfrage an das AWS Marketplace Seller Operations Team zu richten. Die Bearbeitung der Abmeldeanfrage kann bis zu 10 Werktage dauern.

# Sammeln und Analysieren von Daten mit Datenfeeds
<a name="data-feed-using"></a>

AWS Marketplace bietet Datenfeeds als Mechanismus zum Senden strukturierter up-to-date Produkt- und Kundeninformationen von AWS Marketplace Systemen an Amazon S3 S3-Buckets des Verkäufers für ETL (Extrahieren, Transformieren und Laden) zwischen unternehmenseigenen Business Intelligence-Tools. Wenn Daten in Ihrem Amazon S3 S3-Bucket verfügbar sind, können Sie Daten-Feeds auf folgende Weise verwenden:
+ Laden Sie die CSV-Dateien aus dem Amazon S3 S3-Bucket herunter, in dem Sie sie erstellt haben, [Zugriff auf Datenfeeds](data-feed-accessing.md) damit Sie die Daten in einer Tabelle anzeigen können.
+ Verwenden Sie zum Erfassen und Analysieren von Daten ETL (Extrahieren, Transformieren und Laden), SQL-Abfragen und Geschäftsanalysetools.

  Sie können AWS Dienste zum Sammeln und Analysieren von Daten oder jedes Drittanbieter-Tool verwenden, das Analysen von CSV-basierten Datensätzen durchführen kann.

Weitere Informationen zu Datenfeeds zum Sammeln und Analysieren von Daten finden Sie im folgenden Beispiel.

## Beispiel: Verwenden Sie AWS Dienste, um Daten zu sammeln und zu analysieren
<a name="data-feed-using-example"></a>

Das folgende Verfahren setzt voraus, dass Sie Ihre Umgebung bereits für den Empfang von Datenfeeds in einen Amazon S3 S3-Bucket konfiguriert haben und dass der Bucket Datenfeeds enthält.

**So erfassen und analysieren Sie Daten aus Datenfeeds**

1. [Erstellen Sie von der [AWS Glue Konsole](https://console.aws.amazon.com/glue) aus einen Crawler](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html), um eine Verbindung zum Amazon S3 S3-Bucket herzustellen, in dem die Datenfeeds gespeichert sind, extrahieren Sie die gewünschten Daten und erstellen Sie Metadatentabellen in der AWS Glue Data Catalog.

   Weitere Informationen AWS Glue dazu finden Sie im [https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html).

1. [Führen Sie von der [Athena-Konsole](https://console.aws.amazon.com/athena) aus SQL-Abfragen für die Daten in der AWS Glue Data Catalog](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html) aus.

   Weitere Informationen zu Athena finden Sie im [https://docs.aws.amazon.com/athena/latest/ug/what-is.html](https://docs.aws.amazon.com/athena/latest/ug/what-is.html). 

1. [Erstellen Sie in der [Schnellkonsole](http://quicksight.aws.amazon.com) eine Analyse](https://docs.aws.amazon.com/quick/latest/userguide/creating-an-analysis.html) und anschließend [eine visuelle Darstellung](https://docs.aws.amazon.com/quick/latest/userguide/creating-a-visual.html) der Daten.

   Weitere Informationen zu Quick finden Sie im [https://docs.aws.amazon.com/quick/latest/userguide/welcome.html](https://docs.aws.amazon.com/quick/latest/userguide/welcome.html).

Ein detailliertes Beispiel für eine Möglichkeit, AWS Dienste zum Sammeln und Analysieren von Daten in Datenfeeds zu verwenden, finden Sie im AWS Marketplace Blog [unter Verwenden des Seller Data Feed Delivery Service, Amazon Athena und Quick to create Seller Reports](https://aws.amazon.com/blogs/awsmarketplace/using-seller-data-feed-delivery-service-amazon-athena-and-amazon-quicksight-to-create-seller-reports/).

# Übersicht über Datenfeed-Tabellen
<a name="data-feed-joining"></a>

AWS Marketplace stellt Datenfeeds als eine Reihe von Tabellen bereit, die Sie zusammenfügen können, um mehr Kontext für Ihre Abfragen bereitzustellen.

AWS Marketplace stellt die folgenden allgemeinen Domänen oder Interessenkategorien in Ihren Datenfeeds bereit:
+ **Katalog** — Enthält Informationen zu den Produkten und Angeboten in Ihrem Konto.
+ **Konten** — Enthält Informationen zu den Konten, über die Produkte angeboten oder gekauft werden AWS Marketplace (Ihre eigenen Konten oder Konten von Parteien, mit denen Sie zusammenarbeiten, z. B. Vertriebspartner oder Käufer).
+ **Umsatz** — Beinhaltet Informationen zu Abrechnung, Auszahlungen und Steuern.
+ **Beschaffung** — enthält Informationen zu den Vereinbarungen für die Produktangebote, die Sie als registrierter Verkäufer abgeschlossen haben. 

Dieses Diagramm zeigt die Tabellen in den Bereichen Katalog, Konten und Umsatz.

![\[Entity relationship diagram showing how data feeds relate to each other.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-overview.png) 

## Tabellen im Zusammenhang mit dem Katalog
<a name="data-feed-catalog-domain"></a>

Das folgende Diagramm zeigt die Beziehungen zwischen Tabellen in der Katalogdomäne sowie den Feldern innerhalb der Tabellen. 

![\[Beziehungen zwischen den Tabellen Product, Offer_Product, Offer, Offer_Target und Legacy_ID_Mapping in der Catalog-Domäne.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-catalog-details.png)


Die Tabellen`Product`,, und \$1befinden sich in der `Offer_Product` `Offer` Catalog-Domäne`Offer_Target`. `Legacy_id_mapping`

Die `Offer_Target` Tabelle enthält ein Wertfeld für das `account_id` Ziel, aber nur, wenn der `target_type` Wert ist`account`.

Die `Legacy_id_mapping` Tabelle wird nicht für aktuelle Daten verwendet.

**Anmerkung**  
Weitere Informationen zu diesen Tabellen, einschließlich einer Beschreibung der einzelnen Felder in der Tabelle und der Verknüpfungen, die erstellt werden können, finden Sie in den folgenden Themen:  
[Produktdatenfeed](data-feed-product.md)
[Datenfeed zu Angebotsprodukten](data-feed-offer-product.md)
[Angebotsdatenfeed](data-feed-offer.md)
[Datenfeed zum Angebotsziel](data-feed-offer-target.md)
[Datenfeed zu Legacy-Zuweisungen](data-feed-legacy-mapping.md)

## Tabellen, die sich auf Konten beziehen
<a name="data-feed-accounts-domain"></a>

Das folgende Diagramm zeigt die Beziehungen zwischen den `Address` Tabellen `Account` und in der Domäne Konten sowie die Felder innerhalb der Tabellen.

![\[Beziehung zwischen den Konten- und Adresstabellen in der Domäne Konten und den Feldern innerhalb der einzelnen Tabellen.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-accounts-details.png)


**Anmerkung**  
Weitere Informationen zu diesen Tabellen, einschließlich einer Beschreibung der einzelnen Felder in der Tabelle und der Verknüpfungen, die Sie erstellen können, finden Sie in den folgenden Themen:  
[Kontodatenfeed](data-feed-account.md)
[Adressdatenfeed](data-feed-address.md)

## Umsatzbezogene Tabellen
<a name="data-feed-revenue-domain"></a>

Das folgende Diagramm zeigt die Beziehungen zwischen den `Tax_Item` Tabellen `Billing_Event` und im Bereich Umsatz sowie die Felder innerhalb der Tabellen. Die `Billing_Event` Tabelle enthält Informationen zu Auszahlungen sowie zu Abrechnungsereignissen.

![\[Beziehungen zwischen den Tabellen Billing_Event und Tax_Item in der Domäne Revenue und den Feldern in den einzelnen Tabellen.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-revenue-details.png)


**Anmerkung**  
Weitere Informationen zu diesen Tabellen, einschließlich einer Beschreibung der einzelnen Felder in der Tabelle und der Verknüpfungen, die Sie erstellen können, finden Sie in den folgenden Themen:  
[Datenfeed zu Abrechnungsereignissen](data-feed-billing-event.md)
[Daten-Feed für Steuerartikel](data-feed-tax-item.md)

### Tabellen zum Thema Beschaffung
<a name="procurement-tables"></a>

Das folgende Diagramm zeigt die Felder in der Vereinbarungstabelle im Bereich Beschaffung.

**Anmerkung**  
Weitere Informationen zu diesen Tabellen, einschließlich einer Beschreibung der einzelnen Felder in der Tabelle und der Verknüpfungen, die erstellt werden können[Datenfeed für Vereinbarungen](data-feed-agreements.md), finden Sie unter in diesem Handbuch.

Die folgenden Abschnitte enthalten *Entitätsbeziehungsdiagramme* (ER) für jede Domäne. Jedes ER-Diagramm zeigt die Tabellen und die Felder in jeder Tabelle sowie die Felder, mit denen Sie die Tabellen verknüpfen können.

**Anmerkung**  
Die ER-Diagramme in diesem Abschnitt enthalten nicht die gemeinsamen Felder für alle Datenfeeds. Weitere Informationen zu den allgemeinen Feldern finden Sie unter[Speicherung und Struktur von AWS Marketplace Datenfeeds](data-feed-details.md).

In der folgenden Tabelle werden die Symbole beschrieben, die in den ER-Diagrammen verwendet werden.


| Symbol | Beschreibung | 
| --- | --- | 
|  ![\[Ein Bild der Buchstaben „PK“ als Symbol.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-primary-key.png)  |  **Primärschlüssel** — Ein Primärschlüssel für die Tabelle. Wenn er zusammen mit den `update_date` Feldern `valid_from` und verwendet wird, ist er eindeutig. Weitere Informationen zur gemeinsamen Verwendung dieser Felder finden Sie unter[Datenhistorisierung](data-feed-details.md#data-feed-historization). Wenn mehr als ein Feld als Primärschlüssel markiert ist, bilden die Felder zusammen den Primärschlüssel.  | 
|  ![\[Ein Bild der Buchstaben „FK“ als Symbol.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-foreign-key.png)  |   **Fremdschlüssel** — Ein Feld, das einen Primärschlüssel in einer anderen Tabelle darstellt. Nicht unbedingt einzigartig in der Tabelle.   In einigen Fällen kann der Fremdschlüssel leer sein, wenn für den Datensatz in der aktuellen Tabelle kein entsprechender Datensatz in der Fremdtabelle vorhanden ist.   | 
|  ![\[Ein Bild der Buchstaben „AK“ als Symbol.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-alternate-key.png)  |   **Alternativer Schlüssel** — Ein Schlüssel, der als Schlüssel in der Tabelle verwendet werden kann. Folgt den gleichen Eindeutigkeitsregeln wie der Primärschlüssel.  | 
|  ![\[Ein Bild einer Linie mit einem Kreuz an einem Ende und einem Kreis und einer Gabelung am anderen Ende.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-one-to-many.png)  |   **Konnektor** — Linien zwischen Feldern stellen eine Verbindung dar. Dabei handelt es sich um zwei Felder, die zum Verbinden von Tabellen verwendet werden können. Die Enden der Linie stehen für die Art der Verbindung. Dieses Beispiel stellt eine one-to-many Verbindung dar.  | 

**Arten von Anschlüssen**

Die folgende Tabelle zeigt die Arten von Enden, die jeder Stecker haben kann.


| Typ des Steckverbinders | Beschreibung | 
| --- | --- | 
|  ![\[Ein Bild einer Linie mit einem Kreuz an einem Ende.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-one-to-n.png)  |   **Eins bis n** — Ein Verbinder mit diesem Ende steht für eine Verbindung, die genau einen Wert auf dieser Seite der Verbindung hat.  | 
|  ![\[Ein Bild einer Linie mit einem Kreuz und einem Kreis an einem Ende.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-zero-or-one-to-n.png)  |   **Null oder eins bis n** — Ein Verbinder mit diesem Ende steht für eine Verbindung, die auf dieser Seite der Verbindung Null oder Eins hat.  | 
|  ![\[Ein Bild einer Linie mit einem Kreis und einer Gabelung an einem Ende.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-optional-many-to-n.png)  |   **Null oder mehr bis n** — Ein Verbinder mit diesem Ende steht für eine Verbindung, die Null, einen oder viele Werte auf dieser Seite der Verbindung hat.  | 
|  ![\[Ein Bild einer Linie mit einem Kreuz und einer Gabelung an einem Ende.\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/images/datafeeds-one-or-more-to-n.png)  |   **Eins oder mehrere bis n** — Ein Verbinder mit diesem Ende steht für eine Verbindung, die einen oder mehrere Werte auf dieser Seite der Verbindung hat.  | 

# Beispiele für Datenfeed-Abfragen
<a name="data-feed-full-examples"></a>

Dieser Abschnitt enthält Beispiele für komplexe Abfragen, bei denen die von AWS Marketplace bereitgestellten Datenfeeds verwendet werden. Diese Beispiele ähneln denen[Dashboards für Verkäufer](dashboards.md), die Sie von der erhalten AWS Marketplace Management Portal. Sie können diese Abfragen anpassen, um weitere Berichte zu erstellen, die Sie benötigen.

**Topics**
+ [

## Verträge und Verlängerungen
](#data-feed-example-agreements)
+ [

## Fakturierter Umsatz
](#data-feed-example-billed-revenue)
+ [

## Nicht eingezogene oder ausgezahlte Rechnungen
](#data-feed-example-collections)
+ [

## Besteuerte Rechnungen
](#data-feed-example-tax)
+ [

## Auszahlungen nach Produkten
](#data-feed-example-disbursement-by-product)
+ [

## Sales Compensation Report (Vertriebsvergütungsbericht)
](#data-feed-example-sales-compensation)

## Verträge und Verlängerungen
<a name="data-feed-example-agreements"></a>

Um Ihre Vertrags- und Verlängerungsdaten zu finden, können Sie eine Reihe von Abfragen wie im folgenden Beispiel ausführen. Die Abfragen bauen aufeinander auf und bilden das Dashboard „**Verträge und Verlängerungen**“ mit detaillierten Daten. Sie können das Beispiel wie abgebildet verwenden oder es an Ihre Daten und Anwendungsfälle anpassen.

In den Kommentaren in den Abfragen wird erklärt, was die Abfragen bewirken und wie sie geändert werden können.

```
      Query currently under development.
```

## Fakturierter Umsatz
<a name="data-feed-example-billed-revenue"></a>

Um Ihre Rechnungsdaten zu finden, können Sie eine Reihe von Abfragen wie im folgenden Beispiel ausführen. Die Abfragen bauen aufeinander auf, um den Bericht „**Fakturierter Umsatz“** zu erstellen. Sie können das Beispiel wie abgebildet verwenden oder es an Ihre Daten und Anwendungsfälle anpassen.

In den Kommentaren in den Abfragen wird erklärt, was die Abfragen bewirken und wie sie geändert werden können.

```
-- Billed revenue report

-- General note: When executing this query we are assuming that the data ingested in the database uses 
-- two time axes (the valid_from column and the update_date column).
-- See documentation for more details: https://docs.aws.amazon.com/marketplace/latest/userguide/data-feed.html#data-feed-details

-- An account_id has several valid_from dates (each representing a separate revision of the data)
-- but because of bi-temporality, an account_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
with accounts_with_uni_temporal_data as (
  select
    account_id,
    aws_account_id,
    encrypted_account_id,
    mailing_address_id,
    tax_address_id,
    tax_legal_name,
    from_iso8601_timestamp(valid_from) as valid_from,
    tax_registration_number
  from
    (
      select
        account_id,
        aws_account_id,
        encrypted_account_id,
        mailing_address_id,
        tax_address_id,
        tax_legal_name,
        valid_from,
        delete_date,
        tax_registration_number,
        row_number() over (partition by account_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
      from
        accountfeed_v1
    )
    where
      -- keep latest ...
      row_num = 1
      -- ... and remove the soft-deleted one.
      and (delete_date is null or delete_date = '')
  ),

accounts_with_history as (
  with accounts_with_history_with_extended_valid_from as (
    select
      account_id,
      -- sometimes, this columns gets imported as a "bigint" and loses heading 0s -> casting to a char and re-adding heading 0s (if need be)
      substring('000000000000'||cast(aws_account_id as varchar),-12) as aws_account_id,
      encrypted_account_id,
      mailing_address_id,
      tax_address_id,
      tax_legal_name,
      -- The start time of account valid_from is extended to '1970-01-01 00:00:00', because:
      -- ... in tax report transformations, some tax line items with invoice_date cannot
      -- ... fall into the default valid time range of the associated account
      case
        when lag(valid_from) over (partition by account_id order by valid_from asc) is null
          then cast('1970-01-01 00:00:00' as timestamp)
        else valid_from
      end as valid_from
    from accounts_with_uni_temporal_data
    )
  select
    account_id,
    aws_account_id,
    encrypted_account_id,
    mailing_address_id,
    tax_address_id,
    tax_legal_name,
    valid_from,
    coalesce(
      lead(valid_from) over (partition by account_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp)
    ) as valid_to
  from
    accounts_with_history_with_extended_valid_from
),

-- An address_id has several valid_from dates (each representing a separate revision of the data)
-- but because of bi-temporality, an account_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
address_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    address_id,
    company_name,
    email_domain,
    country_code,
    state_or_region,
    city,
    postal_code,
    row_num
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      address_id,
      company_name,
      email_domain,
      country_code,
      state_or_region,
      city,
      postal_code,
      row_number() over (partition by address_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      addressfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

-- We are only interested in the most recent tuple (BTW: a given address is not supposed to change over time but when bugs ;-) so this query mainly does nothing)
address_with_latest_revision as (
  select
    valid_from,
    address_id,
    company_name,
    email_domain,
    country_code,
    state_or_region,
    city,
    postal_code,
    row_num_latest_revision
  from
  (
    select
      valid_from,
      address_id,
      company_name,
      email_domain,
      country_code,
      state_or_region,
      city,
      postal_code,
      row_number() over (partition by address_id order by valid_from desc) as row_num_latest_revision
    from
      address_with_uni_temporal_data
  )
  where
    row_num_latest_revision = 1
),

accounts_with_history_with_company_name as (
  select
    awh.account_id,
    awh.aws_account_id,
    awh.encrypted_account_id,
    awh.mailing_address_id,
    awh.tax_address_id,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when address.company_name = '' then null else address.company_name end,
      awh.tax_legal_name) as mailing_company_name,
    address.email_domain,
    awh.valid_from,
    -- For BYOL, the agreement might be accepted (using some external non-AWS system or manual process) days before
    -- that BYOL agreement is entered into AWS Marketplace by the buyer. Therefore, the buyer is permitted to manually
    -- enter a backdated acceptance date, which might predate the point in time when the account was created.
    -- To work around this, we need to adjust the valid_from of the account to be
    -- earlier than the earliest possible backdated BYOL agreement acceptance date.
    case
      when lag(awh.valid_from) over (partition by aws_account_id order by awh.valid_from asc) is null
      then date_add('Day', -212, awh.valid_from)
      -- 212 is the longest delay between acceptance_date of the agreement and the account start_Date
      else awh.valid_from
    end as valid_from_adjusted,
    awh.valid_to
  from accounts_with_history as awh
  left join address_with_latest_revision as address on
    awh.mailing_address_id = address.address_id and awh.mailing_address_id is not null
),

-- An agreement_id has several valid_from dates (each representing an agreement revision)
-- but because of bi-temporality, an agreement_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
agreements_with_uni_temporal_data as (
  select
    agreement_id,
    origin_offer_id,
    proposer_account_id,
    acceptor_account_id,
    agreement_revision,
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(start_date) as start_date,
    from_iso8601_timestamp(end_date) as end_date,
    from_iso8601_timestamp(acceptance_date) as acceptance_date,
    agreement_type,
    previous_agreement_id,
    agreement_intent
  from
  (
    select
      --empty value in Athena shows as '', change all '' value to null
      case when agreement_id = '' then null else agreement_id end as agreement_id,
      origin_offer_id,
      proposer_account_id,
      acceptor_account_id,
      agreement_revision,
      valid_from,
      delete_date,
      start_date,
      end_date,
      acceptance_date,
      agreement_type,
      previous_agreement_id,
      agreement_intent,
      row_number() over (partition by agreement_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      -- TODO change to agreementfeed_v1 when Agreement Feed is GA'ed
      agreementfeed
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

agreements_with_history as (
  with agreements_with_window_functions as (
    select
      agreement_id,
      origin_offer_id as offer_id,
      proposer_account_id,
      acceptor_account_id,
      agreement_revision,
      start_date,
      end_date,
      acceptance_date,
      -- The start time of agreement valid_from is extended to '1970-01-01 00:00:00', because:
      -- ... in usage report transformations, some usage line items with usage_date cannot
      -- ... fall into the default valid time range of the associated agreement
      case
          when lag(valid_from) over (PARTITION BY agreement_id order by valid_from asc) is null
          then timestamp '1970-01-01 00:00:00'
          else valid_from
      end as valid_from,
      coalesce(
          lead(valid_from) over (partition by agreement_id order by valid_from asc),
          timestamp '2999-01-01 00:00:00'
      ) as valid_to,
      rank() over (partition by agreement_id order by valid_from asc) version,
      agreement_type,
      previous_agreement_id,
      agreement_intent
    from
      agreements_with_uni_temporal_data
  )
  select
    agreement_id,
    offer_id,
    proposer_account_id,
    acceptor_account_id,
    agreement_revision,
    start_date,
    end_date,
    acceptance_date,
    valid_from,
    case
        when version=1 and valid_from<timestamp '2023-03-03 06:16:08.743' then timestamp '1970-01-01'
        -- The following 60 minute adjustment is to handle special case where When Renewal happens for a contract
        when version=1 then date_add('minute',-60,valid_from)
        else valid_from
    end as valid_from_adjusted,
    valid_to,
    agreement_type,
    previous_agreement_id,
    agreement_intent
  from
    agreements_with_window_functions
),

-- An offer_id has several valid_from dates (each representing an offer revision)
-- but because of bi-temporality, an offer_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
offers_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    from_iso8601_timestamp(delete_date) as delete_date,
    offer_id,
    offer_revision,
    name,
    expiration_date,
    opportunity_id,
    opportunity_name,
    opportunity_description,
    seller_account_id
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      offer_id,
      offer_revision,
      name,
      expiration_date,
      opportunity_id,
      opportunity_name,
      opportunity_description,
      seller_account_id,
      row_number() over (partition by offer_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      offerfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

-- Here, we build the validity time range (adding valid_to on top of valid_from) of each offer revision.
-- We will use it to get Offer name at invoice time.
-- NB: If you'd rather get "current" offer name, un-comment "offers_with_latest_revision"
offers_with_history as (
  select
    offer_id,
    offer_revision,
    name,
    opportunity_id,
    opportunity_name,
    opportunity_description,
    valid_from,
    -- When we try to look up an offer revision as at the acceptance date of a BYOL agreement, we run into a problem.
    -- For BYOL, the agreement might be accepted (using some external non-AWS system or manual process) days before
    -- that BYOL agreement is entered into AWS Marketplace by the buyer. Therefore, the buyer is permitted to manually
    -- enter a backdated acceptance date, which might predate the point in time when the first revision of the offer
    -- was created. To work around this, we need to adjust the valid_from on the first revision of the offer to be
    -- earlier than the earliest possible backdated BYOL agreement acceptance date.
    case
      when lag(valid_from) over (partition by offer_id order by valid_from asc) is null and valid_from<cast('2021-04-01' as timestamp)
      then date_add('Day', -3857, valid_from)
      -- 3857 is the longest delay between acceptance_date of an agreement and the first revision of the offer
      when lag(valid_from) over (partition by offer_id order by valid_from asc) is null and valid_from >= cast('2021-04-01' as timestamp)
      then date_add('Day', -1460, valid_from)
      --after 2021 for the two offers we need to adjust for 2 more years
      else valid_from
    end as valid_from_adjusted,
    coalesce(
      lead(valid_from) over (partition by offer_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp))
    as valid_to
  from offers_with_uni_temporal_data
),
-- provided for reference only if you are interested into get "current" offer name
-- (ie. not used afterwards)
offers_with_latest_revision as (
  select
    offer_id,
    offer_revision,
    name,
    opportunity_name,
    opportunity_description,
    valid_from,
    null valid_to
  from
  (
    select
      offer_id,
      offer_revision,
      name,
      opportunity_name,
      opportunity_description,
      valid_from,
      null valid_to,
      row_number() over (partition by offer_id order by valid_from desc) as row_num_latest_revision
    from
      offers_with_uni_temporal_data
  )
  where
    row_num_latest_revision = 1
),

-- An offer_target_id has several valid_from dates (each representing an offer revision)
-- but because of bi-temporality, an offer_target_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
offer_targets_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    from_iso8601_timestamp(delete_date) as delete_date,
    offer_target_id,
    offer_id,
    offer_revision,
    target_type,
    polarity,
    value
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      offer_target_id,
      offer_id,
      offer_revision,
      target_type,
      polarity,
      value,
      row_number() over (partition by offer_target_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      offertargetfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

offer_target_type as (
  select
    offer_id,
    offer_revision,
    substring(
      -- The first character indicates the priority (lower value means higher precedence):
      min(
        case
          when offer_target.target_type='BuyerAccounts' then '1Private'
          when offer_target.target_type='ParticipatingPrograms' then '2Program:'||cast(offer_target.value as varchar)
          when offer_target.target_type='CountryCodes' then '3GeoTargeted'
          -- well, there is no other case today, but rather be safe...
          else '4Other Targeting'
        end
      ),
      -- Remove the first character that was only used for th priority in the "min" aggregate function:
      2
    ) as offer_target
  from
    offer_targets_with_uni_temporal_data as offer_target
  group by
    offer_id,
    offer_revision
),

offers_with_history_with_target_type as (
  select
    offer.offer_id,
    offer.offer_revision,
    -- even though today it is not possible to combine several types of targeting in a single offer, let's ensure the query is still predictable if this gets possible in the future
    max(
      case
        when off_tgt.offer_target is null then 'Public'
        else off_tgt.offer_target
      end
    ) as offer_target,
    min(offer.name) as name,
    min(offer.opportunity_name) as opportunity_name,
    min(offer.opportunity_description) as opportunity_description,
    offer.valid_from,
    offer.valid_from_adjusted,
    offer.valid_to,
    offer.opportunity_id
  from
    offers_with_history as offer
  left join offer_target_type as off_tgt on
    offer.offer_id = off_tgt.offer_id
    and offer.offer_revision = off_tgt.offer_revision
  group by
    offer.offer_id,
    offer.offer_revision,
    offer.valid_from,
    offer.valid_from_adjusted,
    offer.valid_to,
    offer.opportunity_id
),

-- provided for reference only if you are interested into get "current" offer targets
-- (ie. not used afterwards)
offers_with_latest_revision_with_target_type as (
  select
    offer.offer_id,
    offer.offer_revision,
    -- even though today it is not possible to combine several types of targeting in a single offer, let's ensure the query is still predictable if this gets possible in the future
    max(
      distinct
      case
        when off_tgt.target_type is null then 'Public'
        when off_tgt.target_type='BuyerAccounts' then 'Private'
        when off_tgt.target_type='ParticipatingPrograms' then 'Program:'||cast(off_tgt.value as varchar)
        when off_tgt.target_type='CountryCodes' then 'GeoTargeted'
        -- well, there is no other case today, but rather be safe...
        else 'Other Targeting'
      end
    ) as offer_target,
    min(offer.name) as name,
    min(offer.opportunity_name) as opportunity_name,
    min(offer.opportunity_description) as opportunity_description,
    offer.valid_from,
    offer.valid_to
  from
    offers_with_latest_revision offer
    -- left joining because public offers don't have targets
    left join offer_targets_with_uni_temporal_data off_tgt on
      offer.offer_id=off_tgt.offer_id and offer.offer_revision=off_tgt.offer_revision
  group by
    offer.offer_id,
    offer.offer_revision,
    -- redundant with offer_revision, as each revision has a dedicated valid_from (but cleaner in the group by)
    offer.valid_from,
    offer.valid_to
),

-- A product_id has several valid_from dates (each representing a product revision),
-- but because of bi-temporality, each product_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
products_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    from_iso8601_timestamp(delete_date) as delete_date,
    product_id,
    manufacturer_account_id,
    product_code,
    title
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      product_id,
      manufacturer_account_id,
      product_code,
      title,
      row_number() over (partition by product_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      productfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

products_with_history as (
  select
    product_id,
    title,
    valid_from,
    -- Offerv2 can have upto 50 years and Offerv3 is upto 5 years of past date
    case
      when lag(valid_from) over (partition by product_id order by valid_from asc) is null and valid_from<cast('2021-04-01' as timestamp)
        then date_add('Day', -3857, valid_from)
      -- 3827 is the longest delay between acceptance_date of an agreement and the product
      -- we are keeping 3857 as a consistency between the offers and products
      when lag(valid_from) over (partition by product_id order by valid_from asc) is null and valid_from >= cast('2021-04-01' as timestamp)
        then date_add('Day', -2190, valid_from)
      --after 2021 for the two offers we need to adjust for 2 more years
      else valid_from 
    end as valid_from_adjusted,
    coalesce(
      lead(valid_from) over (partition by product_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp)
    ) as valid_to,
    product_code,
    manufacturer_account_id
  from
    products_with_uni_temporal_data
),

legacy_products as (
  select
    legacy_id,
    new_id
  from
    legacyidmappingfeed_v1
  where
    mapping_type='PRODUCT'
  group by
    legacy_id,
    new_id
),

-- A given billing_event_id represents an accounting event and thus has only one valid_from date,
-- but because of bi-temporality, a billing_event_id (+ its valid_from) can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
billing_events_with_uni_temporal_data as (
  select
    billing_event_id,
    valid_from,
    update_date,
    delete_date,
    invoice_date,
    transaction_type,
    transaction_reference_id,
    parent_billing_event_id,
    bank_trace_id,
    broker_id,
    product_id,
    disbursement_billing_event_id,
    action,
    from_account_id,
    to_account_id,
    end_user_account_id,
    billing_address_id,
    amount,
    currency,
    balance_impacting,
    --empty value in Athena shows as '', change all '' value to null
    case when agreement_id = '' then null else agreement_id end as agreement_id,
    invoice_id,
    payment_due_date,
    usage_period_start_date,
    usage_period_end_date,
    buyer_transaction_reference_id,
    row_num
  from
  (
    select
      billing_event_id,
      from_iso8601_timestamp(valid_from) as valid_from,
      from_iso8601_timestamp(update_date) as update_date,
      delete_date,
      from_iso8601_timestamp(invoice_date) as invoice_date,
      transaction_type,
      transaction_reference_id,
      parent_billing_event_id,
      -- casting in case data was imported as number
      cast(bank_trace_id as varchar) as bank_trace_id,
      broker_id,
      product_id,
      disbursement_billing_event_id,
      action,
      from_account_id,
      to_account_id,
      end_user_account_id,
      billing_address_id,
      -- casting in case data was imported as varchar
      cast(amount as decimal(38,6)) as amount,
      currency,
      balance_impacting,
      agreement_id,
      invoice_id,
      case when payment_due_date is null or payment_due_date = '' then null else from_iso8601_timestamp(payment_due_date) end as payment_due_date,
      from_iso8601_timestamp(usage_period_start_date) as usage_period_start_date,
      from_iso8601_timestamp(usage_period_end_date) as usage_period_end_date,
      buyer_transaction_reference_id,
      row_number() over (partition by billing_event_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      billingeventfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

-- Here we select the account_id of the current seller (We identify this by looking for the to_account_id related to revenue transactions).
-- We will use it later to distinguish own agreements from agreements generated by channel partners.
seller_account as (
  select
    from_account_id as seller_account_id
  from
    billing_events_with_uni_temporal_data bill
  where
    -- Assumption here is only seller will pay listing fee. As of 12/21/2021, there are cases that Channel partner have 0 listing fee for CPPO, so the amount could be 0.
    bill.transaction_type like 'AWS_REV_SHARE' and amount <= 0 and action = 'INVOICED'
  group by
    -- from_account_id is always the same for all those "listing fee" transactions == the seller of record himself.
    -- If this view returns more than 1 record, the overall query will fail (on purpose). Please contact AWS Marketplace if this happens.
    from_account_id
),

billing_event_with_business_flags as (
  select
    bl.billing_event_id,
    bl.end_user_account_id,
    bl.agreement_id,
    aggrement.proposer_account_id,
    aggrement.offer_id,
    aggrement.acceptor_account_id,
    case
      -- For AWS and BALANCE_ADJUSTMENT, the billing event feed will show the "AWS Marketplace" account as the
      -- receiver of the funds and the seller as the payer. We are not interested in this information here.
      -- Null values will be ignored by the `max` aggregation function.
      when bl.transaction_type like 'AWS%' then null
      -- For BALANCE_ADJUSTMENT, payer is seller themselves
      when bl.invoice_id is null then bl.to_account_id
      -- We get the payer of the invoice from *any* transaction type that is not AWS and not BALANCE_ADJUSTMENT (because they are the same for a given end user + agreement + product).
      else bl.from_account_id
    end as payer_account_id,
    bl.product_id,
    bl.action,
    bl.transaction_type,
    bl.parent_billing_event_id,
    bl.disbursement_billing_event_id,
    bl.amount,
    bl.currency,
    bl.balance_impacting,
    bl.invoice_date,
    bl.payment_due_date,
    bl.usage_period_start_date,
    bl.usage_period_end_date,
    bl.invoice_id,
    bl.billing_address_id,
    bl.transaction_reference_id,
    bl.buyer_transaction_reference_id,
    case when disbursement.bank_trace_id = 'EMEA_MP_TEST_TRACE_ID' then null else disbursement.bank_trace_id end as bank_trace_id,
    case when disbursement.bank_trace_id = 'EMEA_MP_TEST_TRACE_ID' then null else disbursement.invoice_date end as disbursement_date,
    disbursement.billing_event_id as disbursement_id,
    -- We will use disbursement_id_or_invoiced as part of the PK, so it cannot be null:
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when disbursement.billing_event_id = '' then null else disbursement.billing_event_id end,
      '<invoiced>') as disbursement_id_or_invoiced,
    bl.broker_id,
    case
      when bl.invoice_id is null /* transaction_type = 'BALANCE_ADJUSTMENT' */
        then (select seller_account_id from seller_account) ||':'|| cast(bl.invoice_date as varchar)
      else bl.buyer_transaction_reference_id
        ||'-'|| case when bl.agreement_id is null or bl.agreement_id = '' then ' ' else bl.agreement_id end
        ||'-'|| case when bl.end_user_account_id is null or bl.end_user_account_id = '' then ' ' else bl.end_user_account_id end
        ||'-'|| coalesce(cast(bl.usage_period_start_date as varchar),' ')
        ||'-'|| coalesce(cast(bl.usage_period_end_date as varchar),' ')
    end as internal_buyer_line_item_id,
    bl.buyer_transaction_reference_id <> bl.transaction_reference_id as is_seller_invoice,
    case when bl.transaction_type = 'SELLER_REV_SHARE' and (select seller_account_id from seller_account) <> bl.to_account_id then true else false end as is_cog,
    case when bl.transaction_type in('SELLER_REV_SHARE_CREDIT', 'SELLER_REV_SHARE_REFUND') and (select seller_account_id from seller_account) <> bl.to_account_id then true else false end as is_cog_refund,
    --TODO: replace below logic once we can create a logic the identify reseller/manufacturer without depending on agreement feed
    case when aggrement.proposer_account_id <> (select seller_account_id from seller_account) then true else false end as is_manufacturer_view_of_reseller
  from
    billing_events_with_uni_temporal_data as bl
    left join billing_events_with_uni_temporal_data as disbursement on
      disbursement.transaction_type like 'DISBURSEMENT%'
        and disbursement.action = 'DISBURSED'
        and disbursement.transaction_type IN ('DISBURSEMENT', 'DISBURSEMENT_FAILURE')
        and bl.disbursement_billing_event_id = disbursement.billing_event_id
    left join agreements_with_history as aggrement on
      bl.agreement_id = aggrement.agreement_id
        and bl.invoice_date >= aggrement.valid_from_adjusted
        and bl.invoice_date<aggrement.valid_to
    left join accounts_with_history awh on
      bl.to_account_id = awh.account_id
        and bl.invoice_date >= awh.valid_from
        and bl.invoice_date<awh.valid_to
  where
    bl.transaction_type not like 'DISBURSEMENT%' and
      (bl.agreement_id is null or bl.agreement_id = ''
      or aggrement.agreement_id is not null)
),

-- listagg function in athena does not support partitioning, grouping here and then joining to the main query
seller_invoice_list as (
  select
    internal_buyer_line_item_id,
    listagg(case when not is_seller_invoice then null else invoice_id end,',') within group (order by case when not is_seller_invoice then null else cast(invoice_date as varchar) end) as seller_invoice_id_or_null,
    listagg(case when not is_seller_invoice then null else cast(invoice_date as varchar) end,',') within group (order by case when not is_seller_invoice then null else cast(invoice_date as varchar) end) as seller_invoice_date_or_null
  from
    (
    -- listagg function in athena does not support ordering by another field when distinct is used,
    -- here we first select distinct invoices and then do the listagg order by invoice_date
    select distinct internal_buyer_line_item_id, is_seller_invoice, invoice_id, invoice_date
    from billing_event_with_business_flags) distinct_invoices
  group by internal_buyer_line_item_id
  order by internal_buyer_line_item_id
),

billing_event_with_categorized_transaction as (
-- Use the flags that were created in the previous transformation in more calculated columns:
-- NOTE: This transformation has no joins and no window functions
  select
    billing_event_id,
    end_user_account_id,
    agreement_id,
    proposer_account_id,
    offer_id,
    acceptor_account_id,
    case when is_cog or is_cog_refund then null else payer_account_id end as payer_account_id,
    product_id,
    action,
    transaction_type,
    parent_billing_event_id,
    disbursement_billing_event_id,
    amount,
    currency,
    balance_impacting,
    invoice_date,
    payment_due_date,
    usage_period_start_date,
    usage_period_end_date,
    invoice_id,
    billing_address_id,
    transaction_reference_id,
    buyer_transaction_reference_id,
    bank_trace_id,
    disbursement_date,
    disbursement_id,
    disbursement_id_or_invoiced,
    broker_id,
    bl.internal_buyer_line_item_id,
    is_seller_invoice,
    is_cog,
    is_cog_refund,
    is_manufacturer_view_of_reseller,

    -- Buyer/seller columns:
    case when is_seller_invoice then null else invoice_id end as buyer_invoice_id_or_null,
    seller_invoices.seller_invoice_id_or_null,
    case when is_seller_invoice then null else invoice_date end as buyer_invoice_date_or_null,
    seller_invoices.seller_invoice_date_or_null,

    -- Categorized amounts by transaction type:
    case when transaction_type =   'SELLER_REV_SHARE' and not is_cog then amount else 0 end as gross_revenue,
    case when transaction_type in ('SELLER_REV_SHARE_REFUND','SELLER_REV_SHARE_CREDIT') and not is_cog_refund then amount else 0 end as gross_refund,
    case when transaction_type =   'SELLER_REV_SHARE' and     is_cog then amount else 0 end as cogs,
    case when transaction_type in ('SELLER_REV_SHARE_REFUND','SELLER_REV_SHARE_CREDIT') and     is_cog_refund then amount else 0 end as cogs_refund,
    case when transaction_type =   'AWS_REV_SHARE' then amount else 0 end as aws_rev_share,
    case when transaction_type in ('AWS_REV_SHARE_REFUND','AWS_REV_SHARE_CREDIT') then amount else 0 end as aws_refund_share,
    case when transaction_type =   'AWS_TAX_SHARE' and not is_seller_invoice then amount else 0 end as aws_tax_share,             -- AWS tax share from _buyer_  invoice
    case when transaction_type =   'AWS_TAX_SHARE' and     is_seller_invoice then amount else 0 end as aws_tax_share_listing_fee, -- AWS tax share from _seller_ invoice
    case when transaction_type =   'AWS_TAX_SHARE_REFUND' and not is_seller_invoice then amount else 0 end as aws_tax_share_refund,
    case when transaction_type =   'AWS_TAX_SHARE_REFUND' and     is_seller_invoice then amount else 0 end as aws_tax_share_refund_listing_fee,
    case when transaction_type =   'SELLER_TAX_SHARE' then amount else 0 end as seller_tax_share,
    case when transaction_type =   'SELLER_TAX_SHARE_REFUND' then amount else 0 end as seller_tax_share_refund,
    case when transaction_type =   'BALANCE_ADJUSTMENT' then amount else 0 end as balance_adjustment,
    case when transaction_type =   'SELLER_REV_SHARE_CREDIT' then amount else 0 end as seller_rev_credit,
    case when transaction_type =   'AWS_REV_SHARE_CREDIT' then amount else 0 end as aws_ref_fee_credit
  from
    billing_event_with_business_flags as bl
    left join seller_invoice_list as seller_invoices
      on bl.internal_buyer_line_item_id = seller_invoices.internal_buyer_line_item_id
    ),

line_items_aggregated as (
-- This transformation has the only "group by" in all of these transformations.
-- NOTE: This transformation has no joins and no window functions
  select
    internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    broker_id,
    currency,
    agreement_id,
    proposer_account_id,
    acceptor_account_id,
    max(payer_account_id) as payer_account_id,
    offer_id,
    end_user_account_id,
    usage_period_start_date,
    usage_period_end_date,
    max(payment_due_date) payment_due_date,
    buyer_transaction_reference_id,
    bank_trace_id,
    disbursement_date,
    max(billing_address_id) as billing_address_id,

    -- Buyer/seller columns:
    max(buyer_invoice_id_or_null) as buyer_invoice_id,
    max(seller_invoice_id_or_null) as seller_invoice_id,
    max(buyer_invoice_date_or_null) as buyer_invoice_date,
    max(seller_invoice_date_or_null) as seller_invoice_date,
  
    -- Categorized amounts by transaction type:
    -- When disbursement_id_or_invoiced = '<invoiced>',    these are invoiced amounts
    -- When disbursement_id_or_invoiced <> '<invoiced>' these are disbursed amounts for _this_ specific disbursement_id
    sum(gross_revenue) as gross_revenue_this_disbursement_id_or_invoiced,
    sum(gross_refund) as gross_refund_this_disbursement_id_or_invoiced,
    sum(cogs) as cogs_this_disbursement_id_or_invoiced,
    sum(cogs_refund) as cogs_refund_this_disbursement_id_or_invoiced,
    sum(aws_rev_share) as aws_rev_share_this_disbursement_id_or_invoiced,
    sum(aws_refund_share) as aws_refund_share_this_disbursement_id_or_invoiced,
    sum(aws_tax_share) as aws_tax_share_this_disbursement_id_or_invoiced,
    sum(aws_tax_share_listing_fee) as aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    sum(aws_tax_share_refund) as aws_tax_share_refund_this_disbursement_id_or_invoiced,
    sum(aws_tax_share_refund_listing_fee) as aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    sum(seller_tax_share) as seller_tax_share_this_disbursement_id_or_invoiced,
    sum(seller_tax_share_refund) as seller_tax_share_refund_this_disbursement_id_or_invoiced,
    sum(balance_adjustment) as balance_adjustment_this_disbursement_id_or_invoiced,
    sum(seller_rev_credit) as seller_rev_credit_this_disbursement_id_or_invoiced,
    sum(aws_ref_fee_credit) as aws_ref_fee_credit_this_disbursement_id_or_invoiced
  from
    billing_event_with_categorized_transaction as billing_categorized
  group by
    internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    broker_id,
    -- The following columns are included the in group by but they are intentionally omitted from the PK.
    -- These columns should have the _same_ values for each record in the PK.
    product_id,
    currency,
    agreement_id,
    proposer_account_id,
    acceptor_account_id,
    offer_id,
    end_user_account_id,
    usage_period_start_date,
    usage_period_end_date,
    buyer_transaction_reference_id,
    bank_trace_id,
    disbursement_date
),

-- listagg function in athena does not support partitioning, grouping here and then joining to the main query
disbursement_list as (
  select
    internal_buyer_line_item_id,
    listagg(cast(disbursement_date as varchar),',') within group (order by cast(disbursement_date as varchar)) as disbursement_date_list,
    listagg(bank_trace_id,',') within group (order by cast(disbursement_date as varchar)) as disburse_bank_trace_id_list
    from (
    -- listagg function in athena does not support ordering by another field when distinct is used,
    -- here we first select distinct bank_trace_ids and then do the listagg order by disbursement_date
    select distinct internal_buyer_line_item_id, disbursement_date, bank_trace_id
  from billing_event_with_business_flags) distinct_disbursements
  group by internal_buyer_line_item_id
  order by internal_buyer_line_item_id
),

line_items_with_window_functions as (
--add flag next step compare gross_revenue and gross_revenue_disbursed or gross_refund and gross_refund_disbursed
  select
    line_item.internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    broker_id,
    currency,
    agreement_id,
    proposer_account_id,
    acceptor_account_id,
    -- when there's aws_rev_Share adjustment/refund to a seller_rev_share invoice, it can happen that for the same aws_rev_share invoice_id, there are multiple disbursement events,
    -- using windows function to map payer_account_id of seller_rev_share to all corresponding aws_rev_Share
    max(payer_account_id) over (partition by line_item.internal_buyer_line_item_id) as payer_account_id,
    offer_id,
    end_user_account_id,
    usage_period_start_date,
    usage_period_end_date,
    payment_due_date,
    bank_trace_id,
    disbursement_date,
    billing_address_id,

    -- Buyer/seller columns:
    max(buyer_invoice_id) over (partition by line_item.internal_buyer_line_item_id) as buyer_invoice_id,
    seller_invoice_id,
    max(buyer_invoice_date) over (partition by line_item.internal_buyer_line_item_id) as buyer_invoice_date,
    seller_invoice_date,

    -- When disbursement_id_or_invoiced = '<invoiced>', these are actually invoiced amounts
    -- When disbursement_id_or_invoiced <> '<invoiced>' these are disbursed amounts for _this_ specific disbursement_id
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    -- IMPORTANT: All window functions partitioned by internal_buyer_line_item_id:

    -- Invoiced amounts, categorized by transaction type:
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then gross_revenue_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end)over (partition by line_item.internal_buyer_line_item_id) as gross_revenue_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then gross_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as gross_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then cogs_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then cogs_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then aws_rev_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_rev_share_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then aws_refund_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_refund_share_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then aws_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then aws_tax_share_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_listing_fee_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then aws_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_listing_fee_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then seller_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then seller_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then balance_adjustment_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as balance_adjustment_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then seller_rev_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_rev_credit_invoiced,
    sum(case when disbursement_id_or_invoiced = '<invoiced>' then aws_ref_fee_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_ref_fee_credit_invoiced,

    -- Total disbursed amounts (for all disbursement_id values), categorized by transaction type:
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then gross_revenue_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as gross_revenue_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then gross_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as gross_refund_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then cogs_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then cogs_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_refund_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then aws_rev_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_rev_share_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then aws_refund_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_refund_share_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then aws_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then aws_tax_share_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_listing_fee_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then aws_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_listing_fee_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then seller_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then seller_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_refund_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then balance_adjustment_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as balance_adjustment_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then seller_rev_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_rev_credit_disbursed,
    sum(case when disbursement_id_or_invoiced <> '<invoiced>' then aws_ref_fee_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_ref_fee_credit_disbursed,

    -- aggregate multiple disbursement
    max(disbursement_date) over (partition by line_item.internal_buyer_line_item_id) as last_disbursement_date,
    first_value(case when disbursement_id_or_invoiced = '<invoiced>' then null else disbursement_id_or_invoiced end) over(partition by line_item.internal_buyer_line_item_id order by coalesce(disbursement_date,cast('1900-01-01' as timestamp)) desc rows between unbounded preceding and unbounded following) as last_disbursement_id,
    first_value(bank_trace_id) over (partition by line_item.internal_buyer_line_item_id order by coalesce(disbursement_date,cast('1900-01-01' as timestamp)) desc rows between unbounded preceding and unbounded following) as last_disburse_bank_trace_id,
    disb_list.disbursement_date_list,
    disb_list.disburse_bank_trace_id_list
  from
    line_items_aggregated as line_item
    left join disbursement_list disb_list
      on line_item.internal_buyer_line_item_id = disb_list.internal_buyer_line_item_id
),

cppo_offer_id as (
  select
    -- Channel partner offers do not exist in offertargetfeed_v1 table (as per legal requirement), causing cppo offer be defined as 'Public' in previous step, we will convert them back to 'Private' in next step
    offer_id
  from
    offers_with_uni_temporal_data
  where
    -- seller_account_id is null means the ISV owns the offer
    seller_account_id is not null
    and seller_account_id <>  (select seller_account_id from seller_account)
  group by
    offer_id
),

line_items_with_window_functions_enrich_offer_product_address as (
  select
    internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    line.product_id,
    legacy_product.legacy_id as legacy_product_id,
    products.title as product_title,
    line.broker_id,
    line.currency,
    line.end_user_account_id,
    acc_enduser.encrypted_account_id as end_user_encrypted_account_id,
    acc_enduser.aws_account_id as end_user_aws_account_id,
    acc_payer.aws_account_id as payer_aws_account_id,
    acc_payer.encrypted_account_id payer_encrypted_account_id,
    line.agreement_id,
    agreement.agreement_revision,
    line.proposer_account_id,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.start_date end as Agreement_Start_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.end_date end as Agreement_End_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.acceptance_date end as Agreement_Acceptance_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.valid_from end as agreement_updated_date,
    case when offer.offer_id like 'aiqoffer-%' then null else line.usage_period_start_date end as Usage_Period_Start_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else line.usage_period_end_date end as Usage_Period_End_Date,

    line.acceptor_account_id,
    acc_subscriber.aws_account_id as subscriber_aws_account_id,
    acc_subscriber.encrypted_account_id as subscriber_encrypted_account_id,
    offer.offer_id,
    case
      when offer.offer_id in (
        select distinct offer_id
        from cppo_offer_id)
        then 'Private'
      else offer.offer_target
    end as offer_target,
    offer.name offer_name,
    offer.opportunity_name offer_opportunity_name,
    offer.opportunity_description offer_opportunity_description,
    offer.opportunity_id,
    payment_due_date,
    line.bank_trace_id,
    disbursement_date,
    billing_address_id,
    buyer_invoice_id,
    seller_invoice_id,
    buyer_invoice_date,
    seller_invoice_date,
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    gross_revenue_invoiced,
    gross_refund_invoiced,
    cogs_invoiced,
    cogs_refund_invoiced,
    aws_rev_share_invoiced,
    aws_refund_share_invoiced,
    aws_tax_share_invoiced,
    aws_tax_share_listing_fee_invoiced,
    aws_tax_share_refund_invoiced,
    aws_tax_share_refund_listing_fee_invoiced,
    seller_tax_share_invoiced,
    seller_tax_share_refund_invoiced,
    balance_adjustment_invoiced,
    seller_rev_credit_invoiced,
    aws_ref_fee_credit_invoiced,
    gross_revenue_disbursed,
    gross_refund_disbursed,
    cogs_disbursed,
    cogs_refund_disbursed,
    aws_rev_share_disbursed,
    aws_refund_share_disbursed,
    aws_tax_share_disbursed,
    aws_tax_share_listing_fee_disbursed,
    aws_tax_share_refund_disbursed,
    aws_tax_share_refund_listing_fee_disbursed,
    seller_tax_share_disbursed,
    seller_tax_share_refund_disbursed,
    balance_adjustment_disbursed,
    seller_rev_credit_disbursed,
    aws_ref_fee_credit_disbursed,
    last_disbursement_date,
    last_disbursement_id,
    last_disburse_bank_trace_id,
    disbursement_date_list,
    disburse_bank_trace_id_list,
    products.product_code,
    acc_products.aws_account_id as manufacturer_aws_account_id,
    products.manufacturer_account_id,
    --add subscriber and payer addressID, payer address preference order: tax address > billing address > mailing address,  subscriber address preference order: tax address >  mailing address
    coalesce (
      --empty value in Athena shows as '', change all '' value to null in order to follow the preference order logic above
      case when acc_subscriber.tax_address_id ='' then null else acc_subscriber.tax_address_id end,
      case when acc_subscriber.mailing_address_id = '' then null else acc_subscriber.mailing_address_id end) as subscriber_address_id,
    coalesce (
      case when acc_payer.tax_address_id = '' then null else acc_payer.tax_address_id end,
      case when line.billing_address_id = '' then null else line.billing_address_id end,
      case when acc_payer.mailing_address_id = '' then null else acc_payer.mailing_address_id end) as payer_address_id,
    coalesce (
      case when acc_enduser.tax_address_id = '' then null else acc_enduser.tax_address_id end,
      case when line.billing_address_id = '' then null else line.billing_address_id end,
      case when acc_enduser.mailing_address_id = '' then null else acc_enduser.mailing_address_id end) as end_user_address_id
  from
    line_items_with_window_functions as line
  left join agreements_with_history as agreement on
      line.agreement_id = agreement.agreement_id and line.buyer_invoice_date >= agreement.valid_from_adjusted and line.buyer_invoice_date<agreement.valid_to
  left join offers_with_history_with_target_type as offer on
        line.offer_id = offer.offer_id and line.buyer_invoice_date >= offer.valid_from and line.buyer_invoice_date<offer.valid_to
  left join products_with_history as products on
        line.product_id = products.product_id and line.buyer_invoice_date >= products.valid_from_adjusted and line.buyer_invoice_date<products.valid_to
  left join legacy_products as legacy_product on
        line.product_id = legacy_product.new_id
  left join accounts_with_history_with_company_name as acc_payer on
        line.payer_account_id = acc_payer.account_id and line.buyer_invoice_date >= acc_payer.valid_from and line.buyer_invoice_date<acc_payer.valid_to
  left join accounts_with_history_with_company_name as acc_enduser on
        line.end_user_account_id = acc_enduser.account_id and line.buyer_invoice_date >= acc_enduser.valid_from and line.buyer_invoice_date<acc_enduser.valid_to
  left join accounts_with_history_with_company_name as acc_subscriber on
        line.acceptor_account_id = acc_subscriber.account_id and line.buyer_invoice_date >= acc_subscriber.valid_from and line.buyer_invoice_date<acc_subscriber.valid_to
  left join accounts_with_history_with_company_name as acc_products on
        products.manufacturer_account_id = acc_products.account_id and line.buyer_invoice_date >= acc_products.valid_from and line.buyer_invoice_date<acc_products.valid_to

),

line_items_with_window_functions_enrich_offer_product_address_name as (
  select
    line.internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    legacy_product_id,
    product_title,
    broker_id,
    currency,
    end_user_address_id,
    end_user_account_id,
    end_user_encrypted_account_id,
    end_user_aws_account_id,
    add_enduser.company_name end_user_company_name,
    add_enduser.email_domain end_user_email_domain,
    add_enduser.city end_user_city,
    add_enduser.state_or_region end_user_state,
    add_enduser.country_code end_user_country,
    add_enduser.postal_code end_user_postal_code,
    payer_aws_account_id,
    payer_encrypted_account_id,
    payer_address_id,
    add_payer.company_name payer_company_name,
    add_payer.email_domain payer_email_domain,
    add_payer.city payer_city,
    add_payer.state_or_region payer_state,
    add_payer.country_code payer_country,
    add_payer.postal_code payer_postal_code,
    agreement_id,
    agreement_revision,
    agreement_start_date,
    agreement_end_date,
    agreement_acceptance_date,
    agreement_updated_date,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.aws_account_id end as reseller_aws_account_id,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.mailing_company_name end as reseller_company_name,
    usage_period_start_date,
    usage_period_end_date,
    proposer_account_id,
    acc_proposer.aws_account_id as proposer_aws_account_id,
    acceptor_account_id,
    subscriber_aws_account_id,
    subscriber_encrypted_account_id,
    subscriber_address_id,
    add_subscriber.company_name subscriber_company_name,
    add_subscriber.email_domain subscriber_email_domain,
    add_subscriber.city subscriber_city,
    add_subscriber.state_or_region subscriber_state,
    add_subscriber.country_code subscriber_country,
    add_subscriber.postal_code subscriber_postal_code,
    offer_id,
    offer_target,
    offer_name,
    offer_opportunity_name,
    offer_opportunity_description,
    opportunity_id,
    payment_due_date,
    bank_trace_id,
    disbursement_date,
    billing_address_id,
    max(buyer_invoice_id)as buyer_invoice_id,
    max(seller_invoice_id)as seller_invoice_id,
    max(buyer_invoice_date)as buyer_invoice_date,
    max(seller_invoice_date)as seller_invoice_date,
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    (gross_revenue_this_disbursement_id_or_invoiced + gross_refund_this_disbursement_id_or_invoiced + aws_rev_share_this_disbursement_id_or_invoiced + aws_refund_share_this_disbursement_id_or_invoiced + seller_tax_share_this_disbursement_id_or_invoiced + seller_tax_share_refund_this_disbursement_id_or_invoiced
      + cogs_this_disbursement_id_or_invoiced + cogs_refund_this_disbursement_id_or_invoiced + aws_tax_share_listing_fee_this_disbursement_id_or_invoiced + aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced) as seller_net_revenue_this_disbursement_id_or_invoiced,
    gross_revenue_invoiced,
    gross_refund_invoiced,
    cogs_invoiced,
    cogs_refund_invoiced,
    aws_rev_share_invoiced,
    aws_refund_share_invoiced,
    aws_tax_share_invoiced,
    aws_tax_share_listing_fee_invoiced,
    aws_tax_share_refund_invoiced,
    aws_tax_share_refund_listing_fee_invoiced,
    seller_tax_share_invoiced,
    seller_tax_share_refund_invoiced,
    balance_adjustment_invoiced,
    seller_rev_credit_invoiced,
    aws_ref_fee_credit_invoiced,
    gross_revenue_disbursed,
    gross_refund_disbursed,
    cogs_disbursed,
    cogs_refund_disbursed,
    aws_rev_share_disbursed,
    aws_refund_share_disbursed,
    aws_tax_share_disbursed,
    aws_tax_share_listing_fee_disbursed,
    aws_tax_share_refund_disbursed,
    aws_tax_share_refund_listing_fee_disbursed,
    seller_tax_share_disbursed,
    seller_tax_share_refund_disbursed,
    balance_adjustment_disbursed,
    seller_rev_credit_disbursed,
    aws_ref_fee_credit_disbursed,
    (gross_revenue_invoiced + gross_revenue_disbursed) as uncollected_gross_revenue,
    -- net revenue = gross revenue - listing fee - tax - cogs
    (gross_revenue_invoiced + gross_refund_invoiced + aws_rev_share_invoiced + aws_refund_share_invoiced + seller_tax_share_invoiced + seller_tax_share_refund_invoiced + cogs_invoiced + cogs_refund_invoiced + aws_tax_share_listing_fee_invoiced + aws_tax_share_refund_listing_fee_invoiced) as seller_net_revenue,
    (gross_revenue_invoiced + gross_refund_invoiced + aws_rev_share_invoiced + aws_refund_share_invoiced + seller_tax_share_invoiced + seller_tax_share_refund_invoiced + cogs_invoiced + cogs_refund_invoiced + aws_tax_share_listing_fee_invoiced + aws_tax_share_refund_listing_fee_invoiced
      + gross_revenue_disbursed + gross_refund_disbursed + aws_rev_share_disbursed + aws_refund_share_disbursed + seller_tax_share_disbursed + seller_tax_share_refund_disbursed + cogs_disbursed + cogs_refund_disbursed + aws_tax_share_listing_fee_disbursed + aws_tax_share_refund_listing_fee_disbursed) as uncollected_seller_net_revenue,
    last_disbursement_date,
    last_disbursement_id,
    last_disburse_bank_trace_id,
    disbursement_date_list,
    disburse_bank_trace_id_list,
    product_code,
    manufacturer_aws_account_id,
    manufacturer_account_id,
    acc_manu.mailing_company_name as manufacturer_company_name,
    cast(null as varchar) as AR_Period,
    case
      when (
        (gross_revenue_invoiced <>0 and gross_revenue_invoiced = -1 * gross_revenue_disbursed)
        or (gross_refund_invoiced <> 0 and gross_refund_invoiced = -1 * gross_refund_disbursed)
        or (balance_adjustment_invoiced <> 0 and balance_adjustment_invoiced = -1 * balance_adjustment_disbursed)
        or (seller_tax_share_refund_invoiced <> 0 and seller_tax_share_refund_invoiced = -1 * seller_tax_share_refund_disbursed)
        or (gross_revenue_invoiced = 0 and gross_refund_invoiced = 0 and balance_adjustment_invoiced = 0 and seller_tax_share_refund_invoiced = 0 and last_disbursement_id is not null)) then 'Yes'
      when gross_revenue_disbursed = 0 and gross_refund_disbursed = 0 and balance_adjustment_disbursed = 0 and seller_tax_share_disbursed = 0 and seller_tax_share_refund_disbursed = 0 then 'No'
      else 'Partial'
    end as Disbursement_Flag
  from line_items_with_window_functions_enrich_offer_product_address as line
  left join accounts_with_history_with_company_name as acc_manu on
    line.manufacturer_account_id = acc_manu.account_id and line.buyer_invoice_date >= acc_manu.valid_from_adjusted and line.buyer_invoice_date <= acc_manu.valid_to
  left join accounts_with_history_with_company_name as acc_proposer on
    line.proposer_account_id = acc_proposer.account_id and line.buyer_invoice_date >= acc_proposer.valid_from and line.buyer_invoice_date<acc_proposer.valid_to
  left join address_with_latest_revision as add_payer on
    line.payer_address_id = add_payer.address_id
  left join address_with_latest_revision as add_subscriber on
    line.subscriber_address_id = add_subscriber.address_id
  left join address_with_latest_revision as add_enduser on
    line.end_user_address_id = add_enduser.address_id
  group by
    line.internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    legacy_product_id,
    product_title,
    broker_id,
    currency,
    end_user_address_id,
    end_user_account_id,
    end_user_encrypted_account_id,
    end_user_aws_account_id,
    add_enduser.company_name,
    add_enduser.email_domain,
    add_enduser.city,
    add_enduser.state_or_region,
    add_enduser.country_code,
    add_enduser.postal_code,
    payer_aws_account_id,
    payer_encrypted_account_id,
    payer_address_id,
    add_payer.company_name,
    add_payer.email_domain,
    add_payer.city,
    add_payer.state_or_region,
    add_payer.country_code,
    add_payer.postal_code,
    agreement_id,
    agreement_revision,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.aws_account_id end,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.mailing_company_name end,
    agreement_start_date,
    agreement_end_date,
    agreement_acceptance_date,
    agreement_updated_date,
    usage_period_start_date,
    usage_period_end_date,
    acceptor_account_id,
    subscriber_aws_account_id,
    subscriber_encrypted_account_id,
    subscriber_address_id,
    add_subscriber.company_name,
    add_subscriber.email_domain,
    add_subscriber.city,
    add_subscriber.state_or_region,
    add_subscriber.country_code,
    add_subscriber.postal_code,
    offer_id,
    offer_target,
    offer_name,
    offer_opportunity_name,
    offer_opportunity_description,
    opportunity_id,
    payment_due_date,
    bank_trace_id,
    disbursement_date,
    billing_address_id,
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    gross_revenue_invoiced,
    gross_refund_invoiced,
    cogs_invoiced,
    cogs_refund_invoiced,
    aws_rev_share_invoiced,
    aws_refund_share_invoiced,
    aws_tax_share_invoiced,
    aws_tax_share_listing_fee_invoiced,
    aws_tax_share_refund_invoiced,
    aws_tax_share_refund_listing_fee_invoiced,
    seller_tax_share_invoiced,
    seller_tax_share_refund_invoiced,
    balance_adjustment_invoiced,
    seller_rev_credit_invoiced,
    aws_ref_fee_credit_invoiced,
    gross_revenue_disbursed,
    gross_refund_disbursed,
    cogs_disbursed,
    cogs_refund_disbursed,
    aws_rev_share_disbursed,
    aws_refund_share_disbursed,
    aws_tax_share_disbursed,
    aws_tax_share_listing_fee_disbursed,
    aws_tax_share_refund_disbursed,
    aws_tax_share_refund_listing_fee_disbursed,
    seller_tax_share_disbursed,
    seller_tax_share_refund_disbursed,
    balance_adjustment_disbursed,
    seller_rev_credit_disbursed,
    aws_ref_fee_credit_disbursed,
    last_disbursement_date,
    last_disbursement_id,
    last_disburse_bank_trace_id,
    disbursement_date_list,
    disburse_bank_trace_id_list,
    product_code,
    manufacturer_aws_account_id,
    manufacturer_account_id,
    acc_manu.mailing_company_name,
    proposer_account_id,
    acc_proposer.aws_account_id
),

billed_revenue as (
  select
    ------------------
    -- Invoice Info --
    ------------------
    buyer_invoice_date as Invoice_Date,
    Payment_Due_Date as Payment_Due_Date,
    concat(
      'Net ',
      case
        when abs(date_diff('Day', Payment_due_date, buyer_invoice_date))>180 then '180+'
        else cast(abs(date_diff('Day', Payment_due_date, buyer_invoice_date)) as varchar)
        end,
      ' days'
    ) as payment_terms,
    buyer_invoice_id as Invoice_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when seller_invoice_id = '' then null else seller_invoice_id end,
      'Not applicable') as Listing_Fee_Invoice_ID,

    ---------------------------
    --End user Information --
    ---------------------------
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when End_User_Company_Name = '' then null else End_User_Company_Name end,
      'Not available') as End_User_Company_Name,
    End_User_AWS_Account_ID,
    End_User_Encrypted_Account_ID,
    End_User_Email_Domain,
    End_User_City,
    End_User_State as End_User_State_or_Region,
    End_User_Country,
    End_User_Postal_Code,
    End_User_Address_ID,

    ---------------------------
    --Subscriber Information --
    ---------------------------
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Company_Name is null or Subscriber_Company_Name = '' then 'Not provided'
      else Subscriber_Company_Name
      end as Subscriber_Company_Name,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Subscriber_AWS_Account_ID
      end as Subscriber_AWS_Account_ID,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Subscriber_Encrypted_Account_ID
      end as Subscriber_Encrypted_Account_ID,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Email_Domain is null or Subscriber_Email_Domain = '' then 'Not provided'
      else Subscriber_Email_Domain
      end as Subscriber_Email_Domain,
    case
      when Agreement_id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_City is null or Subscriber_City = '' then 'Not provided'
      else Subscriber_City
      end as Subscriber_City,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_State is null or Subscriber_State = '' then 'Not provided'
      else Subscriber_State
      end as Subscriber_State_or_Region,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Country is null or Subscriber_Country = '' then 'Not provided'
      else Subscriber_Country
      end as Subscriber_Country,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Postal_Code is null or Subscriber_Postal_Code = '' then 'Not provided'
      else Subscriber_Postal_Code
      end as Subscriber_Postal_Code,
    case
      when Agreement_ID is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Address_ID is null or Subscriber_Address_ID = '' then 'Not provided'
      else Subscriber_Address_ID
      end as Subscriber_Address_ID,

    ----------------------
    -- Procurement Info --
    ----------------------
     -- product title at time of invoice. It is possible that the title changes over time and therefore there may be multiple product titles mapped to a single product id.
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Product_Title = '' then null else Product_Title end,
      'Not provided') as Product_Title,
    -- offer name at time of invoice. It is possible that the name changes over time therefore there may be multiple offer names mapped to a single offer id.
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when (Offer_Name is null or Offer_Name = '') and Offer_Target = 'Public' then 'Not applicable'
      else Offer_Name
      end as Offer_Name,
    case
      when Agreement_Id is null or Agreement_ID = ''
      then 'Not available'
      else Offer_ID
      end as Offer_ID,
    -- offer target at time of invoice.,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Offer_Target
      end as Offer_Visibility,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Agreement_ID = '' then null else Agreement_ID end,
      'Not available') as Agreement_ID,
    Agreement_Start_Date,
    Agreement_Acceptance_Date,
    Agreement_End_Date,
    Usage_Period_Start_Date,
    Usage_Period_End_Date,

    -----------------------
    -- Disbursement Info --
    -----------------------
    case
      when Disbursement_Flag = 'Yes' then 'Disbursed'
      when Disbursement_Flag = 'No' then 'Not Disbursed'
      else 'Other'
      end as Disbursement_Status,
    last_disbursement_date as disbursement_date,
    case
      when Disbursement_Flag = 'No' then 'Not applicable'
      when disburse_bank_trace_id_list is null or disburse_bank_trace_id_list = '' then 'Not available'
      else disburse_bank_trace_id_list
    end as disburse_bank_trace_id,

    --------------
    -- Revenues --
    --------------
    -- We are rounding the sums using 2 decimal precision
    -- Note that the rounding method might differ between SQL implementations.
    -- The monthly revenue report is using RoundingMode.HALF_UP. This might create tiny discrepancies between this SQL output
    -- and the legacy report
    round(gross_revenue_invoiced,2) as Gross_Revenue,
    round(gross_refund_invoiced,2) as Gross_Refund,
    round(aws_rev_share_invoiced,2) as Listing_Fee,
    round(aws_refund_share_invoiced,2) as Listing_Fee_Refund,
    truncate(
      case
        when gross_revenue_invoiced != 0 then abs(aws_rev_share_invoiced/gross_revenue_invoiced)
        when gross_refund_invoiced != 0 then abs(aws_refund_share_invoiced/gross_refund_invoiced)
        else 0
      end
      ,4) as Listing_Fee_Percentage,
    round(seller_tax_share_invoiced,2) as Seller_Tax_Share,
    round(seller_tax_share_refund_invoiced,2) as Seller_Tax_Share_Refund,
    round(aws_tax_share_invoiced,2) as AWS_Tax_Share,
    round(aws_tax_share_refund_invoiced,2) as AWS_Tax_Share_Refund,
    round(aws_tax_share_listing_fee_invoiced,2) as AWS_Tax_Share_Listing_Fee,
    round(aws_tax_share_refund_listing_fee_invoiced,2) as AWS_Tax_Share_Refund_Listing_Fee,
    round(cogs_invoiced,2) as Wholesale_cost,
    round(cogs_refund_invoiced,2) as Wholesale_cost_Refund,
    round(seller_net_revenue,2) as Seller_Net_Revenue,
    currency as Currency,

    substring(internal_buyer_line_item_id,1,strpos(internal_buyer_line_item_id,'-')-1) as Transaction_Reference_ID,
    broker_id as AWS_seller_of_record,

    -----------------
    -- Resale info --
    -----------------
    case
      when Opportunity_Id is null or Opportunity_Id = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Opportunity_Id
    end as Resale_authorization_ID,
    case
      when Offer_Opportunity_Name is null or Offer_Opportunity_Name = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Offer_Opportunity_Name
    end as Resale_authorization_name,
    case
      when Offer_Opportunity_Description is null or Offer_Opportunity_Description = '' then
        case
         when Offer_Target = 'Public' then 'Not applicable'
         when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
         else null
        end
      else Offer_Opportunity_Name
    end as Resale_authorization_description,
    case
      when (Reseller_AWS_Account_ID is not null and Reseller_AWS_Account_ID != '')
        and (Reseller_Company_Name is null or Reseller_Company_Name = '') then 'Not available'
      when (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '')
        and (opportunity_id is null or opportunity_id = '') then 'Not applicable'
      when (select seller_account_id from seller_account) <> manufacturer_aws_account_id
        and (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '') then 'Not applicable'
      else Reseller_Company_Name
    end as Reseller_Company_Name,
    case
      when (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '')
        and (Opportunity_Id is null or Opportunity_Id = '') then 'Not applicable'
      when (select seller_account_id from seller_account) <> manufacturer_aws_account_id
        and (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '') then 'Not applicable'
      else Reseller_AWS_Account_ID
    end as Reseller_AWS_Account_ID,

    -----------------------
    -- Payer Information --
    -----------------------
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Payer_Company_Name = '' then null else Payer_Company_Name end,
      'Not available') as Payer_Company_Name,
    Payer_AWS_Account_ID,
    Payer_Encrypted_Account_ID,
    Payer_Email_Domain,
    Payer_City,
    Payer_State as Payer_State_or_Region,
    Payer_Country,
    Payer_Postal_Code,
    Payer_Address_ID,

    ---------------------
    -- ISV Information --
    ---------------------
    manufacturer_aws_account_id as ISV_Account_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Manufacturer_Company_Name = '' then null else Manufacturer_Company_Name end,
      'Not available') as ISV_Company_Name,

    ---------------------
    -- Products info --
    ---------------------
    Legacy_Product_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Product_ID = '' then null else Product_ID end,
      'Not provided') as Product_ID,
    Product_Code
  from
    line_items_with_window_functions_enrich_offer_product_address_name as line
  where disbursement_id_or_invoiced = '<invoiced>'

)

select *
from billed_revenue
where invoice_date >= date_add('DAY', -90, current_date)
--where invoice_date between cast('2023-01-01' as timestamp) and cast('2024-03-01' as timestamp)
```

## Nicht eingezogene oder ausgezahlte Rechnungen
<a name="data-feed-example-collections"></a>

Um Ihre nicht eingezogenen oder ausgezahlten Rechnungen zu finden, können Sie eine Reihe von Abfragen wie das folgende Beispiel ausführen. Die Abfragen bauen aufeinander auf, um den Bericht **Inkasso und** Auszahlungen zu erstellen. Sie können das Beispiel wie abgebildet verwenden oder es an Ihre Daten und Anwendungsfälle anpassen.

In den Kommentaren in den Abfragen wird erklärt, was die Abfragen bewirken und wie sie geändert werden können.

```
-- Collections and disbursements report

-- General note: When running this query, we assume that the data ingested in the database uses
-- two time axes (the valid_from column and the update_date column).
-- See documentation for more details: https://docs.aws.amazon.com/marketplace/latest/userguide/data-feed.html#data-feed-details

-- An account_id has several valid_from dates (each representing a separate revision of the data)
-- but because of bi-temporality, an account_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
with accounts_with_uni_temporal_data as (
  select
    account_id,
    aws_account_id,
    encrypted_account_id,
    mailing_address_id,
    tax_address_id,
    tax_legal_name,
    from_iso8601_timestamp(valid_from) as valid_from,
    tax_registration_number
  from
    (
      select
        account_id,
        aws_account_id,
        encrypted_account_id,
        mailing_address_id,
        tax_address_id,
        tax_legal_name,
        valid_from,
        delete_date,
        tax_registration_number,
        row_number() over (partition by account_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
      from
        accountfeed_v1
    )
    where
      -- keep latest ...
      row_num = 1
      -- ... and remove the soft-deleted one.
      and (delete_date is null or delete_date = '')
  ),

accounts_with_history as (
  with accounts_with_history_with_extended_valid_from as (
    select
      account_id,
      -- sometimes, this columns gets imported as a "bigint" and loses heading 0s -> casting to a char and re-adding heading 0s (if need be)
      substring('000000000000'||cast(aws_account_id as varchar),-12) as aws_account_id,
      encrypted_account_id,
      mailing_address_id,
      tax_address_id,
      tax_legal_name,
      -- The start time of account valid_from is extended to '1970-01-01 00:00:00', because:
      -- ... in tax report transformations, some tax line items with invoice_date cannot
      -- ... fall into the default valid time range of the associated account
      case
        when lag(valid_from) over (partition by account_id order by valid_from asc) is null
          then cast('1970-01-01 00:00:00' as timestamp)
        else valid_from
      end as valid_from
    from accounts_with_uni_temporal_data
    )
  select
    account_id,
    aws_account_id,
    encrypted_account_id,
    mailing_address_id,
    tax_address_id,
    tax_legal_name,
    valid_from,
    coalesce(
      lead(valid_from) over (partition by account_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp)
    ) as valid_to
  from
    accounts_with_history_with_extended_valid_from
),

-- An address_id has several valid_from dates (each representing a separate revision of the data)
-- but because of bi-temporality, an account_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
address_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    address_id,
    company_name,
    email_domain,
    country_code,
    state_or_region,
    city,
    postal_code,
    row_num
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      address_id,
      company_name,
      email_domain,
      country_code,
      state_or_region,
      city,
      postal_code,
      row_number() over (partition by address_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      addressfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

-- We are only interested in the most recent tuple (BTW: a given address is not supposed to change over time but when bugs ;-) so this query mainly does nothing)
address_with_latest_revision as (
  select
    valid_from,
    address_id,
    company_name,
    email_domain,
    country_code,
    state_or_region,
    city,
    postal_code,
    row_num_latest_revision
  from
  (
    select
      valid_from,
      address_id,
      company_name,
      email_domain,
      country_code,
      state_or_region,
      city,
      postal_code,
      row_number() over (partition by address_id order by valid_from desc) as row_num_latest_revision
    from
      address_with_uni_temporal_data
  )
  where
    row_num_latest_revision = 1
),

accounts_with_history_with_company_name as (
  select
    awh.account_id,
    awh.aws_account_id,
    awh.encrypted_account_id,
    awh.mailing_address_id,
    awh.tax_address_id,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when address.company_name = '' then null else address.company_name end,
      awh.tax_legal_name) as mailing_company_name,
    address.email_domain,
    awh.valid_from,
    -- For BYOL, the agreement might be accepted (using some external non-AWS system or manual process) days before
    -- that BYOL agreement is entered into AWS Marketplace by the buyer. Therefore, the buyer is permitted to manually
    -- enter a backdated acceptance date, which might predate the point in time when the account was created.
    -- To work around this, we need to adjust the valid_from of the account to be
    -- earlier than the earliest possible backdated BYOL agreement acceptance date.
    case
      when lag(awh.valid_from) over (partition by aws_account_id order by awh.valid_from asc) is null
      then date_add('Day', -212, awh.valid_from)
      -- 212 is the longest delay between acceptance_date of the agreement and the account start_Date
      else awh.valid_from
    end as valid_from_adjusted,
    awh.valid_to
  from accounts_with_history as awh
  left join address_with_latest_revision as address on
    awh.mailing_address_id = address.address_id and awh.mailing_address_id is not null
),

-- An agreement_id has several valid_from dates (each representing an agreement revision)
-- but because of bi-temporality, an agreement_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
agreements_with_uni_temporal_data as (
  select
    agreement_id,
    origin_offer_id,
    proposer_account_id,
    acceptor_account_id,
    agreement_revision,
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(start_date) as start_date,
    from_iso8601_timestamp(end_date) as end_date,
    from_iso8601_timestamp(acceptance_date) as acceptance_date,
    agreement_type,
    previous_agreement_id,
    agreement_intent
  from
  (
    select
      --empty value in Athena shows as '', change all '' value to null
      case when agreement_id = '' then null else agreement_id end as agreement_id,
      origin_offer_id,
      proposer_account_id,
      acceptor_account_id,
      agreement_revision,
      valid_from,
      delete_date,
      start_date,
      end_date,
      acceptance_date,
      agreement_type,
      previous_agreement_id,
      agreement_intent,
      row_number() over (partition by agreement_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      -- TODO change to agreementfeed_v1 when Agreement Feed is GA'ed
      agreementfeed
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

agreements_with_history as (
  with agreements_with_window_functions as (
    select
      agreement_id,
      origin_offer_id as offer_id,
      proposer_account_id,
      acceptor_account_id,
      agreement_revision,
      start_date,
      end_date,
      acceptance_date,
      -- The start time of agreement valid_from is extended to '1970-01-01 00:00:00', because:
      -- ... in usage report transformations, some usage line items with usage_date cannot
      -- ... fall into the default valid time range of the associated agreement
      case
          when lag(valid_from) over (PARTITION BY agreement_id order by valid_from asc) is null
          then timestamp '1970-01-01 00:00:00'
          else valid_from
      end as valid_from,
      coalesce(
          lead(valid_from) over (partition by agreement_id order by valid_from asc),
          timestamp '2999-01-01 00:00:00'
      ) as valid_to,
      rank() over (partition by agreement_id order by valid_from asc) version,
      agreement_type,
      previous_agreement_id,
      agreement_intent
    from
      agreements_with_uni_temporal_data
  )
  select
    agreement_id,
    offer_id,
    proposer_account_id,
    acceptor_account_id,
    agreement_revision,
    start_date,
    end_date,
    acceptance_date,
    valid_from,
    case
        when version=1 and valid_from < timestamp '2023-03-03 06:16:08.743' then timestamp '1970-01-01'
        -- The following 60 minute adjustment is to handle special case where When Renewal happens for a contract
        when version=1 then date_add('minute',-60,valid_from)
        else valid_from
    end as valid_from_adjusted,
    valid_to,
    agreement_type,
    previous_agreement_id,
    agreement_intent
  from
    agreements_with_window_functions
),

-- An offer_id has several valid_from dates (each representing an offer revision)
-- but because of bi-temporality, an offer_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
offers_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    from_iso8601_timestamp(delete_date) as delete_date,
    offer_id,
    offer_revision,
    name,
    expiration_date,
    opportunity_id,
    opportunity_name,
    opportunity_description,
    seller_account_id
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      offer_id,
      offer_revision,
      name,
      expiration_date,
      opportunity_id,
      opportunity_name,
      opportunity_description,
      seller_account_id,
      row_number() over (partition by offer_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      offerfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

-- Here, we build the validity time range (adding valid_to on top of valid_from) of each offer revision.
-- We will use it to get Offer name at invoice time.
-- NB: If you'd rather get "current" offer name, un-comment "offers_with_latest_revision"
offers_with_history as (
  select
    offer_id,
    offer_revision,
    name,
    opportunity_id,
    opportunity_name,
    opportunity_description,
    valid_from,
    -- When we try to look up an offer revision as at the acceptance date of a BYOL agreement, we run into a problem.
    -- For BYOL, the agreement might be accepted (using some external non-AWS system or manual process) days before
    -- that BYOL agreement is entered into AWS Marketplace by the buyer. Therefore, the buyer is permitted to manually
    -- enter a backdated acceptance date, which might predate the point in time when the first revision of the offer
    -- was created. To work around this, we need to adjust the valid_from on the first revision of the offer to be
    -- earlier than the earliest possible backdated BYOL agreement acceptance date.
    case
      when lag(valid_from) over (partition by offer_id order by valid_from asc) is null and valid_from < cast('2021-04-01' as timestamp)
      then date_add('Day', -3857, valid_from)
      -- 3857 is the longest delay between acceptance_date of an agreement and the first revision of the offer
      when lag(valid_from) over (partition by offer_id order by valid_from asc) is null and valid_from >= cast('2021-04-01' as timestamp)
      then date_add('Day', -1460, valid_from)
      --after 2021 for the two offers we need to adjust for 2 more years
      else valid_from
    end as valid_from_adjusted,
    coalesce(
      lead(valid_from) over (partition by offer_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp))
    as valid_to
  from offers_with_uni_temporal_data
),
-- provided for reference only if you are interested into get "current" offer name
-- (ie. not used afterwards)
offers_with_latest_revision as (
  select
    offer_id,
    offer_revision,
    name,
    opportunity_name,
    opportunity_description,
    valid_from,
    null valid_to
  from
  (
    select
      offer_id,
      offer_revision,
      name,
      opportunity_name,
      opportunity_description,
      valid_from,
      null valid_to,
      row_number() over (partition by offer_id order by valid_from desc) as row_num_latest_revision
    from
      offers_with_uni_temporal_data
  )
  where
    row_num_latest_revision = 1
),

-- An offer_target_id has several valid_from dates (each representing an offer revision)
-- but because of bi-temporality, an offer_target_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
offer_targets_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    from_iso8601_timestamp(delete_date) as delete_date,
    offer_target_id,
    offer_id,
    offer_revision,
    target_type,
    polarity,
    value
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      offer_target_id,
      offer_id,
      offer_revision,
      target_type,
      polarity,
      value,
      row_number() over (partition by offer_target_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      offertargetfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

offer_target_type as (
  select
    offer_id,
    offer_revision,
    substring(
      -- The first character indicates the priority (lower value means higher precedence):
      min(
        case
          when offer_target.target_type='BuyerAccounts' then '1Private'
          when offer_target.target_type='ParticipatingPrograms' then '2Program:'||cast(offer_target.value as varchar)
          when offer_target.target_type='CountryCodes' then '3GeoTargeted'
          -- well, there is no other case today, but rather be safe...
          else '4Other Targeting'
        end
      ),
      -- Remove the first character that was only used for th priority in the "min" aggregate function:
      2
    ) as offer_target
  from
    offer_targets_with_uni_temporal_data as offer_target
  group by
    offer_id,
    offer_revision
),

offers_with_history_with_target_type as (
  select
    offer.offer_id,
    offer.offer_revision,
    -- even though today it is not possible to combine several types of targeting in a single offer, let's ensure the query is still predictable if this gets possible in the future
    max(
      case
        when off_tgt.offer_target is null then 'Public'
        else off_tgt.offer_target
      end
    ) as offer_target,
    min(offer.name) as name,
    min(offer.opportunity_name) as opportunity_name,
    min(offer.opportunity_description) as opportunity_description,
    offer.valid_from,
    offer.valid_from_adjusted,
    offer.valid_to,
    offer.opportunity_id
  from
    offers_with_history as offer
  left join offer_target_type as off_tgt on
    offer.offer_id = off_tgt.offer_id
    and offer.offer_revision = off_tgt.offer_revision
  group by
    offer.offer_id,
    offer.offer_revision,
    offer.valid_from,
    offer.valid_from_adjusted,
    offer.valid_to,
    offer.opportunity_id
),

-- provided for reference only if you are interested into get "current" offer targets
-- (ie. not used afterwards)
offers_with_latest_revision_with_target_type as (
  select
    offer.offer_id,
    offer.offer_revision,
    -- even though today it is not possible to combine several types of targeting in a single offer, let's ensure the query is still predictable if this gets possible in the future
    max(
      distinct
      case
        when off_tgt.target_type is null then 'Public'
        when off_tgt.target_type='BuyerAccounts' then 'Private'
        when off_tgt.target_type='ParticipatingPrograms' then 'Program:'||cast(off_tgt.value as varchar)
        when off_tgt.target_type='CountryCodes' then 'GeoTargeted'
        -- well, there is no other case today, but rather be safe...
        else 'Other Targeting'
      end
    ) as offer_target,
    min(offer.name) as name,
    min(offer.opportunity_name) as opportunity_name,
    min(offer.opportunity_description) as opportunity_description,
    offer.valid_from,
    offer.valid_to
  from
    offers_with_latest_revision offer
    -- left joining because public offers don't have targets
    left join offer_targets_with_uni_temporal_data off_tgt on
      offer.offer_id=off_tgt.offer_id and offer.offer_revision=off_tgt.offer_revision
  group by
    offer.offer_id,
    offer.offer_revision,
    -- redundant with offer_revision, as each revision has a dedicated valid_from (but cleaner in the group by)
    offer.valid_from,
    offer.valid_to
),

-- A product_id has several valid_from dates (each representing a product revision),
-- but because of bi-temporality, each product_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
products_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    from_iso8601_timestamp(delete_date) as delete_date,
    product_id,
    manufacturer_account_id,
    product_code,
    title
  from
  (
    select
      valid_from,
      update_date,
      delete_date,
      product_id,
      manufacturer_account_id,
      product_code,
      title,
      row_number() over (partition by product_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      productfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

products_with_history as (
  select
    product_id,
    title,
    valid_from,
    -- Offerv2 can have upto 50 years and Offerv3 is upto 5 years of past date
    case
      when lag(valid_from) over (partition by product_id order by valid_from asc) is null and valid_from < cast('2021-04-01' as timestamp)
        then date_add('Day', -3857, valid_from)
      -- 3827 is the longest delay between acceptance_date of an agreement and the product
      -- we are keeping 3857 as a consistency between the offers and products
      when lag(valid_from) over (partition by product_id order by valid_from asc) is null and valid_from >= cast('2021-04-01' as timestamp)
        then date_add('Day', -2190, valid_from)
      --after 2021 for the two offers we need to adjust for 2 more years
      else valid_from 
    end as valid_from_adjusted,
    coalesce(
      lead(valid_from) over (partition by product_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp)
    ) as valid_to,
    product_code,
    manufacturer_account_id
  from
    products_with_uni_temporal_data
),

legacy_products as (
  select
    legacy_id,
    new_id
  from
    legacyidmappingfeed_v1
  where
    mapping_type='PRODUCT'
  group by
    legacy_id,
    new_id
),

-- A given billing_event_id represents an accounting event and thus has only one valid_from date,
-- but because of bi-temporality, a billing_event_id (+ its valid_from) can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
billing_events_with_uni_temporal_data as (
  select
    billing_event_id,
    valid_from,
    update_date,
    delete_date,
    invoice_date,
    transaction_type,
    transaction_reference_id,
    parent_billing_event_id,
    bank_trace_id,
    broker_id,
    product_id,
    disbursement_billing_event_id,
    action,
    from_account_id,
    to_account_id,
    end_user_account_id,
    billing_address_id,
    amount,
    currency,
    balance_impacting,
    --empty value in Athena shows as '', change all '' value to null
    case when agreement_id = '' then null else agreement_id end as agreement_id,
    invoice_id,
    payment_due_date,
    usage_period_start_date,
    usage_period_end_date,
    buyer_transaction_reference_id,
    row_num
  from
  (
    select
      billing_event_id,
      from_iso8601_timestamp(valid_from) as valid_from,
      from_iso8601_timestamp(update_date) as update_date,
      delete_date,
      from_iso8601_timestamp(invoice_date) as invoice_date,
      transaction_type,
      transaction_reference_id,
      parent_billing_event_id,
      -- casting in case data was imported as number
      cast(bank_trace_id as varchar) as bank_trace_id,
      broker_id,
      product_id,
      disbursement_billing_event_id,
      action,
      from_account_id,
      to_account_id,
      end_user_account_id,
      billing_address_id,
      -- casting in case data was imported as varchar
      cast(amount as decimal(38,6)) as amount,
      currency,
      balance_impacting,
      agreement_id,
      invoice_id,
      case when payment_due_date is null or payment_due_date = '' then null else from_iso8601_timestamp(payment_due_date) end as payment_due_date,
      from_iso8601_timestamp(usage_period_start_date) as usage_period_start_date,
      from_iso8601_timestamp(usage_period_end_date) as usage_period_end_date,
      buyer_transaction_reference_id,
      row_number() over (partition by billing_event_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
    from
      billingeventfeed_v1
  )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

-- Here we select the account_id of the current seller (We identify this by looking for the to_account_id related to revenue transactions).
-- We will use it later to distinguish own agreements from agreements generated by channel partners.
seller_account as (
  select
    from_account_id as seller_account_id
  from
    billing_events_with_uni_temporal_data bill
  where
    -- Assumption here is only seller will pay listing fee. As of 12/21/2021, there are cases that Channel partner have 0 listing fee for CPPO, so the amount could be 0.
    bill.transaction_type like 'AWS_REV_SHARE' and amount <= 0 and action = 'INVOICED'
  group by
    -- from_account_id is always the same for all those "listing fee" transactions == the seller of record himself.
    -- If this view returns more than 1 record, the overall query will fail (on purpose). Please contact AWS Marketplace if this happens.
    from_account_id
),

billing_event_with_business_flags as (
  select
    bl.billing_event_id,
    bl.end_user_account_id,
    bl.agreement_id,
    aggrement.proposer_account_id,
    aggrement.offer_id,
    aggrement.acceptor_account_id,
    case
      -- For AWS and BALANCE_ADJUSTMENT, the billing event feed will show the "AWS Marketplace" account as the
      -- receiver of the funds and the seller as the payer. We are not interested in this information here.
      -- Null values will be ignored by the `max` aggregation function.
      when bl.transaction_type like 'AWS%' then null
      -- For BALANCE_ADJUSTMENT, payer is seller themselves
      when bl.invoice_id is null then bl.to_account_id
      -- We get the payer of the invoice from *any* transaction type that is not AWS and not BALANCE_ADJUSTMENT (because they are the same for a given end user + agreement + product).
      else bl.from_account_id
    end as payer_account_id,
    bl.product_id,
    bl.action,
    bl.transaction_type,
    bl.parent_billing_event_id,
    bl.disbursement_billing_event_id,
    bl.amount,
    bl.currency,
    bl.balance_impacting,
    bl.invoice_date,
    bl.payment_due_date,
    bl.usage_period_start_date,
    bl.usage_period_end_date,
    bl.invoice_id,
    bl.billing_address_id,
    bl.transaction_reference_id,
    bl.buyer_transaction_reference_id,
    case when disbursement.bank_trace_id = 'EMEA_MP_TEST_TRACE_ID' then null else disbursement.bank_trace_id end as bank_trace_id,
    case when disbursement.bank_trace_id = 'EMEA_MP_TEST_TRACE_ID' then null else disbursement.invoice_date end as disbursement_date,
    disbursement.billing_event_id as disbursement_id,
    -- We will use disbursement_id_or_invoiced as part of the PK, so it cannot be null:
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when disbursement.billing_event_id = '' then null else disbursement.billing_event_id end,
      '<invoiced>') as disbursement_id_or_invoiced,
    bl.broker_id,
    case
      when bl.invoice_id is null /* transaction_type = 'BALANCE_ADJUSTMENT' */
        then (select seller_account_id from seller_account) ||':'|| cast(bl.invoice_date as varchar)
      else bl.buyer_transaction_reference_id
        ||'-'|| case when bl.agreement_id is null or bl.agreement_id = '' then ' ' else bl.agreement_id end
        ||'-'|| case when bl.end_user_account_id is null or bl.end_user_account_id = '' then ' ' else bl.end_user_account_id end
        ||'-'|| coalesce(cast(bl.usage_period_start_date as varchar),' ')
        ||'-'|| coalesce(cast(bl.usage_period_end_date as varchar),' ')
    end as internal_buyer_line_item_id,
    bl.buyer_transaction_reference_id <> bl.transaction_reference_id as is_seller_invoice,
    case when bl.transaction_type = 'SELLER_REV_SHARE' and (select seller_account_id from seller_account) <> bl.to_account_id then true else false end as is_cog,
    case when bl.transaction_type in('SELLER_REV_SHARE_CREDIT', 'SELLER_REV_SHARE_REFUND') and (select seller_account_id from seller_account) <> bl.to_account_id then true else false end as is_cog_refund,
    --TODO: replace below logic once we can create a logic the identify reseller/manufacturer without depending on agreement feed
    case when aggrement.proposer_account_id <> (select seller_account_id from seller_account) then true else false end as is_manufacturer_view_of_reseller
  from
    billing_events_with_uni_temporal_data as bl
    left join billing_events_with_uni_temporal_data as disbursement on
      disbursement.transaction_type like 'DISBURSEMENT%'
        and disbursement.action = 'DISBURSED'
        and disbursement.transaction_type IN ('DISBURSEMENT', 'DISBURSEMENT_FAILURE')
        and bl.disbursement_billing_event_id = disbursement.billing_event_id
    left join agreements_with_history as aggrement on
      bl.agreement_id = aggrement.agreement_id
        and bl.invoice_date >= aggrement.valid_from_adjusted
        and bl.invoice_date < aggrement.valid_to
    left join accounts_with_history awh on
      bl.to_account_id = awh.account_id
        and bl.invoice_date >= awh.valid_from
        and bl.invoice_date < awh.valid_to
  where
    bl.transaction_type not like 'DISBURSEMENT%' and
      (bl.agreement_id is null or bl.agreement_id = ''
      or aggrement.agreement_id is not null)
),

-- listagg function in athena does not support partitioning, grouping here and then joining to the main query
seller_invoice_list as (
  select
    internal_buyer_line_item_id,
    listagg(case when not is_seller_invoice then null else invoice_id end,',') within group (order by case when not is_seller_invoice then null else cast(invoice_date as varchar) end) as seller_invoice_id_or_null,
    listagg(case when not is_seller_invoice then null else cast(invoice_date as varchar) end,',') within group (order by case when not is_seller_invoice then null else cast(invoice_date as varchar) end) as seller_invoice_date_or_null
  from
    (
    -- listagg function in athena does not support ordering by another field when distinct is used,
    -- here we first select distinct invoices and then do the listagg order by invoice_date
    select distinct internal_buyer_line_item_id, is_seller_invoice, invoice_id, invoice_date
    from billing_event_with_business_flags) distinct_invoices
  group by internal_buyer_line_item_id
  order by internal_buyer_line_item_id
),

billing_event_with_categorized_transaction as (
-- Use the flags that were created in the previous transformation in more calculated columns:
-- NOTE: This transformation has no joins and no window functions
  select
    billing_event_id,
    end_user_account_id,
    agreement_id,
    proposer_account_id,
    offer_id,
    acceptor_account_id,
    case when is_cog or is_cog_refund then null else payer_account_id end as payer_account_id,
    product_id,
    action,
    transaction_type,
    parent_billing_event_id,
    disbursement_billing_event_id,
    amount,
    currency,
    balance_impacting,
    invoice_date,
    payment_due_date,
    usage_period_start_date,
    usage_period_end_date,
    invoice_id,
    billing_address_id,
    transaction_reference_id,
    buyer_transaction_reference_id,
    bank_trace_id,
    disbursement_date,
    disbursement_id,
    disbursement_id_or_invoiced,
    broker_id,
    bl.internal_buyer_line_item_id,
    is_seller_invoice,
    is_cog,
    is_cog_refund,
    is_manufacturer_view_of_reseller,

    -- Buyer/seller columns:
    case when is_seller_invoice then null else invoice_id end as buyer_invoice_id_or_null,
    seller_invoices.seller_invoice_id_or_null,
    case when is_seller_invoice then null else invoice_date end as buyer_invoice_date_or_null,
    seller_invoices.seller_invoice_date_or_null,

    -- Categorized amounts by transaction type:
    case when transaction_type =   'SELLER_REV_SHARE' and not is_cog then amount else 0 end as gross_revenue,
    case when transaction_type in ('SELLER_REV_SHARE_REFUND','SELLER_REV_SHARE_CREDIT') and not is_cog_refund then amount else 0 end as gross_refund,
    case when transaction_type =   'SELLER_REV_SHARE' and     is_cog then amount else 0 end as cogs,
    case when transaction_type in ('SELLER_REV_SHARE_REFUND','SELLER_REV_SHARE_CREDIT') and     is_cog_refund then amount else 0 end as cogs_refund,
    case when transaction_type =   'AWS_REV_SHARE' then amount else 0 end as aws_rev_share,
    case when transaction_type in ('AWS_REV_SHARE_REFUND','AWS_REV_SHARE_CREDIT') then amount else 0 end as aws_refund_share,
    case when transaction_type =   'AWS_TAX_SHARE' and not is_seller_invoice then amount else 0 end as aws_tax_share,             -- AWS tax share from _buyer_  invoice
    case when transaction_type =   'AWS_TAX_SHARE' and     is_seller_invoice then amount else 0 end as aws_tax_share_listing_fee, -- AWS tax share from _seller_ invoice
    case when transaction_type =   'AWS_TAX_SHARE_REFUND' and not is_seller_invoice then amount else 0 end as aws_tax_share_refund,
    case when transaction_type =   'AWS_TAX_SHARE_REFUND' and     is_seller_invoice then amount else 0 end as aws_tax_share_refund_listing_fee,
    case when transaction_type =   'SELLER_TAX_SHARE' then amount else 0 end as seller_tax_share,
    case when transaction_type =   'SELLER_TAX_SHARE_REFUND' then amount else 0 end as seller_tax_share_refund,
    case when transaction_type =   'BALANCE_ADJUSTMENT' then amount else 0 end as balance_adjustment,
    case when transaction_type =   'SELLER_REV_SHARE_CREDIT' then amount else 0 end as seller_rev_credit,
    case when transaction_type =   'AWS_REV_SHARE_CREDIT' then amount else 0 end as aws_ref_fee_credit
  from
    billing_event_with_business_flags as bl
    left join seller_invoice_list as seller_invoices
      on bl.internal_buyer_line_item_id = seller_invoices.internal_buyer_line_item_id
    ),

line_items_aggregated as (
-- This transformation has the only "group by" in all of these transformations.
-- NOTE: This transformation has no joins and no window functions
  select
    internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    broker_id,
    currency,
    agreement_id,
    proposer_account_id,
    acceptor_account_id,
    max(payer_account_id) as payer_account_id,
    offer_id,
    end_user_account_id,
    usage_period_start_date,
    usage_period_end_date,
    max(payment_due_date) payment_due_date,
    buyer_transaction_reference_id,
    bank_trace_id,
    disbursement_date,
    max(billing_address_id) as billing_address_id,

    -- Buyer/seller columns:
    max(buyer_invoice_id_or_null) as buyer_invoice_id,
    max(seller_invoice_id_or_null) as seller_invoice_id,
    max(buyer_invoice_date_or_null) as buyer_invoice_date,
    max(seller_invoice_date_or_null) as seller_invoice_date,
  
    -- Categorized amounts by transaction type:
    -- When disbursement_id_or_invoiced = '<invoiced>',    these are invoiced amounts
    -- When disbursement_id_or_invoiced <> ''<invoiced>' these are disbursed amounts for _this_ specific disbursement_id
    sum(gross_revenue) as gross_revenue_this_disbursement_id_or_invoiced,
    sum(gross_refund) as gross_refund_this_disbursement_id_or_invoiced,
    sum(cogs) as cogs_this_disbursement_id_or_invoiced,
    sum(cogs_refund) as cogs_refund_this_disbursement_id_or_invoiced,
    sum(aws_rev_share) as aws_rev_share_this_disbursement_id_or_invoiced,
    sum(aws_refund_share) as aws_refund_share_this_disbursement_id_or_invoiced,
    sum(aws_tax_share) as aws_tax_share_this_disbursement_id_or_invoiced,
    sum(aws_tax_share_listing_fee) as aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    sum(aws_tax_share_refund) as aws_tax_share_refund_this_disbursement_id_or_invoiced,
    sum(aws_tax_share_refund_listing_fee) as aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    sum(seller_tax_share) as seller_tax_share_this_disbursement_id_or_invoiced,
    sum(seller_tax_share_refund) as seller_tax_share_refund_this_disbursement_id_or_invoiced,
    sum(balance_adjustment) as balance_adjustment_this_disbursement_id_or_invoiced,
    sum(seller_rev_credit) as seller_rev_credit_this_disbursement_id_or_invoiced,
    sum(aws_ref_fee_credit) as aws_ref_fee_credit_this_disbursement_id_or_invoiced
  from
    billing_event_with_categorized_transaction as billing_categorized
  group by
    internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    broker_id,
    -- The following columns are included the in group by but they are intentionally omitted from the PK.
    -- These columns should have the _same_ values for each record in the PK.
    product_id,
    currency,
    agreement_id,
    proposer_account_id,
    acceptor_account_id,
    offer_id,
    end_user_account_id,
    usage_period_start_date,
    usage_period_end_date,
    buyer_transaction_reference_id,
    bank_trace_id,
    disbursement_date
),

-- listagg function in athena does not support partitioning, grouping here and then joining to the main query
disbursement_list as (
  select
    internal_buyer_line_item_id,
    listagg(cast(disbursement_date as varchar),',') within group (order by cast(disbursement_date as varchar)) as disbursement_date_list,
    listagg(bank_trace_id,',') within group (order by cast(disbursement_date as varchar)) as disburse_bank_trace_id_list
    from (
    -- listagg function in athena does not support ordering by another field when distinct is used,
    -- here we first select distinct bank_trace_ids and then do the listagg order by disbursement_date
    select distinct internal_buyer_line_item_id, disbursement_date, bank_trace_id
  from billing_event_with_business_flags) distinct_disbursements
  group by internal_buyer_line_item_id
  order by internal_buyer_line_item_id
),

line_items_with_window_functions as (
--add flag next step compare gross_revenue and gross_revenue_disbursed or gross_refund and gross_refund_disbursed
  select
    line_item.internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    broker_id,
    currency,
    agreement_id,
    proposer_account_id,
    acceptor_account_id,
    -- when there's aws_rev_Share adjustment/refund to a seller_rev_share invoice, it can happen that for the same aws_rev_share invoice_id, there are multiple disbursement events,
    -- using windows function to map payer_account_id of seller_rev_share to all corresponding aws_rev_Share
    max(payer_account_id) over (partition by line_item.internal_buyer_line_item_id) as payer_account_id,
    offer_id,
    end_user_account_id,
    usage_period_start_date,
    usage_period_end_date,
    payment_due_date,
    bank_trace_id,
    disbursement_date,
    billing_address_id,

    -- Buyer/seller columns:
    max(buyer_invoice_id) over (partition by line_item.internal_buyer_line_item_id) as buyer_invoice_id,
    seller_invoice_id,
    max(buyer_invoice_date) over (partition by line_item.internal_buyer_line_item_id) as buyer_invoice_date,
    seller_invoice_date,

    -- When disbursement_id_or_invoiced = ''<invoiced>', these are actually invoiced amounts
    -- When disbursement_id_or_invoiced <> ''<invoiced>' these are disbursed amounts for _this_ specific disbursement_id
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    -- IMPORTANT: All window functions partitioned by internal_buyer_line_item_id:

    -- Invoiced amounts, categorized by transaction type:
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then gross_revenue_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end)over (partition by line_item.internal_buyer_line_item_id) as gross_revenue_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then gross_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as gross_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then cogs_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then cogs_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then aws_rev_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_rev_share_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then aws_refund_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_refund_share_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then aws_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then aws_tax_share_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_listing_fee_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then aws_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_listing_fee_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then seller_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then seller_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_refund_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then balance_adjustment_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as balance_adjustment_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then seller_rev_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_rev_credit_invoiced,
    sum(case when disbursement_id_or_invoiced = ''<invoiced>' then aws_ref_fee_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_ref_fee_credit_invoiced,

    -- Total disbursed amounts (for all disbursement_id values), categorized by transaction type:
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then gross_revenue_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as gross_revenue_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then gross_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as gross_refund_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then cogs_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then cogs_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as cogs_refund_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then aws_rev_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_rev_share_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then aws_refund_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_refund_share_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then aws_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then aws_tax_share_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_listing_fee_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then aws_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_tax_share_refund_listing_fee_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then seller_tax_share_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then seller_tax_share_refund_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_tax_share_refund_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then balance_adjustment_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as balance_adjustment_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then seller_rev_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as seller_rev_credit_disbursed,
    sum(case when disbursement_id_or_invoiced '<> ''<invoiced>' then aws_ref_fee_credit_this_disbursement_id_or_invoiced else cast(0 as decimal(38,6)) end) over (partition by line_item.internal_buyer_line_item_id) as aws_ref_fee_credit_disbursed,

    -- aggregate multiple disbursement
    max(disbursement_date) over (partition by line_item.internal_buyer_line_item_id) as last_disbursement_date,
    first_value(case when disbursement_id_or_invoiced = ''<invoiced>' then null else disbursement_id_or_invoiced end) over(partition by line_item.internal_buyer_line_item_id order by coalesce(disbursement_date,cast('1900-01-01' as timestamp)) desc rows between unbounded preceding and unbounded following) as last_disbursement_id,
    first_value(bank_trace_id) over (partition by line_item.internal_buyer_line_item_id order by coalesce(disbursement_date,cast('1900-01-01' as timestamp)) desc rows between unbounded preceding and unbounded following) as last_disburse_bank_trace_id,
    disb_list.disbursement_date_list,
    disb_list.disburse_bank_trace_id_list
  from
    line_items_aggregated as line_item
    left join disbursement_list disb_list
      on line_item.internal_buyer_line_item_id = disb_list.internal_buyer_line_item_id
),

cppo_offer_id as (
  select
    -- Channel partner offers do not exist in offertargetfeed_v1 table (as per legal requirement), causing cppo offer be defined as 'Public' in previous step, we will convert them back to 'Private' in next step
    offer_id
  from
    offers_with_uni_temporal_data
  where
    -- seller_account_id is null means the ISV owns the offer
    seller_account_id is not null
    and seller_account_id '<>  (select seller_account_id from seller_account)
  group by
    offer_id
),

line_items_with_window_functions_enrich_offer_product_address as (
  select
    internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    line.product_id,
    legacy_product.legacy_id as legacy_product_id,
    products.title as product_title,
    line.broker_id,
    line.currency,
    line.end_user_account_id,
    acc_enduser.encrypted_account_id as end_user_encrypted_account_id,
    acc_enduser.aws_account_id as end_user_aws_account_id,
    acc_payer.aws_account_id as payer_aws_account_id,
    acc_payer.encrypted_account_id payer_encrypted_account_id,
    line.agreement_id,
    agreement.agreement_revision,
    line.proposer_account_id,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.start_date end as Agreement_Start_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.end_date end as Agreement_End_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.acceptance_date end as Agreement_Acceptance_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else agreement.valid_from end as agreement_updated_date,
    case when offer.offer_id like 'aiqoffer-%' then null else line.usage_period_start_date end as Usage_Period_Start_Date,
    case when offer.offer_id like 'aiqoffer-%' then null else line.usage_period_end_date end as Usage_Period_End_Date,

    line.acceptor_account_id,
    acc_subscriber.aws_account_id as subscriber_aws_account_id,
    acc_subscriber.encrypted_account_id as subscriber_encrypted_account_id,
    offer.offer_id,
    case
      when offer.offer_id in (
        select distinct offer_id
        from cppo_offer_id)
        then 'Private'
      else offer.offer_target
    end as offer_target,
    offer.name offer_name,
    offer.opportunity_name offer_opportunity_name,
    offer.opportunity_description offer_opportunity_description,
    offer.opportunity_id,
    payment_due_date,
    line.bank_trace_id,
    disbursement_date,
    billing_address_id,
    buyer_invoice_id,
    seller_invoice_id,
    buyer_invoice_date,
    seller_invoice_date,
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    gross_revenue_invoiced,
    gross_refund_invoiced,
    cogs_invoiced,
    cogs_refund_invoiced,
    aws_rev_share_invoiced,
    aws_refund_share_invoiced,
    aws_tax_share_invoiced,
    aws_tax_share_listing_fee_invoiced,
    aws_tax_share_refund_invoiced,
    aws_tax_share_refund_listing_fee_invoiced,
    seller_tax_share_invoiced,
    seller_tax_share_refund_invoiced,
    balance_adjustment_invoiced,
    seller_rev_credit_invoiced,
    aws_ref_fee_credit_invoiced,
    gross_revenue_disbursed,
    gross_refund_disbursed,
    cogs_disbursed,
    cogs_refund_disbursed,
    aws_rev_share_disbursed,
    aws_refund_share_disbursed,
    aws_tax_share_disbursed,
    aws_tax_share_listing_fee_disbursed,
    aws_tax_share_refund_disbursed,
    aws_tax_share_refund_listing_fee_disbursed,
    seller_tax_share_disbursed,
    seller_tax_share_refund_disbursed,
    balance_adjustment_disbursed,
    seller_rev_credit_disbursed,
    aws_ref_fee_credit_disbursed,
    last_disbursement_date,
    last_disbursement_id,
    last_disburse_bank_trace_id,
    disbursement_date_list,
    disburse_bank_trace_id_list,
    products.product_code,
    acc_products.aws_account_id as manufacturer_aws_account_id,
    products.manufacturer_account_id,
    --add subscriber and payer addressID, payer address preference order: tax address>billing address>mailing address,  subscriber address preference order: tax address> mailing address
    coalesce (
      --empty value in Athena shows as '', change all '' value to null in order to follow the preference order logic above
      case when acc_subscriber.tax_address_id ='' then null else acc_subscriber.tax_address_id end,
      case when acc_subscriber.mailing_address_id = '' then null else acc_subscriber.mailing_address_id end) as subscriber_address_id,
    coalesce (
      case when acc_payer.tax_address_id = '' then null else acc_payer.tax_address_id end,
      case when line.billing_address_id = '' then null else line.billing_address_id end,
      case when acc_payer.mailing_address_id = '' then null else acc_payer.mailing_address_id end) as payer_address_id,
    coalesce (
      case when acc_enduser.tax_address_id = '' then null else acc_enduser.tax_address_id end,
      case when line.billing_address_id = '' then null else line.billing_address_id end,
      case when acc_enduser.mailing_address_id = '' then null else acc_enduser.mailing_address_id end) as end_user_address_id
  from
    line_items_with_window_functions as line
  left join agreements_with_history as agreement on
      line.agreement_id = agreement.agreement_id and line.buyer_invoice_date >= agreement.valid_from_adjusted and line.buyer_invoice_date < agreement.valid_to
  left join offers_with_history_with_target_type as offer on
        line.offer_id = offer.offer_id and line.buyer_invoice_date >= offer.valid_from and line.buyer_invoice_date < offer.valid_to
  left join products_with_history as products on
        line.product_id = products.product_id and line.buyer_invoice_date >= products.valid_from_adjusted and line.buyer_invoice_date < products.valid_to
  left join legacy_products as legacy_product on
        line.product_id = legacy_product.new_id
  left join accounts_with_history_with_company_name as acc_payer on
        line.payer_account_id = acc_payer.account_id and line.buyer_invoice_date >= acc_payer.valid_from and line.buyer_invoice_date < acc_payer.valid_to
  left join accounts_with_history_with_company_name as acc_enduser on
        line.end_user_account_id = acc_enduser.account_id and line.buyer_invoice_date >= acc_enduser.valid_from and line.buyer_invoice_date < acc_enduser.valid_to
  left join accounts_with_history_with_company_name as acc_subscriber on
        line.acceptor_account_id = acc_subscriber.account_id and line.buyer_invoice_date >= acc_subscriber.valid_from and line.buyer_invoice_date < acc_subscriber.valid_to
  left join accounts_with_history_with_company_name as acc_products on
        products.manufacturer_account_id = acc_products.account_id and line.buyer_invoice_date >= acc_products.valid_from and line.buyer_invoice_date < acc_products.valid_to

),

line_items_with_window_functions_enrich_offer_product_address_name as (
  select
    line.internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    legacy_product_id,
    product_title,
    broker_id,
    currency,
    end_user_address_id,
    end_user_account_id,
    end_user_encrypted_account_id,
    end_user_aws_account_id,
    add_enduser.company_name end_user_company_name,
    add_enduser.email_domain end_user_email_domain,
    add_enduser.city end_user_city,
    add_enduser.state_or_region end_user_state,
    add_enduser.country_code end_user_country,
    add_enduser.postal_code end_user_postal_code,
    payer_aws_account_id,
    payer_encrypted_account_id,
    payer_address_id,
    add_payer.company_name payer_company_name,
    add_payer.email_domain payer_email_domain,
    add_payer.city payer_city,
    add_payer.state_or_region payer_state,
    add_payer.country_code payer_country,
    add_payer.postal_code payer_postal_code,
    agreement_id,
    agreement_revision,
    agreement_start_date,
    agreement_end_date,
    agreement_acceptance_date,
    agreement_updated_date,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.aws_account_id end as reseller_aws_account_id,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.mailing_company_name end as reseller_company_name,
    usage_period_start_date,
    usage_period_end_date,
    proposer_account_id,
    acc_proposer.aws_account_id as proposer_aws_account_id,
    acceptor_account_id,
    subscriber_aws_account_id,
    subscriber_encrypted_account_id,
    subscriber_address_id,
    add_subscriber.company_name subscriber_company_name,
    add_subscriber.email_domain subscriber_email_domain,
    add_subscriber.city subscriber_city,
    add_subscriber.state_or_region subscriber_state,
    add_subscriber.country_code subscriber_country,
    add_subscriber.postal_code subscriber_postal_code,
    offer_id,
    offer_target,
    offer_name,
    offer_opportunity_name,
    offer_opportunity_description,
    opportunity_id,
    payment_due_date,
    bank_trace_id,
    disbursement_date,
    billing_address_id,
    max(buyer_invoice_id)as buyer_invoice_id,
    max(seller_invoice_id)as seller_invoice_id,
    max(buyer_invoice_date)as buyer_invoice_date,
    max(seller_invoice_date)as seller_invoice_date,
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    (gross_revenue_this_disbursement_id_or_invoiced + gross_refund_this_disbursement_id_or_invoiced + aws_rev_share_this_disbursement_id_or_invoiced + aws_refund_share_this_disbursement_id_or_invoiced + seller_tax_share_this_disbursement_id_or_invoiced + seller_tax_share_refund_this_disbursement_id_or_invoiced
      + cogs_this_disbursement_id_or_invoiced + cogs_refund_this_disbursement_id_or_invoiced + aws_tax_share_listing_fee_this_disbursement_id_or_invoiced + aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced) as seller_net_revenue_this_disbursement_id_or_invoiced,
    gross_revenue_invoiced,
    gross_refund_invoiced,
    cogs_invoiced,
    cogs_refund_invoiced,
    aws_rev_share_invoiced,
    aws_refund_share_invoiced,
    aws_tax_share_invoiced,
    aws_tax_share_listing_fee_invoiced,
    aws_tax_share_refund_invoiced,
    aws_tax_share_refund_listing_fee_invoiced,
    seller_tax_share_invoiced,
    seller_tax_share_refund_invoiced,
    balance_adjustment_invoiced,
    seller_rev_credit_invoiced,
    aws_ref_fee_credit_invoiced,
    gross_revenue_disbursed,
    gross_refund_disbursed,
    cogs_disbursed,
    cogs_refund_disbursed,
    aws_rev_share_disbursed,
    aws_refund_share_disbursed,
    aws_tax_share_disbursed,
    aws_tax_share_listing_fee_disbursed,
    aws_tax_share_refund_disbursed,
    aws_tax_share_refund_listing_fee_disbursed,
    seller_tax_share_disbursed,
    seller_tax_share_refund_disbursed,
    balance_adjustment_disbursed,
    seller_rev_credit_disbursed,
    aws_ref_fee_credit_disbursed,
    (gross_revenue_invoiced + gross_revenue_disbursed) as uncollected_gross_revenue,
    -- net revenue = gross revenue - listing fee - tax - cogs
    (gross_revenue_invoiced + gross_refund_invoiced + aws_rev_share_invoiced + aws_refund_share_invoiced + seller_tax_share_invoiced + seller_tax_share_refund_invoiced + cogs_invoiced + cogs_refund_invoiced + aws_tax_share_listing_fee_invoiced + aws_tax_share_refund_listing_fee_invoiced) as seller_net_revenue,
    (gross_revenue_invoiced + gross_refund_invoiced + aws_rev_share_invoiced + aws_refund_share_invoiced + seller_tax_share_invoiced + seller_tax_share_refund_invoiced + cogs_invoiced + cogs_refund_invoiced + aws_tax_share_listing_fee_invoiced + aws_tax_share_refund_listing_fee_invoiced
      + gross_revenue_disbursed + gross_refund_disbursed + aws_rev_share_disbursed + aws_refund_share_disbursed + seller_tax_share_disbursed + seller_tax_share_refund_disbursed + cogs_disbursed + cogs_refund_disbursed + aws_tax_share_listing_fee_disbursed + aws_tax_share_refund_listing_fee_disbursed) as uncollected_seller_net_revenue,
    last_disbursement_date,
    last_disbursement_id,
    last_disburse_bank_trace_id,
    disbursement_date_list,
    disburse_bank_trace_id_list,
    product_code,
    manufacturer_aws_account_id,
    manufacturer_account_id,
    acc_manu.mailing_company_name as manufacturer_company_name,
    cast(null as varchar) as AR_Period,
    case
      when (
        (gross_revenue_invoiced '<>0 and gross_revenue_invoiced = -1 * gross_revenue_disbursed)
        or (gross_refund_invoiced '<> 0 and gross_refund_invoiced = -1 * gross_refund_disbursed)
        or (balance_adjustment_invoiced '<> 0 and balance_adjustment_invoiced = -1 * balance_adjustment_disbursed)
        or (seller_tax_share_refund_invoiced '<> 0 and seller_tax_share_refund_invoiced = -1 * seller_tax_share_refund_disbursed)
        or (gross_revenue_invoiced = 0 and gross_refund_invoiced = 0 and balance_adjustment_invoiced = 0 and seller_tax_share_refund_invoiced = 0 and last_disbursement_id is not null)) then 'Yes'
      when gross_revenue_disbursed = 0 and gross_refund_disbursed = 0 and balance_adjustment_disbursed = 0 and seller_tax_share_disbursed = 0 and seller_tax_share_refund_disbursed = 0 then 'No'
      else 'Partial'
    end as Disbursement_Flag
  from line_items_with_window_functions_enrich_offer_product_address as line
  left join accounts_with_history_with_company_name as acc_manu on
    line.manufacturer_account_id = acc_manu.account_id and line.buyer_invoice_date >= acc_manu.valid_from_adjusted and line.buyer_invoice_date <= acc_manu.valid_to
  left join accounts_with_history_with_company_name as acc_proposer on
    line.proposer_account_id = acc_proposer.account_id and line.buyer_invoice_date >= acc_proposer.valid_from and line.buyer_invoice_date < acc_proposer.valid_to
  left join address_with_latest_revision as add_payer on
    line.payer_address_id = add_payer.address_id
  left join address_with_latest_revision as add_subscriber on
    line.subscriber_address_id = add_subscriber.address_id
  left join address_with_latest_revision as add_enduser on
    line.end_user_address_id = add_enduser.address_id
  group by
    line.internal_buyer_line_item_id,
    disbursement_id,
    disbursement_id_or_invoiced,
    product_id,
    legacy_product_id,
    product_title,
    broker_id,
    currency,
    end_user_address_id,
    end_user_account_id,
    end_user_encrypted_account_id,
    end_user_aws_account_id,
    add_enduser.company_name,
    add_enduser.email_domain,
    add_enduser.city,
    add_enduser.state_or_region,
    add_enduser.country_code,
    add_enduser.postal_code,
    payer_aws_account_id,
    payer_encrypted_account_id,
    payer_address_id,
    add_payer.company_name,
    add_payer.email_domain,
    add_payer.city,
    add_payer.state_or_region,
    add_payer.country_code,
    add_payer.postal_code,
    agreement_id,
    agreement_revision,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.aws_account_id end,
    case when proposer_account_id = (select seller_account_id from seller_account) then null else acc_proposer.mailing_company_name end,
    agreement_start_date,
    agreement_end_date,
    agreement_acceptance_date,
    agreement_updated_date,
    usage_period_start_date,
    usage_period_end_date,
    acceptor_account_id,
    subscriber_aws_account_id,
    subscriber_encrypted_account_id,
    subscriber_address_id,
    add_subscriber.company_name,
    add_subscriber.email_domain,
    add_subscriber.city,
    add_subscriber.state_or_region,
    add_subscriber.country_code,
    add_subscriber.postal_code,
    offer_id,
    offer_target,
    offer_name,
    offer_opportunity_name,
    offer_opportunity_description,
    opportunity_id,
    payment_due_date,
    bank_trace_id,
    disbursement_date,
    billing_address_id,
    gross_revenue_this_disbursement_id_or_invoiced,
    gross_refund_this_disbursement_id_or_invoiced,
    cogs_this_disbursement_id_or_invoiced,
    cogs_refund_this_disbursement_id_or_invoiced,
    aws_rev_share_this_disbursement_id_or_invoiced,
    aws_refund_share_this_disbursement_id_or_invoiced,
    aws_tax_share_this_disbursement_id_or_invoiced,
    aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_this_disbursement_id_or_invoiced,
    aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,
    seller_tax_share_this_disbursement_id_or_invoiced,
    seller_tax_share_refund_this_disbursement_id_or_invoiced,
    balance_adjustment_this_disbursement_id_or_invoiced,
    seller_rev_credit_this_disbursement_id_or_invoiced,
    aws_ref_fee_credit_this_disbursement_id_or_invoiced,
    gross_revenue_invoiced,
    gross_refund_invoiced,
    cogs_invoiced,
    cogs_refund_invoiced,
    aws_rev_share_invoiced,
    aws_refund_share_invoiced,
    aws_tax_share_invoiced,
    aws_tax_share_listing_fee_invoiced,
    aws_tax_share_refund_invoiced,
    aws_tax_share_refund_listing_fee_invoiced,
    seller_tax_share_invoiced,
    seller_tax_share_refund_invoiced,
    balance_adjustment_invoiced,
    seller_rev_credit_invoiced,
    aws_ref_fee_credit_invoiced,
    gross_revenue_disbursed,
    gross_refund_disbursed,
    cogs_disbursed,
    cogs_refund_disbursed,
    aws_rev_share_disbursed,
    aws_refund_share_disbursed,
    aws_tax_share_disbursed,
    aws_tax_share_listing_fee_disbursed,
    aws_tax_share_refund_disbursed,
    aws_tax_share_refund_listing_fee_disbursed,
    seller_tax_share_disbursed,
    seller_tax_share_refund_disbursed,
    balance_adjustment_disbursed,
    seller_rev_credit_disbursed,
    aws_ref_fee_credit_disbursed,
    last_disbursement_date,
    last_disbursement_id,
    last_disburse_bank_trace_id,
    disbursement_date_list,
    disburse_bank_trace_id_list,
    product_code,
    manufacturer_aws_account_id,
    manufacturer_account_id,
    acc_manu.mailing_company_name,
    proposer_account_id,
    acc_proposer.aws_account_id
),
invoiced_not_disbursed as(
  select
    --we will filter on rownum =1 in next step,
    -- means internal_buyer_line_item_id, there's only '<invoiced> record, no disbursement_id linked
    *,
    max(case when disbursement_id_or_invoiced = ''<invoiced>' then 1 else 2 end)
      over (partition by internal_buyer_line_item_id) rownum
  from line_items_with_window_functions_enrich_offer_product_address_name as line_items

),
collections_and_disbursements as (
  select
    ------------------
    -- Invoice Info --
    ------------------
    buyer_invoice_date as Invoice_Date,
    Payment_Due_Date as Payment_Due_Date,
    concat(
      'Net ',
      case
        when abs(date_diff('Day', Payment_due_date, buyer_invoice_date))>180 then '180+'
        else cast(abs(date_diff('Day', Payment_due_date, buyer_invoice_date)) as varchar)
        end,
      ' days'
    ) as payment_terms,
    buyer_invoice_id as Invoice_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when seller_invoice_id = '' then null else seller_invoice_id end,
      'Not applicable') as Listing_Fee_Invoice_ID,

    ---------------------------
    --End user Information --
    ---------------------------
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when End_User_Company_Name = '' then null else End_User_Company_Name end,
      'Not available') as End_User_Company_Name,
    End_User_AWS_Account_ID,
    End_User_Encrypted_Account_ID,
    End_User_Email_Domain,
    End_User_City,
    End_User_State as End_User_State_or_Region,
    End_User_Country,
    End_User_Postal_Code,
    End_User_Address_ID,

    ---------------------------
    --Subscriber Information --
    ---------------------------
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Company_Name is null or Subscriber_Company_Name = '' then 'Not provided'
      else Subscriber_Company_Name
    end as Subscriber_Company_Name,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Subscriber_AWS_Account_ID
    end as Subscriber_AWS_Account_ID,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Subscriber_Encrypted_Account_ID
    end as Subscriber_Encrypted_Account_ID,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Email_Domain is null or Subscriber_Email_Domain = '' then 'Not provided'
      else Subscriber_Email_Domain
    end as Subscriber_Email_Domain,
    case
      when Agreement_id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_City is null or Subscriber_City = '' then 'Not provided'
      else Subscriber_City
    end as Subscriber_City,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_State is null or Subscriber_State = '' then 'Not provided'
      else Subscriber_State
    end as Subscriber_State_or_Region,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Country is null or Subscriber_Country = '' then 'Not provided'
      else Subscriber_Country
    end as Subscriber_Country,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Postal_Code is null or Subscriber_Postal_Code = '' then 'Not provided'
      else Subscriber_Postal_Code
    end as Subscriber_Postal_Code,
    case
      when Agreement_ID is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Address_ID is null or Subscriber_Address_ID = '' then 'Not provided'
      else Subscriber_Address_ID
    end as Subscriber_Address_ID,

    ----------------------
    -- Procurement Info --
    ----------------------
    -- product title at time of invoice. It is possible that the title changes over time and therefore there may be multiple product titles mapped to a single product id.
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Product_Title = '' then null else Product_Title end,
      'Not provided') as Product_Title,
    -- offer name at time of invoice. It is possible that the name changes over time therefore there may be multiple offer names mapped to a single offer id.
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when (Offer_Name is null or Offer_Name = '') and Offer_Target = 'Public' then 'Not applicable'
      else Offer_Name
    end as Offer_Name,
    case
      when Agreement_Id is null or Agreement_ID = ''
      then 'Not available'
      else Offer_ID
    end as Offer_ID,
    -- offer visibility at time of invoice.,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Offer_Target
    end as Offer_Visibility,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Agreement_ID = '' then null else Agreement_ID end,
      'Not available') as Agreement_ID,
    Agreement_Start_Date,
    Agreement_Acceptance_Date,
    Agreement_End_Date,

    Usage_Period_Start_Date,
    Usage_Period_End_Date,

    -----------------------
    -- Disbursement Info --
    -----------------------
    case
      when Disbursement_Flag = 'Yes' then 'Disbursed'
      when Disbursement_Flag = 'No' then 'Not Disbursed'
      else 'Other'
    end as Disbursement_Status,
    last_disbursement_date as disbursement_date,
    case
      when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date))
      else null
    end as Disbursement_Time,
    case
      when Disbursement_Flag = 'No' then 'Not applicable'
      when bank_trace_id is null or bank_trace_id = '' then 'Not available'
      else bank_trace_id
    end as disburse_bank_trace_id,

    --------------
    -- Revenues --
    --------------
    -- We are rounding the sums using 2 decimal precision
    -- Note that the rounding method might differ between SQL implementations.
    -- The monthly revenue report is using RoundingMode.HALF_UP. This might create tiny discrepancies between this SQL output
    -- and the legacy report
    round(-1 * gross_revenue_this_disbursement_id_or_invoiced,2) as Gross_Revenue,
    round(-1 * gross_refund_this_disbursement_id_or_invoiced,2) as Gross_Refund,
    round(-1 * aws_rev_share_this_disbursement_id_or_invoiced,2) as Listing_Fee,
    round(-1 * aws_refund_share_this_disbursement_id_or_invoiced,2) as Listing_Fee_Refund,
    truncate(
      case
        when gross_revenue_this_disbursement_id_or_invoiced != 0 then abs(aws_rev_share_this_disbursement_id_or_invoiced/gross_revenue_this_disbursement_id_or_invoiced)
        when gross_refund_this_disbursement_id_or_invoiced != 0 then abs(aws_refund_share_this_disbursement_id_or_invoiced/gross_refund_this_disbursement_id_or_invoiced)
        else 0
      end
      ,4) as Listing_Fee_Percentage,
    round(-1 * seller_tax_share_this_disbursement_id_or_invoiced,2) as Seller_Tax_Share,
    round(-1 * seller_tax_share_refund_this_disbursement_id_or_invoiced,2) as Seller_Tax_Share_Refund,
    round(-1 * aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,2) as AWS_Tax_Share_Listing_Fee,
    round(-1 * aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,2) as AWS_Tax_Share_Refund_Listing_Fee,
    round(-1 * cogs_this_disbursement_id_or_invoiced,2) as Wholesale_cost,
    round(-1 * cogs_refund_this_disbursement_id_or_invoiced,2) as Wholesale_cost_Refund,
    round(-1 * seller_net_revenue_this_disbursement_id_or_invoiced,2) as Seller_Net_Revenue,
    currency as Currency,

    substring(internal_buyer_line_item_id,1,strpos(internal_buyer_line_item_id,'-')-1) as Transaction_Reference_ID,
    broker_id as AWS_seller_of_record,

    -----------------
    -- Resale info --
    -----------------
    case
      when Opportunity_Id is null or Opportunity_Id = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Opportunity_Id
    end as Resale_authorization_ID,
    case
      when Offer_Opportunity_Name is null or Offer_Opportunity_Name = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Offer_Opportunity_Name
    end as Resale_authorization_name,
    case
      when Offer_Opportunity_Description is null or Offer_Opportunity_Description = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Offer_Opportunity_Description
    end as Resale_authorization_description,
    case
      when (Reseller_AWS_Account_ID is not null and Reseller_AWS_Account_ID != '')
        and (Reseller_Company_Name is null or Reseller_Company_Name = '') then 'Not available'
      when (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '')
        and (opportunity_id is null or opportunity_id = '') then 'Not applicable'
      when (select seller_account_id from seller_account) '<> manufacturer_aws_account_id
        and (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '') then 'Not applicable'
      else Reseller_Company_Name
    end as Reseller_Company_Name,
    case
      when (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '')
        and (Opportunity_Id is null or Opportunity_Id = '') then 'Not applicable'
      when (select seller_account_id from seller_account) '<> manufacturer_aws_account_id
        and (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '') then 'Not applicable'
      else Reseller_AWS_Account_ID
    end as Reseller_AWS_Account_ID,

    -----------------------
    -- Payer Information --
    -----------------------
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Payer_Company_Name = '' then null else Payer_Company_Name end,
      'Not available') as Payer_Company_Name,
    Payer_AWS_Account_ID, -- "Customer AWS Account Number" in legacy report
    Payer_Encrypted_Account_ID,
    Payer_Email_Domain,
    Payer_City,
    Payer_State as Payer_State_or_Region,
    Payer_Country,
    Payer_Postal_Code,
    Payer_Address_ID,

    ---------------------
    -- ISV Information --
    ---------------------
    manufacturer_aws_account_id as ISV_Account_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Manufacturer_Company_Name = '' then null else Manufacturer_Company_Name end,
      'Not available') as ISV_Company_Name,

    ---------------------
    -- Products info --
    ---------------------
    Legacy_Product_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Product_ID = '' then null else Product_ID end,
      'Not provided') as Product_ID,
    -- this is to get the legacy product id https://sim.amazon.com/issues/MP-INSIGHTS-2561
    Product_Code,

    case when Disbursement_Flag = 'Yes' then round(-1 * seller_net_revenue_this_disbursement_id_or_invoiced,2) else 0 end as Disbursed_Net_Revenue,
    case when Disbursement_Flag = 'No' then round(-1 * seller_net_revenue_this_disbursement_id_or_invoiced,2) else 0 end as Undisbursed_Net_Revenue,
    case
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <= 0 then 'Not due'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=30 then '1-30 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=60 then '31-60 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=90 then '61-90 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=120 then '91-120 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end >=121 then '121+ days late'
      else null
    end as Disbursement_Period
  from
    line_items_with_window_functions_enrich_offer_product_address_name as line
  where disbursement_id_or_invoiced != ''<invoiced>'

  union

  select
    ------------------
    -- Invoice Info --
    ------------------
    buyer_invoice_date as Invoice_Date,
    Payment_Due_Date as Payment_Due_Date,
    concat(
      'Net ',
      case
        when abs(date_diff('Day', Payment_due_date, buyer_invoice_date)) >180 then '180+'
        else cast(abs(date_diff('Day', Payment_due_date, buyer_invoice_date)) as varchar)
      end,
      ' days'
    ) as payment_terms,
    buyer_invoice_id as Invoice_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when seller_invoice_id = '' then null else seller_invoice_id end,
      'Not applicable') as Listing_Fee_Invoice_ID,

    ---------------------------
    --End user Information --
    ---------------------------
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when End_User_Company_Name = '' then null else End_User_Company_Name end,
      'Not available') as End_User_Company_Name,
    End_User_AWS_Account_ID,
    End_User_Encrypted_Account_ID,
    End_User_Email_Domain,
    End_User_City,
    End_User_State as End_User_State_or_Region,
    End_User_Country,
    End_User_Postal_Code,
    End_User_Address_ID,

    ---------------------------
    --Subscriber Information --
    ---------------------------
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Company_Name is null or Subscriber_Company_Name = '' then 'Not provided'
      else Subscriber_Company_Name
    end as Subscriber_Company_Name,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Subscriber_AWS_Account_ID
    end as Subscriber_AWS_Account_ID,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Subscriber_Encrypted_Account_ID
    end as Subscriber_Encrypted_Account_ID,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Email_Domain is null or Subscriber_Email_Domain = '' then 'Not provided'
      else Subscriber_Email_Domain
    end as Subscriber_Email_Domain,
    case
      when Agreement_id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_City is null or Subscriber_City = '' then 'Not provided'
      else Subscriber_City
    end as Subscriber_City,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_State is null or Subscriber_State = '' then 'Not provided'
      else Subscriber_State
    end as Subscriber_State_or_Region,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Country is null or Subscriber_Country = '' then 'Not provided'
      else Subscriber_Country
    end as Subscriber_Country,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Postal_Code is null or Subscriber_Postal_Code = '' then 'Not provided'
      else Subscriber_Postal_Code
    end as Subscriber_Postal_Code,
    case
      when Agreement_ID is null or Agreement_ID = '' then 'Not available'
      when Subscriber_Address_ID is null or Subscriber_Address_ID = '' then 'Not provided'
      else Subscriber_Address_ID
    end as Subscriber_Address_ID,

    ----------------------
    -- Procurement Info --
    ----------------------
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Product_Title = '' then null else Product_Title end,
      'Not provided') as Product_Title,
    -- offer name at time of invoice. It is possible that the name changes over time therefore there may be multiple offer names mapped to a single offer id.
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      when (Offer_Name is null or Offer_Name = '') and Offer_Target = 'Public' then 'Not applicable'
      else Offer_Name
    end as Offer_Name,
    case
      when Agreement_Id is null or Agreement_ID = ''
      then 'Not available'
      else Offer_ID
    end as Offer_ID,
    -- offer visibility at time of invoice.,
    case
      when Agreement_Id is null or Agreement_ID = '' then 'Not available'
      else Offer_Target
    end as Offer_Visibility,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Agreement_ID = '' then null else Agreement_ID end,
      'Not available') as Agreement_ID,
    --case when Agreement_Id is null or Agreement_Id = '' then cast(null as timestamp) else Agreement_Start_Date end as Agreement_Start_Date,
    --case when Agreement_Id is null or Agreement_Id = '' then cast(null as timestamp) else Agreement_End_Date end as Agreement_End_Date,
    --case when Agreement_Id is null or Agreement_Id = '' then cast(null as timestamp) else Agreement_Acceptance_Date end as Agreement_Acceptance_Date,
    Agreement_Start_Date,
    Agreement_Acceptance_Date,
    Agreement_End_Date,

    Usage_Period_Start_Date,
    Usage_Period_End_Date,

    -----------------------
    -- Disbursement Info --
    -----------------------
    case
      when Disbursement_Flag = 'Yes' then 'Disbursed'
      when Disbursement_Flag = 'No' then 'Not Disbursed'
      else 'Other'
    end as Disbursement_Status,
    last_disbursement_date as disbursement_date,
    case
      when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date))
      else null
    end as Disbursement_Time,
    case
      when Disbursement_Flag = 'No' then 'Not applicable'
      when bank_trace_id is null or bank_trace_id = '' then 'Not available'
      else bank_trace_id
    end as disburse_bank_trace_id,

    --------------
    -- Revenues --
    --------------
    -- We are rounding the sums using 2 decimal precision
    -- Note that the rounding method might differ between SQL implementations.
    -- The monthly revenue report is using RoundingMode.HALF_UP. This might create tiny discrepancies between this SQL output
    -- and the legacy report
    round(gross_revenue_this_disbursement_id_or_invoiced,2) as Gross_Revenue,
    round(gross_refund_this_disbursement_id_or_invoiced,2) as Gross_Refund,
    round(aws_rev_share_this_disbursement_id_or_invoiced,2) as Listing_Fee,
    round(aws_refund_share_this_disbursement_id_or_invoiced,2) as Listing_Fee_Refund,
    truncate(
      case
        when gross_revenue_this_disbursement_id_or_invoiced != 0 then abs(aws_rev_share_this_disbursement_id_or_invoiced/gross_revenue_this_disbursement_id_or_invoiced)
        when gross_refund_this_disbursement_id_or_invoiced != 0 then abs(aws_refund_share_this_disbursement_id_or_invoiced/gross_refund_this_disbursement_id_or_invoiced)
        else 0
      end
      ,4) as Listing_Fee_Percentage,
    round(seller_tax_share_this_disbursement_id_or_invoiced,2) as Seller_Tax_Share,
    round(seller_tax_share_refund_this_disbursement_id_or_invoiced,2) as Seller_Tax_Share_Refund,
    round(aws_tax_share_listing_fee_this_disbursement_id_or_invoiced,2) as AWS_Tax_Share_Listing_Fee,
    round(aws_tax_share_refund_listing_fee_this_disbursement_id_or_invoiced,2) as AWS_Tax_Share_Refund_Listing_Fee,
    round(cogs_this_disbursement_id_or_invoiced,2) as Wholesale_cost,
    round(cogs_refund_this_disbursement_id_or_invoiced,2) as Wholesale_cost_Refund,
    round(seller_net_revenue_this_disbursement_id_or_invoiced,2) as Seller_Net_Revenue,
    currency as Currency,

    substring(internal_buyer_line_item_id,1,strpos(internal_buyer_line_item_id,'-')-1) as Transaction_Reference_ID,
    broker_id as AWS_seller_of_record,

    -----------------
    -- Resale info --
    -----------------
    case
      when Opportunity_Id is null or Opportunity_Id = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Opportunity_Id
    end as Resale_authorization_ID,
    case
      when Offer_Opportunity_Name is null or Offer_Opportunity_Name = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Offer_Opportunity_Name
    end as Resale_authorization_name,
    case
      when Offer_Opportunity_Description is null or Offer_Opportunity_Description = '' then
        case
          when Offer_Target = 'Public' then 'Not applicable'
          when (Offer_Target is null or Offer_Target = '') and (Agreement_Id is not null and Agreement_Id != '') then 'Not applicable'
          else null
        end
      else Offer_Opportunity_Description
    end as Resale_authorization_description,
    case
      when (Reseller_AWS_Account_ID is not null and Reseller_AWS_Account_ID != '')
        and (Reseller_Company_Name is null or Reseller_Company_Name = '') then 'Not available'
      when (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '')
        and (opportunity_id is null or opportunity_id = '') then 'Not applicable'
      when (select seller_account_id from seller_account) '<> manufacturer_aws_account_id
        and (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '') then 'Not applicable'
      else Reseller_Company_Name
    end as Reseller_Company_Name,
    case
      when (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '')
        and (Opportunity_Id is null or Opportunity_Id = '') then 'Not applicable'
      when (select seller_account_id from seller_account) '<> manufacturer_aws_account_id
        and (Reseller_AWS_Account_ID is null or Reseller_AWS_Account_ID = '') then 'Not applicable'
      else Reseller_AWS_Account_ID
    end as Reseller_AWS_Account_ID,

    -----------------------
    -- Payer Information --
    -----------------------
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Payer_Company_Name = '' then null else Payer_Company_Name end,
      'Not available') as Payer_Company_Name,
    Payer_AWS_Account_ID, -- "Customer AWS Account Number" in legacy report
    Payer_Encrypted_Account_ID,
    Payer_Email_Domain,
    Payer_City,
    Payer_State as Payer_State_or_Region,
    Payer_Country,
    Payer_Postal_Code,
    Payer_Address_ID,

    ---------------------
    -- ISV Information --
    ---------------------
    manufacturer_aws_account_id as ISV_Account_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Manufacturer_Company_Name = '' then null else Manufacturer_Company_Name end,
      'Not available') as ISV_Company_Name,

    ---------------------
    -- Products info --
    ---------------------
    -- product title at time of invoice. It is possible that the title changes over time and therefore there may be multiple product titles mapped to a single product id.
    Legacy_Product_ID,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when Product_ID = '' then null else Product_ID end,
      'Not provided') as Product_ID,
    -- this is to get the legacy product id https://sim.amazon.com/issues/MP-INSIGHTS-2561
    Product_Code,

    case when Disbursement_Flag = 'Yes' then round(seller_net_revenue_this_disbursement_id_or_invoiced,2) else 0 end as Disbursed_Net_Revenue,
    case when Disbursement_Flag = 'No' then round(seller_net_revenue_this_disbursement_id_or_invoiced,2) else 0 end as Undisbursed_Net_Revenue,
    case
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <= 0 then 'Not due'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=30 then '1-30 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=60 then '31-60 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=90 then '61-90 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end <=120 then '91-120 days late'
      when case when Disbursement_Flag = 'Yes' then date_diff('DAY', date_trunc('DAY',payment_due_date), date_trunc('DAY',last_disbursement_date)) else null end >=121 then '121+ days late'
      else null
    end as Disbursement_Period
  from
    invoiced_not_disbursed
  where rownum = 1

)

select *
from collections_and_disbursements
where payment_due_date >= date_add('DAY', -90, current_date)
--where payment_due_date between cast('2023-01-01' as timestamp) and cast('2024-12-31' as timestamp)

--where disbursement_date >= date_add('DAY', -90, current_date)
--where disbursement_date between cast('2023-01-01' as timestamp) and cast('2024-12-31' as timestamp)
```

## Besteuerte Rechnungen
<a name="data-feed-example-tax"></a>

Um Ihre besteuerten Rechnungen zu finden, können Sie eine Reihe von Abfragen wie im folgenden Beispiel ausführen. Die Abfragen bauen aufeinander auf, um den **Steuerbericht** zu erstellen. Sie können das Beispiel wie abgebildet verwenden oder es an Ihre Daten und Anwendungsfälle anpassen.

In den Kommentaren in den Abfragen wird erklärt, was die Abfragen bewirken und wie sie geändert werden können.

```
-- Taxation report

-- General note: When executing this query we are assuming that the data ingested in the database is using
-- two time axes (the valid_from column and the update_date column).
-- See documentation for more details: https://docs.aws.amazon.com/marketplace/latest/userguide/data-feed.html#data-feed-details

-- An account_id has several valid_from dates (each representing a separate revision of the data)
-- but because of bi-temporality, an account_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
with accounts_with_uni_temporal_data as (
  select
    account_id,
    aws_account_id,
    encrypted_account_id,
    mailing_address_id,
    tax_address_id,
    tax_legal_name,
    from_iso8601_timestamp(valid_from) as valid_from,
    tax_registration_number
  from
    (
      select
        account_id,
        aws_account_id,
        encrypted_account_id,
        mailing_address_id,
        tax_address_id,
        tax_legal_name,
        valid_from,
        delete_date,
        tax_registration_number,
        row_number() over (partition by account_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
      from
        accountfeed_v1
    )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

accounts_with_history as (
  with accounts_with_history_with_extended_valid_from as (
    select
      account_id,
      -- sometimes, this columns gets imported as a "bigint" and loses heading 0s -> casting to a char and re-adding heading 0s (if need be)
      substring('000000000000'||cast(aws_account_id as varchar),-12) as aws_account_id,
      encrypted_account_id,
      mailing_address_id,
      tax_address_id,
      tax_legal_name tax_legal_name,
      -- The start time of account valid_from is extended to '1970-01-01 00:00:00', because:
      -- ... in tax report transformations, some tax line items with invoice_date cannot
      -- ... fall into the default valid time range of the associated account
      CASE
        WHEN LAG(valid_from) OVER (PARTITION BY account_id ORDER BY valid_from ASC) IS NULL
            THEN CAST('1970-01-01 00:00:00' as timestamp)
        ELSE valid_from
      END AS valid_from
    from
      (select * from accounts_with_uni_temporal_data ) as account
  )
  select
    account_id,
    aws_account_id,
    encrypted_account_id,
    mailing_address_id,
    tax_address_id,
    tax_legal_name,
    valid_from,
    coalesce(
      lead(valid_from) over (partition by account_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp)
    ) as valid_to
  from
    accounts_with_history_with_extended_valid_from
),

-- A product_id has several valid_from dates (each representing a product revision),
-- but because of bi-temporality, each product_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
products_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    from_iso8601_timestamp(delete_date) as delete_date,
    product_id,
    manufacturer_account_id,
    product_code,
    title
  from
    (
      select
        valid_from,
        update_date,
        delete_date,
        product_id,
        manufacturer_account_id,
        product_code,
        title,
        row_number() over (partition by product_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
      from
       productfeed_v1
      )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

products_with_history as (
  select
    product_id,
    title,
    valid_from,    
    case
      when lag(valid_from) over (partition by product_id order by valid_from asc) is null and valid_from < cast('2021-04-01' as timestamp)
        then date_add('Day', -3857, valid_from)
      -- 3827 is the longest delay between acceptance_date of an agreement and the product
      -- we are keeping 3857 as a consistency between the offers and products
      when lag(valid_from) over (partition by product_id order by valid_from asc) is null and valid_from >= cast('2021-04-01' as timestamp)
        then date_add('Day', -2190, valid_from)
      --after 2021 for the two offers we need to adjust for 2 more years
      else valid_from end as valid_from_adjusted,
    coalesce(
      lead(valid_from) over (partition by product_id order by valid_from asc),
      cast('2999-01-01 00:00:00' as timestamp)
    ) as valid_to,
    product_code,
    manufacturer_account_id
  from
    products_with_uni_temporal_data
),

-- A tax_item_id has several valid_from dates (each representing a product revision),
-- but because of bi-temporality, each tax_item_id + valid_from tuple can appear multiple times with a different update_date.
-- We are only interested in the most recent tuple (ie, uni-temporal model)
tax_items_with_uni_temporal_data as (
  select
    from_iso8601_timestamp(valid_from) as valid_from,
    from_iso8601_timestamp(update_date) as update_date,
    delete_date,
    cast(tax_item_id as varchar) as tax_item_id,
    cast(invoice_id as varchar) as invoice_id,
    cast(line_item_id as varchar) as line_item_id,
    cast(customer_bill_id as varchar) as customer_bill_id,
    tax_liable_party,
    transaction_type_code,
    product_id,
    product_tax_code,
    from_iso8601_timestamp(invoice_date) as invoice_date,
    taxed_customer_account_id,
    taxed_customer_country,
    taxed_customer_state_or_region,
    taxed_customer_city,
    taxed_customer_postal_code,
    tax_location_code_taxed_jurisdiction,
    tax_type_code,
    jurisdiction_level,
    taxed_jurisdiction,
    display_price_taxability_type,
    tax_jurisdiction_rate,
    tax_amount,
    tax_currency,
    tax_calculation_reason_code,
    date_used_for_tax_calculation,
    customer_exemption_certificate_id,
    customer_exemption_certificate_id_domain,
    customer_exemption_certificate_level,
    customer_exemption_code,
    customer_exemption_domain,
    transaction_reference_id
  from
    (
      select
        valid_from,
        update_date,
        delete_date,
        tax_item_id,
        invoice_id,
        line_item_id,
        customer_bill_id,
        tax_liable_party,
        transaction_type_code,
        product_id,
        product_tax_code,
        invoice_date,
        taxed_customer_account_id,
        taxed_customer_country,
        taxed_customer_state_or_region,
        taxed_customer_city,
        taxed_customer_postal_code,
        tax_location_code_taxed_jurisdiction,
        tax_type_code,
        jurisdiction_level,
        taxed_jurisdiction,
        display_price_taxability_type,
        tax_jurisdiction_rate,
        tax_amount,
        tax_currency,
        tax_calculation_reason_code,
        date_used_for_tax_calculation,
        customer_exemption_certificate_id,
        customer_exemption_certificate_id_domain,
        customer_exemption_certificate_level,
        customer_exemption_code,
        customer_exemption_domain,
        transaction_reference_id,
        row_number() over (partition by tax_item_id, valid_from order by from_iso8601_timestamp(update_date) desc) as row_num
      from
        taxitemfeed_v1
    )
  where
    -- keep latest ...
    row_num = 1
    -- ... and remove the soft-deleted one.
    and (delete_date is null or delete_date = '')
),

taxation as (
  select
    tax_items.invoice_id,
    tax_items.line_item_id,
    tax_items.customer_bill_id,
    tax_items.tax_liable_party,
    tax_items.transaction_type_code,
    tax_items.product_id,
    product_tax_item.title as product_title,
    tax_items.product_tax_code,
    tax_items.invoice_date,
    accounts_with_history.aws_account_id as taxed_customer_account_id,
    tax_items.taxed_customer_country,
    tax_items.taxed_customer_state_or_region,
    tax_items.taxed_customer_city,
    tax_items.taxed_customer_postal_code,
    tax_items.tax_type_code as tax_type,
    tax_items.jurisdiction_level,
    tax_items.taxed_jurisdiction,
    tax_items.display_price_taxability_type,
    tax_items.tax_jurisdiction_rate,
    tax_items.tax_amount,
    tax_items.tax_currency,
    tax_items.tax_calculation_reason_code,
    tax_items.date_used_for_tax_calculation,
    coalesce(
      --empty value in Athena shows as '', change all '' value to null
      case when tax_items.customer_exemption_certificate_id = '' then null else tax_items.customer_exemption_certificate_id end,
      'Not exempt') customer_exemption_certificate_id,
    coalesce(--empty value in Athena shows as '', change all '' value to null
      case when tax_items.customer_exemption_certificate_id_domain = '' then null else tax_items.customer_exemption_certificate_id_domain end,
      'Not exempt') customer_exemption_certificate_id_domain,
    coalesce(--empty value in Athena shows as '', change all '' value to null
      case when tax_items.customer_exemption_certificate_level = '' then null else tax_items.customer_exemption_certificate_level end,
      'Not exempt') customer_exemption_certificate_level,
    coalesce(--empty value in Athena shows as '', change all '' value to null
      case when tax_items.customer_exemption_code = '' then null else tax_items.customer_exemption_code end,
      'Not exempt') customer_exemption_code,
    tax_items.transaction_reference_id
  from
    tax_items_with_uni_temporal_data as tax_items
    left join products_with_history as product_tax_item on
      tax_items.product_id = product_tax_item.product_id and tax_items.invoice_date >= product_tax_item.valid_from_adjusted and tax_items.invoice_date < product_tax_item.valid_to
    left join accounts_with_history as accounts_with_history on
      tax_items.taxed_customer_account_id = accounts_with_history.account_id and tax_items.invoice_date >= accounts_with_history.valid_from and tax_items.invoice_date < accounts_with_history.valid_to

)

select *
from taxation
where invoice_date >= date_add('DAY', -90, current_date)
--where invoice_date between cast('2023-01-01' as timestamp) and cast('2024-12-31' as timestamp)
```

## Auszahlungen nach Produkten
<a name="data-feed-example-disbursement-by-product"></a>

Um die nach Produkten ausgezahlten Beträge zu ermitteln, können Sie eine Reihe von Abfragen wie die folgende ausführen. 

Diese Beispielabfragen bauen aufeinander auf, um die endgültige Liste der Produktdetails mit Auszahlungen zu erstellen. Außerdem wird gezeigt, wie Sie die Produktinformationen zu einem bestimmten Zeitpunkt abrufen können. Sie können dieses Beispiel wie abgebildet verwenden oder es an Ihre Daten und Anwendungsfälle anpassen.

In den Kommentaren in den Abfragen wird erklärt, was die Abfragen bewirken und wie sie geändert werden können.

**Anmerkung**  
Bei der Ausführung dieser Abfrage gehen wir davon aus, dass die Daten anhand von zwei Zeitachsen, den `update` Spalten `valid_from` und, aufgenommen werden. Weitere Informationen zu den Achsen finden Sie unter[Speicherung und Struktur von AWS Marketplace Datenfeeds](data-feed-details.md).

```
    -- Get all the products and keep the latest product_id, valid_from tuple
    with products_with_uni_temporal_data as (
      select
       *
      from
      (
        select
         *,
         ROW_NUMBER() OVER (PARTITION BY product_id, valid_from 
             ORDER BY from_iso8601_timestamp(update_date) desc) 
             as row_num
        from
         productfeed_v1
      )
      where
        -- A product_id can appear multiple times with the same 
        -- valid_from date but with a different update_date column,
        -- making it effectively bi-temporal. By only taking the most
        -- recent tuple, we are converting to a uni-temporal model.
        row_num = 1
    ),

    -- Gets the latest revision of a product
    -- A product can have multiple revisions where some of the 
    -- columns, like the title, can change.
    -- For the purpose of the disbursement report, we want 
    -- to get the latest revision of a product
    products_with_latest_version as (
     select
      *
     from
     (
      select
       *,
       ROW_NUMBER() OVER (PARTITION BY product_id 
           ORDER BY from_iso8601_timestamp(valid_from) desc) 
           as row_num_latest_version
      from
       products_with_uni_temporal_data
     )
     where
      row_num_latest_version = 1
   ),

    -- Get all the accounts and keep the latest account_id, valid_from tuple
    accounts_with_uni_temporal_data as (
      select
       *
      from
      (
        select
         *,
         ROW_NUMBER() OVER (PARTITION BY account_id, valid_from ORDER BY from_iso8601_timestamp(update_date) desc) as row_num
        from
         accountfeed_v1
      )
      where
        -- An account_id can appear multiple times with the same 
        -- valid_from date but with a different update_date column,
        -- making it effectively bi-temporal. By only taking the most
        -- recent tuple, we are converting to a uni-temporal model.
        row_num = 1
    ),

    -- Gets the latest revision of an account
    -- An account can have multiple revisions where some of the 
    -- columns, like the mailing_address_id, can change.
    -- For the purpose of the disbursement report, we want 
    -- to get the latest revision of a product
    accounts_with_latest_version as (
     select
      *
     from
     (
      select
       *,
       ROW_NUMBER() OVER (PARTITION BY account_id 
           ORDER BY from_iso8601_timestamp(valid_from) desc) 
           as row_num_latest_version
      from
       accounts_with_uni_temporal_data
     )
     where
      row_num_latest_version = 1
   ),

    -- Get all the billing events and keep the 
    -- latest billing_event_id, valid_from tuple:
    billing_events_with_uni_temporal_data as (
      select
       *
      from (
        select
          billing_event_id,
          from_iso8601_timestamp(valid_from) as valid_from,
          from_iso8601_timestamp(update_date) as update_date,
          from_iso8601_timestamp(invoice_date) as invoice_date,
          transaction_type,
          transaction_reference_id,
          product_id,
          disbursement_billing_event_id,
          action,
          from_account_id,
          to_account_id,
          end_user_account_id,
          CAST(amount as decimal(20, 10)) invoice_amount,
          bank_trace_id,
          ROW_NUMBER() OVER (PARTITION BY billing_event_id, valid_from 
              ORDER BY from_iso8601_timestamp(update_date) desc) 
              as row_num
        from
          billingeventfeed_v1
        )
      where row_num = 1
    ),

    -- Get all the disbursements
    -- The billing events data is immutable.
    -- It is not required to use time windows based on the 
    -- valid_from column to get the most recent billing event
    disbursement_events as (
      select
        billing_events_raw.billing_event_id as disbursement_id,
        billing_events_raw.invoice_date as disbursement_date,
        billing_events_raw.bank_trace_id
      from
        billing_events_with_uni_temporal_data billing_events_raw
      where
        -- Only interested in disbursements, so filter out
        -- non-disbursements by selecting transaction type 
        -- to be DISBURSEMENT:
        billing_events_raw.transaction_type = 'DISBURSEMENT'
        -- Select a time period, you can adjust the dates 
        -- below if need be. For billing events use the 
        -- invoice date as the point in time of the 
        -- disbursement being initiated:
        and billing_events_raw.invoice_date >= 
            from_iso8601_timestamp('2020-10-01T00:00:00Z')
        and billing_events_raw.invoice_date < 
            from_iso8601_timestamp('2020-11-01T00:00:00Z')
    ),

    -- Get the invoices along with the line items that 
    -- are part of the above filtered disbursements
    disbursed_line_items as (
      select
        line_items.transaction_reference_id,
        line_items.product_id,
        line_items.transaction_type,
        (case
           -- Get the payer of the invoice from any 
           -- transaction type that is not AWS and 
           -- not BALANCE_ADJUSTMENT.
           -- For AWS and BALANCE_ADJUSTMENT, the billing 
           -- event feed will show the "AWS Marketplace" 
           -- account as the receiver of the funds and the 
           -- seller as the payer. Filter those out.
           when line_items.transaction_type 
               not like '%AWS%' and transaction_type 
               not like 'BALANCE_ADJUSTMENT' 
               then line_items.from_account_id
        end) as payer_account_id,
        line_items.end_user_account_id,
        invoice_amount,
        disbursements.disbursement_date,
        disbursements.disbursement_id,
        disbursements.bank_trace_id
      from
        billing_events_with_uni_temporal_data line_items
        -- Each disbursed line item is linked to the parent 
        -- disbursement via the disbursement_billing_event_id
        join disbursement_events disbursements 
          on disbursements.disbursement_id 
          = line_items.disbursement_billing_event_id
      where
        -- we are interested only in the invoice line 
        -- items that are DISBURSED
        line_items.action = 'DISBURSED'
    ),

  -- An invoice can contain multiple line items
  -- Create a pivot table to calculate the different 
  -- amounts that are part of an invoice.
  -- The new row is aggregated at 
  -- transaction_reference_id - end_user_account_id level
  invoice_amounts_aggregated as (
    select
      transaction_reference_id,
      product_id,
      -- a given disbursement id should have the 
      -- same disbursement_date
      max(disbursement_date) as disbursement_date,
      -- Build a pivot table in order to provide all the
      -- data related to a transaction in a single row.
      -- Note that the amounts are negated. This is because 
      -- when an invoice is generated, we give you the 
      -- positive amounts and the disbursement event 
      -- negates the amounts
      sum(case when transaction_type = 'SELLER_REV_SHARE' 
          then -invoice_amount else 0 end) as seller_rev_share,
      sum(case when transaction_type = 'AWS_REV_SHARE'  
          then -invoice_amount else 0 end) as aws_rev_share,
      sum(case when transaction_type = 'SELLER_REV_SHARE_REFUND'  
          then -invoice_amount else 0 end) as seller_rev_refund,
      sum(case when transaction_type = 'AWS_REV_SHARE_REFUND'  
          then -invoice_amount else 0 end) as aws_rev_refund,
      sum(case when transaction_type = 'SELLER_REV_SHARE_CREDIT'  
          then -invoice_amount else 0 end) as seller_rev_credit,
      sum(case when transaction_type = 'AWS_REV_SHARE_CREDIT'  
          then -invoice_amount else 0 end) as aws_rev_credit,
      sum(case when transaction_type = 'SELLER_TAX_SHARE'  
          then -invoice_amount else 0 end) as seller_tax_share,
      sum(case when transaction_type = 'SELLER_TAX_SHARE_REFUND'  
          then -invoice_amount else 0 end) as seller_tax_refund,
      -- This is the account that pays the invoice:
      max(payer_account_id) as payer_account_id,
      -- This is the account that subscribed to the product:
      end_user_account_id as customer_account_id,
      bank_trace_id
    from
      disbursed_line_items
    group by
      transaction_reference_id,
      product_id,
      disbursement_id,
      -- There might be a different end-user for the same 
      -- transaction reference id. Distributed licenses 
      -- is an example
      end_user_account_id,
      bank_trace_id
),

disbursed_amount_by_product as (
  select
    products.title as ProductTitle,
    products.product_code as ProductCode,
    -- We are rounding the sums using 2 decimal precision
    -- Note that the rounding method might differ 
    -- between SQL implementations.
    -- The disbursement seller report is using 
    -- RoundingMode.HALF_UP. This might create 
    -- discrepancies between this SQL output
    -- and the disbursement seller report
    round(invoice_amounts.seller_rev_share, 2) as SellerRev,
    round(invoice_amounts.aws_rev_share, 2) as AWSRefFee,
    round(invoice_amounts.seller_rev_refund, 2) as SellerRevRefund,
    round(invoice_amounts.aws_rev_refund, 2) as AWSRefFeeRefund,
    round(invoice_amounts.seller_rev_credit, 2) as SellerRevCredit,
    round(invoice_amounts.aws_rev_credit, 2) as AWSRefFeeCredit,
    (
        round(invoice_amounts.seller_rev_share, 2) +
        round(invoice_amounts.aws_rev_share, 2) +
        round(invoice_amounts.seller_rev_refund, 2) +
        round(invoice_amounts.aws_rev_refund, 2) +
        round(invoice_amounts.seller_rev_credit, 2) +
        round(invoice_amounts.aws_rev_credit, 2)
    ) as NetAmount,
    invoice_amounts.transaction_reference_id  
          as TransactionReferenceID,
    round(invoice_amounts.seller_tax_share, 2)  
          as SellerSalesTax,
    round(invoice_amounts.seller_tax_refund, 2)  
          as SellerSalesTaxRefund,
    payer_info.aws_account_id  
          as PayerAwsAccountId,
    customer_info.aws_account_id  
          as EndCustomerAwsAccountId,
    invoice_amounts.disbursement_date  
          as DisbursementDate,
    invoice_amounts.bank_trace_id  
          as BankTraceId
  from
    invoice_amounts_aggregated invoice_amounts
    join products_with_latest_version products  
      on products.product_id = invoice_amounts.product_id
    left join accounts_with_latest_version payer_info  
      on payer_info.account_id = invoice_amounts.payer_account_id
    left join accounts_with_latest_version customer_info  
      on customer_info.account_id = invoice_amounts.customer_account_id
)

select * from disbursed_amount_by_product;
```

## Sales Compensation Report (Vertriebsvergütungsbericht)
<a name="data-feed-example-sales-compensation"></a>

Um den in Rechnung gestellten Umsatz nach Kunden zu ermitteln, können Sie eine Reihe von Abfragen wie die folgenden ausführen. Diese Beispielabfragen bauen aufeinander auf, um die endgültige Liste der Kundendetails mit dem Gesamtbetrag zu erstellen, der jedem Kunden für die Nutzung Ihrer Software in Rechnung gestellt wird. Sie können die Abfragen wie in der Abbildung gezeigt verwenden oder sie an Ihre Daten und Anwendungsfälle anpassen.

 In den Kommentaren in den Abfragen wird erklärt, was die Abfragen bewirken und wie sie geändert werden können.

**Anmerkung**  
Bei der Ausführung dieser Abfrage gehen wir davon aus, dass die aufgenommenen Daten zwei Zeitachsen (die `valid_from` und die `update` Spalten) verwenden. Weitere Informationen finden Sie unter [Speicherung und Struktur von AWS Marketplace Datenfeeds](data-feed-details.md).

```
    -- Gets all the products and keeps the latest product_id, 
    -- valid_from tuple.
    with products_with_uni_temporal_data as (
      select
       *
      from
      (
        select
         *,
         ROW_NUMBER() OVER (PARTITION BY product_id, valid_from 
                  ORDER BY from_iso8601_timestamp(update_date) desc) 
                  as row_num
        from
         productfeed_v1
      )
      where
        -- A product_id can appear multiple times with the same 
        -- valid_from date but with a different update_date column,
        -- making it effectively bi-temporal. By only taking the most
        -- recent tuple, we are converting to a uni-temporal model.
        row_num = 1
    ),

    -- Gets the latest revision of a product
    -- A product can have multiple revisions where some of the 
    -- columns, like the title, can change.
    -- For the purpose of the sales compensation report, we want 
    -- to get the latest revision of a product
    products_with_latest_revision as (
     select
      *
     from
     (
      select
       *,
       ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY from_iso8601_timestamp(valid_from) desc) as row_num_latest_revision
      from
       products_with_uni_temporal_data
     )
     where
      row_num_latest_revision = 1
   ),

     -- Gets all the addresses and keeps the latest address_id, 
     -- aws_account_id, and valid_from combination.
     -- We're transitioning from a bi-temporal data model to an 
     -- uni-temporal data_model
     piifeed_with_uni_temporal_data as (
       select
        *
       from
       (
         select
          *,
          ROW_NUMBER() OVER (
             PARTITION BY address_id, aws_account_id, valid_from 
             ORDER BY from_iso8601_timestamp(update_date) desc) 
             as row_num
         from
          piifeed
       )
       where
         -- An address_id can appear multiple times with the same
         -- valid_from date but with a different update_date column.
         -- We are only interested in the most recent.
         row_num = 1
     ),

    -- Gets the latest revision of an address.
    -- An address_id can have multiple revisions where some of 
    -- the columns can change.
    -- For the purpose of the sales compensation report, we want to
    -- get the latest revision of an address + account_id pair.
    pii_with_latest_revision as (
      select
       *
      from
      (
       select
        *,
        ROW_NUMBER() OVER (PARTITION BY address_id, aws_account_id 
              ORDER BY from_iso8601_timestamp(valid_from) desc) 
              as row_num_latest_revision
       from
        piifeed_with_uni_temporal_data
      )
      where
       row_num_latest_revision = 1
    ),

    -- Gets all the accounts and keeps the latest 
    -- account_id, valid_from tuple.
    -- We're transitioning from a bi-temporal data 
    -- model to an uni-temporal data_model.
    accounts_with_uni_temporal_data as (
      select
       *
      from
      (
        select
         *,
         ROW_NUMBER() OVER (PARTITION BY account_id, valid_from 
             ORDER BY from_iso8601_timestamp(update_date) desc) 
             as row_num
        from
         accountfeed_v1
      )
      where
        -- An account_id can appear multiple times with the same 
        -- valid_from date but with a different update_date column.
        -- We are only interested in the most recent tuple.
        row_num = 1
    ),

    -- Gets all the historical dates for an account
    -- An account can have multiple revisions where some of the 
    -- columns like the mailing_address_id can change.
    accounts_with_history as (
     select
      *,
      -- This interval's begin_date
      case
        when
        -- First record for a given account_id
          lag(valid_from, 1) over (partition by account_id 
             order by from_iso8601_timestamp(valid_from) asc) is null
        then
          -- 'force' begin_date a bit earlier because of different 
          -- data propagation times. We'll subtract one day as one
          -- hour is not sufficient
          from_iso8601_timestamp(valid_from) - INTERVAL '1' DAY
        else
          -- not the first line -> return the real date
          from_iso8601_timestamp(valid_from)
      end as begin_date,
      -- This interval's end date.
      COALESCE(
           LEAD(from_iso8601_timestamp(valid_from), 1) 
                OVER (partition by account_id 
                ORDER BY from_iso8601_timestamp(valid_from)),
           from_iso8601_timestamp('9999-01-01T00:00:00Z')
      ) as end_date
     from
       accounts_with_uni_temporal_data
   ),

    -- Gets all the billing events and keeps the latest 
    -- billing_event_id, valid_from tuple.
    -- We're transitioning from a bi-temporal data 
    -- model to an uni-temporal data_model.
    billing_events_with_uni_temporal_data as (
      select
       *
      from (
        select
          billing_event_id,
          from_iso8601_timestamp(valid_from) as valid_from,
          from_iso8601_timestamp(update_date) as update_date,
          from_iso8601_timestamp(invoice_date) as invoice_date,
          transaction_type,
          transaction_reference_id,
          product_id,
          disbursement_billing_event_id,
          action,
          currency,
          from_account_id,
          to_account_id,
          end_user_account_id,
          -- convert an empty billing address to null. This will 
          -- later be used in a COALESCE call
          case
           when billing_address_id <> '' then billing_address_id else null
          end as billing_address_id,
          CAST(amount as decimal(20, 10)) invoice_amount,
          ROW_NUMBER() OVER (PARTITION BY billing_event_id, valid_from 
              ORDER BY from_iso8601_timestamp(update_date) desc) 
              as row_num
        from
          billingeventfeed_v1
        where
          -- The Sales Compensation Report does not contain BALANCE 
          -- ADJUSTMENTS, so we filter them out here
          transaction_type <> 'BALANCE_ADJUSTMENT'
          -- Keep only the transactions that will affect any 
          -- future disbursed amounts.
          and balance_impacting = '1'
        )
      where row_num = 1
    ),

    -- Gets the billing address for all DISBURSED invoices. This 
    -- will be the address of the payer when the invoice was paid.
    -- NOTE: For legal reasons, for CPPO transactions, the 
    -- manufacturer will not see the payer's billing address id
    billing_addresses_for_disbursed_invoices as (
      select
        billing_events_raw.transaction_reference_id,
        billing_events_raw.billing_address_id,
        billing_events_raw.from_account_id
      from
        billing_events_with_uni_temporal_data billing_events_raw
      where
        -- the disbursed items will contain the billing address id
        billing_events_raw.action = 'DISBURSED'
        -- we only want to get the billing address id for the 
        -- transaction line items where the seller is the receiver
        -- of the amount
        and billing_events_raw.transaction_type like 'SELLER_%'
      group by
        billing_events_raw.transaction_reference_id,
        billing_events_raw.billing_address_id,
        billing_events_raw.from_account_id
    ),

  -- An invoice can contain multiple line items.
  -- We create a pivot table to calculate the different amounts 
  -- that are part of an invoice.
  -- The new row is aggregated at 
  -- transaction_reference_id - end_user_account_id level
  invoiced_and_forgiven_transactions as (
    select
      transaction_reference_id,
      product_id,
      -- A transaction will have the same invoice date for all 
      -- of its line items (transaction types)
      max(invoice_date) as invoice_date,
      -- A transaction will have the same billing_address_id 
      -- for all of its line items. Remember that the billing event
      -- is uni temporal and we retrieved only the latest valid_from item
      max(billing_address_id) as billing_address_id,
      --  A transaction will have the same currency for all 
      -- of its line items
      max(currency) as currency,
      -- We're building a pivot table in order to provide all the 
      -- data related to a transaction in a single row
      sum(case when transaction_type = 'SELLER_REV_SHARE' 
            then invoice_amount else 0 end) as seller_rev_share,
      sum(case when transaction_type = 'AWS_REV_SHARE' 
            then invoice_amount else 0 end) as aws_rev_share,
      sum(case when transaction_type = 'SELLER_REV_SHARE_REFUND' 
            then invoice_amount else 0 end) as seller_rev_refund,
      sum(case when transaction_type = 'AWS_REV_SHARE_REFUND' 
            then invoice_amount else 0 end) as aws_rev_refund,
      sum(case when transaction_type = 'SELLER_REV_SHARE_CREDIT' 
            then invoice_amount else 0 end) as seller_rev_credit,
      sum(case when transaction_type = 'AWS_REV_SHARE_CREDIT' 
            then invoice_amount else 0 end) as aws_rev_credit,
      sum(case when transaction_type = 'SELLER_TAX_SHARE' 
            then invoice_amount else 0 end) as seller_tax_share,
      sum(case when transaction_type = 'SELLER_TAX_SHARE_REFUND' 
            then invoice_amount else 0 end) as seller_tax_refund,
      -- this is the account that pays the invoice.
      max(case
        -- Get the payer of the invoice from any transaction type 
        -- that is not AWS and not BALANCE_ADJUSTMENT.
        -- For AWS and BALANCE_ADJUSTMENT, the billing event feed 
        -- will show the "AWS Marketplace" account as the
        -- receiver of the funds and the seller as the payer. We 
        -- are not interested in this information here.
        when
         transaction_type not like '%AWS%' 
           and transaction_type not like 'BALANCE_ADJUSTMENT' 
         then from_account_id
       end) as payer_account_id,
      -- this is the account that subscribed to your product
      end_user_account_id as customer_account_id
    from
      billing_events_with_uni_temporal_data
    where
      -- Get invoiced or forgiven items. Disbursements are 
      -- not part of the sales compensation report
      action in ('INVOICED', 'FORGIVEN')
    group by
      transaction_reference_id,
      product_id,
      -- There might be a different end-user for the same 
      -- transaction reference id. Distributed licenses 
      -- is an example.
      end_user_account_id
),

invoiced_items_with_product_and_billing_address as (
  select
    invoice_amounts.*,
    products.product_code,
    products.title,
    payer_info.aws_account_id as payer_aws_account_id,
    payer_info.account_id as payer_reference_id,
    customer_info.aws_account_id as end_user_aws_account_id,
    (
        invoice_amounts.seller_rev_share +
        invoice_amounts.aws_rev_share +
        invoice_amounts.seller_rev_refund +
        invoice_amounts.aws_rev_refund +
        invoice_amounts.seller_rev_credit +
        invoice_amounts.aws_rev_credit +
        invoice_amounts.seller_tax_share +
        invoice_amounts.seller_tax_refund
    ) as seller_net_revenue,
    -- Try to get the billing address from the DISBURSED event 
    -- (if any). If there is no DISBURSEMENT, get the billing 
    -- address from the INVOICED item. If still no billing address, 
    -- then default to getting the mailing address of the payer.
    coalesce(billing_add.billing_address_id, 
             invoice_amounts.billing_address_id, 
             payer_info.mailing_address_id) 
          as final_billing_address_id
  from
    invoiced_and_forgiven_transactions invoice_amounts
    join products_with_latest_revision products 
        on products.product_id = invoice_amounts.product_id
    left join accounts_with_history payer_info 
        on payer_info.account_id = invoice_amounts.payer_account_id
          -- Get the Payer Information at the time of invoice creation
          and payer_info.begin_date <= invoice_amounts.invoice_date 
          and invoice_amounts.invoice_date < payer_info.end_date
    left join accounts_with_history customer_info 
        on customer_info.account_id = invoice_amounts.customer_account_id
          -- Get the End User Information at the time of invoice creation
          and customer_info.begin_date <= invoice_amounts.invoice_date 
          and invoice_amounts.invoice_date < customer_info.end_date
    left join billing_addresses_for_disbursed_invoices billing_add 
        on billing_add.transaction_reference_id = 
           invoice_amounts.transaction_reference_id
        and billing_add.from_account_id = 
            invoice_amounts.payer_account_id
),

invoices_with_full_address as (
  select
    payer_aws_account_id as "Customer AWS Account Number",
    pii_data.country as "Country",
    pii_data.state_or_region as "State",
    pii_data.city as "City",
    pii_data.postal_code as "Zip Code",
    pii_data.email_domain as "Email Domain",
    product_code as "Product Code",
    title as "Product Title",
    seller_rev_share as "Gross Revenue",
    aws_rev_share as "AWS Revenue Share",
    seller_rev_refund as "Gross Refunds",
    aws_rev_refund as "AWS Refunds Share",
    seller_net_revenue as "Net Revenue",
    currency as "Currency",
    date_format(invoice_date, '%Y-%m')as "AR Period",
    transaction_reference_id as "Transaction Reference ID",
    payer_reference_id as "Payer Reference ID",
    end_user_aws_account_id as "End Customer AWS Account ID"
  from
    invoiced_items_with_product_and_billing_address invoice_amounts
    left join pii_with_latest_revision pii_data 
        on pii_data.aws_account_id = invoice_amounts.payer_aws_account_id
        and pii_data.address_id = invoice_amounts.final_billing_address_id
    -- Filter out FORGIVEN and Field Demonstration Pricing transactions
    where seller_net_revenue <> 0
)

select * from invoices_with_full_address;
```

# Datenfeeds
<a name="data-feeds"></a>

AWS Marketplace bietet eine Reihe von Datenfeeds, mit denen Verkäufer Informationen über Ihre Produktverkäufe sammeln und analysieren können. Datenfeeds stehen allen registrierten AWS Marketplace Verkäufern zur Verfügung. Da Datenfeeds innerhalb eines Tages generiert werden, enthalten sie die neuesten verfügbaren Daten.

In den folgenden Abschnitten werden die einzelnen Datenfeeds beschrieben.

**Topics**
+ [

# Kontodatenfeed
](data-feed-account.md)
+ [

# Adressdatenfeed
](data-feed-address.md)
+ [

# Datenfeed für Vereinbarungen
](data-feed-agreements.md)
+ [

# Datenfeed zur Vereinbarung und Gebühr
](data-feed-agreement-charge.md)
+ [

# Datenfeed zur Laufzeit der Vereinbarung
](data-feed-agreement-term.md)
+ [

# Datenfeed zu Abrechnungsereignissen
](data-feed-billing-event.md)
+ [

# Täglicher Nutzungsdaten-Feed
](data-feed-daily-usage.md)
+ [

# Datenfeed zu Legacy-Zuweisungen
](data-feed-legacy-mapping.md)
+ [

# Angebotsdatenfeed
](data-feed-offer.md)
+ [

# Datenfeed zu Angebotsprodukten
](data-feed-offer-product.md)
+ [

# Datenfeed zum Angebotsziel
](data-feed-offer-target.md)
+ [

# Produktdatenfeed
](data-feed-product.md)
+ [

# Daten-Feed für Steuerartikel
](data-feed-tax-item.md)

# Kontodatenfeed
<a name="data-feed-account"></a>

Dieser Datenfeed enthält Informationen zu allen Konten, mit denen Sie interagieren: Ihre eigenen, alle Channel-Partner, mit denen Sie zusammenarbeiten, Käufer, Zahler und alle besteuerten Konten. 

Kontodaten sind unveränderlich und nicht mit einer Versionsnummer verknüpft. Änderungen an Feldern werden angehängt, sodass dieser Datenfeed mehrere Zeilen mit derselben `account_id` und unterschiedlichen Werten für `valid_from` aufweisen kann. Weitere Informationen zu Feldern zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization).

Der Kontodatenfeed wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten. 


| Spaltenname  | Beschreibung  | 
| --- | --- | 
| account\$1id  | Die weltweit eindeutige Kennung (GUID) des Kontos. Kann verwendet werden, um Felder in den `Tax_Item` Datenfeeds `Product``Offer_Target`,`Billing_Event`, und zu verknüpfen. In diesen Datenfeeds finden Sie Informationen zu den Feldern, die für die Verknüpfung verwendet werden können. | 
| aws\$1account\$1id  | Die AWS Kontonummer des AWS Verkäuferkontos, die je nach AWS Partition eindeutig ist.  | 
| encrypted\$1account\$1id | Die eindeutige, verschlüsselte ID für einen einzelnen Käufer Ihrer Anwendung. Der Wert für encrypted\$1account\$1id wird beispielsweise vom AWS Marketplace Messdienst als Wert für CustomerIdentifier diesen Wert verwendet, der von der [https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html](https://docs.aws.amazon.com/marketplacemetering/latest/APIReference/API_ResolveCustomer.html)Aktion zurückgegeben wird.  | 
| mailing\$1address\$1id | Die Postanschriftreferenz für dieses Konto. | 
| tax\$1address\$1id | Die Steueradressenreferenz für dieses Konto. | 
| tax\$1registration\$1number | Bei Nicht-US-Konten die Steuernummer für dieses Konto.  | 
| tax\$1legal\$1name | Bei Nicht-US-Konten der offizielle Unternehmensname. Dies ist der Name, der auf Steuerrechnungen verwendet wird. | 

## Beispiel für Kontodatenfeeds
<a name="data-feed-account-sample-data"></a>

Das folgende Beispiel zeigt einen Kontodatenfeed. Zur besseren Lesbarkeit werden die Spalten zum Datenverlauf nicht angezeigt. Weitere Informationen zu Feldern zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization).


| account\$1id  | aws\$1account\$1id  | encrypted\$1account\$1id | mailing\$1address\$1id | tax\$1address\$1id | tax\$1registration\$1number | tax\$1legal\$1name | 
| --- | --- | --- | --- | --- | --- | --- | 
| xk0 CSmiAm6PQ4QqEog9iiaochIzuPlkMfba7a1oDlZ | 444456660000 | Zf 7 oMzhe GWpH | 25O3K46EN6 FIIQTXWX8E3 3 eViOf kaOiPal UiofjyFa |  |  |  | 
| 7nyo5 PLYx81VX9JI04 jwTRo O1Ff8 88W8 eEwTur biQi | 555567679999 | 373 vuQUqm q8 V | 5oJ6 mRF2GVH2VJ9HFQiM800M vTjSz uLEHmy FY5Lr42s8 | 5 oJ6 vTjSz mRf2GVH2VJ9 hfqim800M uLEHmy FY5Lr42s8 | SE823935083345 |  | 
| VIeGa2t9j3MuxioH9wc8lsndXXCgGCGUreeXriocM5 | 73739998888 | 8 SPxAYmi8MwX | NLUc5UeiMlGFTrDWCoftDPhDUF1oaSd8xgl5QM8Db7 | V5N Yogwy 0 hBYBi WMhndGU4AfMggmuoTC2j7Pm8ZKKNNyT | DE469558025 |  | 

# Adressdatenfeed
<a name="data-feed-address"></a>

**Wichtig**  
AWS Marketplace wird den PiiFeed, der über den [Dienst für Lieferdatenfeeds für Verkäufer](https://docs.aws.amazon.com/marketplace/latest/userguide/data-feed-service.html) geliefert wird, im Dezember 2023 einstellen. Verwenden Sie den AddressFeed \$1V1-Datenfeed für Ihre Adressdatenanforderungen. Wenn Sie Fragen haben oder Unterstützung benötigen, wenden Sie sich an das [AWS Marketplace Seller Operations](https://aws.amazon.com/marketplace/management/contact-us/) Team.

Dieser Datenfeed enthält Kontaktinformationen für alle Konten, mit denen Sie interagieren: Ihre eigenen, alle Channel-Partner, mit denen Sie zusammenarbeiten, Käufer, Zahler und alle besteuerten Konten. Bei jeder neuen Transaktion wird die Kundenadresse für die Transaktion gescannt, und wenn sie nicht in Ihrem Daten-Feed vorhanden ist, wird der Datei Ihres Daten-Feeds ein neuer Eintrag hinzugefügt.

Adressdaten sind unveränderlich. 

Der Adressdatenfeed wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten. 


| Spaltenname  | Beschreibung  | 
| --- | --- | 
| address\$1id  | Die eindeutige Schlüssel der Adresse. Kann verwendet werden, um über den `Billing_Event` Datenfeed `billing_address_id` im Feld oder über den `Account` Datenfeed in den `tax_address_id` Feldern `mailing_address_id` oder eine Verbindung herzustellen. | 
| email\$1domain  | Die Domäne für die gespeicherte E-Mail-Adresse für dieses Konto.  | 
| company\$1name  | Der Firmenname für dieses Konto.  | 
| country\$1code | Der ISO 3166 Alpha-2-Ländercode für diese Adresse.  | 
| state\$1or\$1region  | Der Bundesstaat oder die Region für diese Adresse.  | 
| city  | Die Stadt für diese Adresse.  | 
| postal\$1code  | Die Postleitzahl für diese Adresse.  | 
| address\$1line\$11  | Die erste Zeile für diese Adresse.  | 
| address\$1line\$12  | Die zweite Zeile für diese Adresse.  | 
| address\$1line\$13  | Die dritte Zeile für diese Adresse.  | 

## Beispiel für Adressdatenfeeds
<a name="data-feed-address-sample-data"></a>

Das folgende Beispiel zeigt einen Adressdatenfeed. Im Datenfeed werden diese Informationen in einer einzigen Tabelle dargestellt. Zur besseren Lesbarkeit werden die Daten hier in zwei Tabellen angezeigt und die Spalten zum Datenverlauf werden nicht angezeigt. Weitere Informationen zu Feldern zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization). 


| address\$1id  | email\$1domain  | company\$1name  | Landesvorwahl  | state\$1or\$1region  | city  | postal\$1code  | 
| --- | --- | --- | --- | --- | --- | --- | 
| v5NH von 0wmHNDGU4 TC2J7PM8ZKKNNYT BiYogwy AfMggmuo | a.com | Unternehmen von Mateo Jackson | DE |  | Hamburg | 67568 | 
| g68xdbkzqdvvhzfbgw6yf5yos0a6nisvwhmh5 ViLjf | b.com | Unternehmen von Mary Major | US | OH | Dayton | 57684 | 
| NLuc5 GfTRDWCOFTDPHDUF1OASD8XGL5QM8DB7 UeiMl | c.com | Unser Verkäufer | US | NY | New York | 89475 | 




| address\$1line\$11  | address\$1line\$12  | address\$1line\$13  | 
| --- | --- | --- | 
|   |   |  | 
|  |   |  | 
|  | 19th Floor |  | 



# Datenfeed für Vereinbarungen
<a name="data-feed-agreements"></a>

Dieser Datenfeed enthält Informationen zu Vereinbarungen, bei denen es sich um einen Vertrag handelt, der zwischen einem Anbieter (registrierter Verkäufer) und einem akzeptierenden Unternehmen (AWS Käufer) unterzeichnet wurde, um mit der Nutzung eines Produkts zu beginnen. Dieser Datenfeed enthält Informationen zu den Vereinbarungen für die Produktangebote, die Sie als registrierter Verkäufer abgeschlossen haben.

Der Vertragsdatenfeed wird alle 24 Stunden aktualisiert.

In der folgenden Tabelle werden die Elemente im Datenfeed aufgeführt und beschrieben.


| Spalte | Description | 
| --- | --- | 
| valid\$1from | Das erste Datum, für das der Wert für den Primärschlüssel in Bezug auf Werte für andere Felder gültig ist. | 
| insert\$1date | Das Datum, an dem ein Datensatz in den Datenfeed eingefügt wurde. | 
| update\$1date | Das Datum, an dem der Datensatz zuletzt aktualisiert wurde. | 
| delete\$1date | Diese Spalte ist immer leer. | 
| Status |  Der aktuelle Status der Vereinbarung. Zu den unterstützten Status gehören: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-agreements.html)  | 
| geschätzter Wert der Vereinbarung | Der bekannte Gesamtbetrag, den der Kunde voraussichtlich während der gesamten Laufzeit des Vertrags zahlen wird. | 
| currency\$1code | Die Währung des bekannten Gesamtbetrags, in dem der Kunde voraussichtlich während der gesamten Laufzeit des Vertrags zahlen wird. | 
| agreement\$1id | Die eindeutige Kennung der Vereinbarung. | 
| license\$1ids | Die mit der Vereinbarung verknüpften Lizenzkennungen, dargestellt als Array. | 
| proposer\$1account\$1id | Der Verkäufer, der dies vorgeschlagen hat PurchaseAgreement, dargestellt durch die weltweit eindeutige Kennung (GUID) des Verkäuferkontos. Kann verwendet werden, um dem Kontodatenfeed beizutreten. | 
| acceptor\$1account\$1id | Der Käufer, der dies akzeptiert hat PurchaseAgreement, dargestellt durch die weltweit eindeutige Kennung (GUID) des Käuferkontos. Kann verwendet werden, um dem Kontodatenfeed beizutreten. | 
| offer\$1revision\$1at\$1acceptance | Die freundliche ID des Angebots, das dieser Vereinbarung entspricht. Kann verwendet werden, um dem Angebot und den Zieldaten-Feeds des Angebots beizutreten. | 
| offer\$1set\$1id | Die Kennung für das Angebotsset, das dem Angebot zugeordnet ist. | 
| start\$1time | Datum und Uhrzeit des Vertragsbeginns. | 
| end\$1time | Das Datum und die Uhrzeit, zu dem die Vereinbarung endet. Bei pay-as-you-go Vereinbarungen, die kein Enddatum haben, ist das Feld leer. | 
| acceptance\$1time | Datum und Uhrzeit der Annahme des Angebots oder der Erstellung der Vereinbarung. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-agreements.html)  | 
| intent | Die Absicht des Käufers bei der letzten Änderung der Vereinbarung. | 
| preceding\$1agreement\$1id | Die Vereinbarungs-ID der vorherigen Vereinbarung. | 
| status\$1reason\$1code | Der Grund für die Änderung des Vereinbarungsstatus. | 
| recipient\$1account\$1id | Das Konto des Verkäufers, der die Daten in den Feeds erhält. Kann verwendet werden, um eine Verbindung zum `Account` Datenfeed auf dem `account_id` Feld herzustellen. | 

## Beispiel für einen Datenfeed für Vereinbarungen
<a name="agreements-feed-example"></a>


| valid\$1from | agreement\$1id | Konto-ID des Antragstellers | Account\$1ID des akzeptierenden | offer\$1id | Überarbeitung\$1des Angebots bei Annahme | angebote\$1set\$1id | start\$1time | end\$1time | akzeptanz\$1zeit | intent | ID der vorhergehenden Vereinbarung | Status | Status\$1Ursachencode | geschätzter\$1Wert der Vereinbarung | Währungscode | 
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | 
| 2024-06-21 20:58:00.0 | agmt-34g544dfgsd5678adsrgwe5t | 88a3xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | 88a3xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | angebot-krxxxxxxxxxxx | 1 | Angebotsset-yricpu74oqox2 | 2024-06-21 20:58:00.0 | 2025-06-21 20:58:00.0 | 2024-06-21 20:58:00.0 | NEW |  | ACTIVE |  | 1.000 | USD | 

# Datenfeed zur Vereinbarung und Gebühr
<a name="data-feed-agreement-charge"></a>

Dieser Datenfeed bietet einen Überblick über die Gebühren, die mit einer Vereinbarung verbunden sind, die Sie als registrierter Verkäufer erstellt haben. Dieser Datenfeed enthält derzeit nur Gebühreninformationen für Verträge, die mit einer Laufzeit im Zahlungsplan verknüpft sind.

Der Datenfeed „Vertragsgebühr“ wird alle 24 Stunden aktualisiert.

In der folgenden Tabelle werden die Elemente im Datenfeed aufgeführt und beschrieben.


| Spalte | Description | 
| --- | --- | 
| valid\$1from | Das erste Datum, für das der Wert für den Primärschlüssel in Bezug auf Werte für andere Felder gültig ist. | 
| insert\$1date | Das Datum, an dem ein Datensatz in den Datenfeed eingefügt wurde. | 
| update\$1date | Das Datum, an dem der Datensatz zuletzt aktualisiert wurde. | 
| delete\$1date | Diese Spalte ist immer leer. | 
| Betrag | Der zu berechnende Betrag. | 
| Währungscode | Die Preiswährung der Zahlung. | 
| time | Das geplante Abbuchungsdatum für die geplante Rate. | 
| agreement\$1id | Die eindeutige Kennung der Vereinbarung. | 
| term\$1id | Die eindeutige Kennung des Begriffs. | 

## Beispiel für einen Datenfeed mit einer Vereinbarung, einer Gebühr
<a name="agreement-charge-feed-example"></a>


| valid\$1from | insert\$1date | update\$1date | delete\$1date | Betrag | currency\$1code | time | vereinbarungsnummer | Begriffs-ID | 
| --- | --- | --- | --- | --- | --- | --- | --- | --- | 
| 2024-12-24 11:31:47,0 | 2025-10-01 01:03:41,0 | 2025-10-01 01:03:41,0 | Null | 28440,00 | USD | 2025-11-06 00:00:00.000 000 | AGMT-3KK39TBW3J6ID2VAKBP0XXXXX | Begriff -3986e2c7f73768ed4ff7cd8a97b41ac0ae2aa02ada6b68deb9349c8604cxxxxx | 

# Datenfeed zur Laufzeit der Vereinbarung
<a name="data-feed-agreement-term"></a>

Dieser Datenfeed bietet einen Überblick über die Vertragsdauer, die mit einer Vereinbarung verknüpft ist, die Sie als registrierter Verkäufer erstellt haben.

Der Datenfeed zur Vertragslaufzeit wird alle 24 Stunden aktualisiert.

In der folgenden Tabelle werden die Elemente im Datenfeed aufgeführt und beschrieben.


| Spalte | Description | 
| --- | --- | 
| valid\$1from | Das erste Datum, für das der Wert für den Primärschlüssel in Bezug auf Werte für andere Felder gültig ist. | 
| insert\$1date | Das Datum, an dem ein Datensatz in den Datenfeed eingefügt wurde. | 
| update\$1date | Das Datum, an dem der Datensatz zuletzt aktualisiert wurde. | 
| delete\$1date | Das Datum, an dem der Datensatz gelöscht wurde. | 
| agreement\$1id | Die eindeutige Kennung der Vereinbarung. | 
| term\$1id | Die eindeutige Kennung des Begriffs. | 
| term\$1type | Die Art der Laufzeit, die mit der Vereinbarung verknüpft ist. Eine vollständige Liste der verfügbaren Bedingungen finden Sie unter https://docs.aws.amazon.com/marketplace/ latest/APIReference/API \$1Types\$1 AWS\$1M arketplace\$1Agreement\$1Service.html. | 
| term\$1configuration | Die zusätzlichen Parameter, die vom Akzeptor bei der Annahme des Begriffs angegeben wurden. Dies gilt für ConfigurableUpfrontPricingTerms und RenewalTerms. | 

## Beispiel für einen Datenfeed mit Vertragsdauer
<a name="agreement-term-feed-example"></a>


| valid\$1from | insert\$1date | update\$1date | delete\$1date | agreement\$1id | Begriffs-ID | Begriffstyp | Begriff\$1Konfiguration | 
| --- | --- | --- | --- | --- | --- | --- | --- | 
| 2024-12-24 11:31:47,0 | 2025-10-01 01:03:41,0 | 2025-10-01 01:03:41,0 | Null | AGMT-3KK39TBW3J6ID2VAKBP0XXXXX | Begriff -3986e2c7f73768ed4ff7cd8a97b41ac0ae2aa02ada6b68deb9349c8604cxxxxx | ConfigurableUpfrontPricingTerm | \$1"selectorValue“ :"P36M“, "dimensions“: [\$1"dimensionKey“ :"Anwendungen“, "dimensionValue“ :1\$1]\$1 | 

# Datenfeed zu Abrechnungsereignissen
<a name="data-feed-billing-event"></a>

Dieser Datenfeed enthält Informationen zu Abrechnungsereignissen, einschließlich Rechnungsstellung und Auszahlungen. 

Sie können diesen Datenfeed beispielsweise verwenden, um zu erfahren, wann und wofür einem Käufer eine Rechnung ausgestellt wird. Sie können auch die [SQL-Beispielabfragen](#data-feeds-billing-event-query-examples) verwenden, um die Daten aus diesem Datenfeed zu analysieren.

Dieser Datenfeed enthält Informationen, die mit Abrechnungsereignissen verknüpft sind, für die Sie der eingetragene Verkäufer sind. Bei Vereinbarungen, die über Vertriebspartner geschlossen wurden, enthält dieser Datenfeed Informationen über Abrechnungsereignisse zwischen dem Hersteller und dem Verkäufer.

Der Datenfeed zu Abrechnungsereignissen wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

Daten zu Abrechnungsereignissen sind unveränderlich. 

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten. 


| Name der Spalte  | Description  | 
| --- | --- | 
| billing\$1event\$1id | Eine Kennung für ein Abrechnungsereignis. Diese ID ist in der Verkäuferumgebung eindeutig.  | 
| from\$1account\$1id |  Das Konto, das das Abrechnungsereignis initiiert hat. Wenn unter `transaction_type` `SELLER_REV_SHARE` angegeben ist, handelt es sich um das Zahlerkonto des Käufers. Dies ist ein Fremdschlüssel für den [Kontodatenfeed](data-feed-account.md). Kann verwendet werden, um eine Verbindung zum `Account` Datenfeed auf dem `account_id` Feld herzustellen.  | 
| to\$1account\$1id | Das Konto, das den Transaktionsbetrag für das Produkt erhält. Dies ist ein Fremdschlüssel für den Kontodatenfeed.Kann verwendet werden, um eine Verbindung zum `Account` Datenfeed auf dem `account_id` Feld herzustellen. | 
| end\$1user\$1account\$1id | Das Konto, das das Produkt verwendet. Dieses Konto kann sich von den Käufer- und Zahlerkonten unterscheiden.Kann verwendet werden, um eine Verbindung zum `Account` Datenfeed auf dem `account_id` Feld herzustellen. | 
| product\$1id | Die Kennung des Produkts. Dies ist ein Fremdschlüssel für den [Produktdatenfeed](data-feed-product.md).Kann verwendet werden, um eine Verbindung zum `Product` Datenfeed auf dem `product_id` Feld herzustellen. | 
| action |  Der Typ der Aktion für dieses Ereignis. Die möglichen Werte lauten wie folgt: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html)  | 
| transaction\$1type |  Der Typ der Transaktion. Beispiele finden Sie unter [Besteuerungsszenarien](#data-feeds-billing-event-tax-examples). Die möglichen Werte lauten wie folgt:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html)  | 
| parent\$1billing\$1event\$1id |  Wenn der Wert von `broker_id` ist`AWS_INC`, der Wert von `DISBURSED` oder `action` ist und der Wert von `transaction_type` is`FORGIVEN`, `parent_billing_event_id` bezieht sich das auf das Original `DISBURSEMENT``billing_event_id`, das dieses Abrechnungsereignis ausgelöst hat. Wenn `action` einen anderen Wert aufweist, ist dieses Feld gleich null.  Wenn der Wert von `broker_id` ist`AWS_EUROPE`, `parent_billing_event_id` bezieht sich der auf das Original, das dieses Fakturierungsereignis ausgelöst hat`billing_event_id`, und zwar in den folgenden Szenarien:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html) Wenn der Wert von `broker_id` ist`AWS_EUROPE`, `parent_billing_event_id` bezieht sich der auf das Original `billing_event_id` des vorherigen erfolgreichen Abrechnungsereignisses für das folgende Szenario: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html) Wenn der Wert von `broker_id` ist`AWS_EUROPE`, ist dieses Feld für alle verbleibenden Szenarien Null.  | 
| disbursement\$1billing\$1event\$1id |  Die zugehörige Auszahlung, wenn der Wert von `action` ist `DISBURSED` und einer der folgenden Punkte zutrifft:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html) In allen anderen Szenarien ist dieser Wert Null.  | 
| Betrag | Der Betrag des Abrechnungsereignisses.  | 
| currency | Der Währungscode ISO 639. | 
| Auszahlungsbetrag | Der Auszahlungsbetrag. Bei dualer Rechnungsstellung enthält dieses Feld den Auszahlungsbetrag. Für Szenarien mit einheitlicher Rechnungsstellung ist dieses Feld leer. | 
| Disbursement\$1Currency | Der ISO-639-Währungscode für den Auszahlungsbetrag. Für Szenarien mit doppelter Rechnungsstellung enthält dieses Feld den Währungscode der Auszahlung. Für Szenarien mit einheitlicher Rechnungsstellung hat dieses Feld den Wert Null. | 
| balance\$1impacting | Gibt an, ob der Betrag bei der Berechnung der Auszahlungen des Verkäufers berücksichtigt wird. Der Wert 0 gibt an, dass der Betrag zu Informationszwecken angezeigt wird und keine Auswirkungen auf den Saldo hat. Der Wert 1 gibt an, dass dieser Betrag bei der Ermittlung der Auszahlungen des Verkäufers berücksichtigt wird.  | 
| invoice\$1date | Das Datum, an dem die Rechnung erstellt wurde. | 
| payment\$1due\$1date |  Wenn der Wert von `action` ist`INVOICED`, ist das Fälligkeitsdatum der Rechnung.  | 
| usage\$1period\$1start\$1date | Das Startdatum für den Zeitraum im Datensatz. | 
| usage\$1period\$1end\$1date | Das Enddatum für den Zeitraum im Datensatz. | 
| invoice\$1id |  Die AWS Rechnungs-ID.  | 
| billing\$1address\$1id | Die Rechnungsadresse des Zahlers im Adressdatenfeed.Kann verwendet werden, um eine Verbindung zum `Address` Datenfeed auf dem `address_id` Feld herzustellen. | 
| transaction\$1reference\$1id |  Eine Kennung, mit der Sie Querverweise zu Daten aus den folgenden Berichten erstellen können: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html)  | 
| bank\$1trace\$1id |  Bei Auszahlungstransaktionen (`transaction_type`=ist `DISBURSEMENT` und Aktion ist`DISBURSED`) die von der Bank zugewiesene Trace-ID. Die Trace-ID kann verwendet werden, um mit von der Bank bereitgestellten Berichten der Verkäuferbank zu korrelieren.  | 
| broker\$1id |  Eine Kennung der Geschäftseinheit, die die Transaktion ermöglicht hat. Die möglichen Werte lauten wie folgt: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html)  | 
| buyer\$1transaction\$1reference\$1id |  Ein Bezeichner, der alle zugehörigen Datensätze im Fakturierungs-Feed mithilfe oder mithilfe der in SQL erstellten Fensterfunktionen zusammenfasst`GROUP BY`. Diese zugehörigen Datensätze können die Käuferrechnung, die Verkäuferrechnung und die Mehrwertsteuer (VATs) auf die Angebotsgebühr enthalten.  | 
| action\$1date |  Das Datum, an dem das Transaktionsereignis eingetreten ist. Das genaue Datum hängt vom Aktionstyp ab: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-billing-event.html)  | 
| recipient\$1account\$1id | Das Konto des Verkäufers, der die Daten in den Feeds erhält. Kann verwendet werden, um eine Verbindung zum `Account` Datenfeed auf dem `account_id` Feld herzustellen. | 
| offer\$1id | Die benutzerfreundliche ID des Angebots, das dem Rechnungseinzelposten des Käufers zugeordnet ist.Kann verwendet werden, um eine Verbindung zum `Offer` Datenfeed auf dem `offer_id` Feld herzustellen. | 
| buyer\$1invoice\$1date | Das Rechnungsdatum der zugehörigen Käuferrechnungsposition. | 
| line\$1item\$1id | Die Einzelposten-ID der Rechnung mit der Granularität der Auszahlung. | 
| buyer\$1line\$1item\$1id | Die Einzelposten-ID des Käufers in der Detailansicht der Auszahlung. | 
| charge\$1variant | Zeigt an, was gekauft oder verkauft wird.  | 
| charge\$1side | Gibt an, ob der Verkäufer die Gebührenvariante kauft oder verkauft.  | 

## Besteuerungsszenarien
<a name="data-feeds-billing-event-tax-examples"></a>

Das Besteuerungsmodell für das Land und den Staat des Käufers und des Verkäufers bestimmt, wie Steuern erhoben und gezahlt werden. Die folgenden Szenarien sind möglich:
+ Steuern werden von AWS erhoben und überwiesen. In diesen Fällen lautet der Wert für `transaction_type` `AWS_TAX_SHARE`. 
+ Steuern werden vom Verkäufer erhoben AWS, an den Verkäufer ausgezahlt und vom Verkäufer an die Steuerbehörden überwiesen. In diesen Fällen lautet der Wert für `transaction_type` `SELLER_TAX_SHARE`.
+ Steuern werden nicht erhoben von. AWS Der Verkäufer muss die Steuern berechnen und an die Steuerbehörden zahlen. Führt in diesen Fällen AWS Marketplace keine Steuerberechnungen durch und erhält keine Steuerinformationen. Der Verkäufer zahlt die Steuern aus dem Umsatzanteil.

## Beispiele für Datenfeeds zu Abrechnungsereignissen
<a name="data-feed-billing-event-sample-scenario"></a>

Dieser Abschnitt zeigt Beispiele für den Datenzeitraum zum Abrechnungsereignis zum Zeitpunkt der Rechnungsstellung und einen Monat später. Beachten Sie folgende Informationen zu allen Tabellen in diesem Abschnitt: 
+ In Datenfeeds bestehen die Werte für `billing_event_id` aus 40-stelligen alphanumerischen Zeichenfolgen. Zur besseren Lesbarkeit werden sie hier als zweistellige Zeichenfolgen angezeigt. 
+ Im Datenfeed werden diese Informationen in einer einzigen Tabelle dargestellt. Zur Lesbarkeit werden die Daten hier in mehreren Tabellen angezeigt, und nicht alle Spalten werden angezeigt. 

Die Beispiele in diesem Abschnitt setzen Folgendes voraus: 
+ Arnav ist der Käufer.
  + Seine Konto-ID lautet `737399998888`.
  + Er ist in Frankreich ansässig und unterliegt damit den Gesetzen für Marktplatzvermittler. Weitere Informationen finden Sie in der [Amazon Web Services-Steuerhilfe](https://aws.amazon.com/tax-help/).
  + Er hat `prod-o4grxfafcxxxx` gekauft und ihm wurden 120,60 USD für die monatliche Nutzung dieses Produkts in Rechnung gestellt.
  + Er hat die Rechnung innerhalb des Monats bezahlt.
+ Jane ist die Herstellerin.
  + Ihre Konto-ID lautet `111122223333`.
+ Paulo ist der eingetragene Verkäufer.
  + Seine Konto-ID lautet `777788889999`. 
  + Er lebt in Kansas und unterliegt damit nicht den Gesetzen für Marktplatzvermittler. 

### Datenfeed zu Abrechnungsereignissen für eingetragene Verkäufer
<a name="billing-event-example-seller-of-record"></a>

Als eingetragener Verkäufer stellt Paulo dem Käufer, Arnav, eine Rechnung. 

Die folgenden Tabellen zeigen die relevanten Informationen im Daten-Feed von Paulo, wenn er Arnav eine Rechnung stellt.


| billing\$1event\$1id  | from\$1account\$1id  | to\$1account\$1id  | end\$1user\$1account\$1id | product\$1id | action | transaction\$1type | 
| --- | --- | --- | --- | --- | --- | --- | 
| I0 | 737399998888 | 777788889999 | 737399998888 | prod-o4grxfafcxxxx | INVOICED | SELLER\$1REV\$1SHARE | 
| I1 | 737399998888 | AWS | 737399998888 | prod-o4grxfafcxxxx | INVOICED | AWS\$1TAX\$1TEILEN | 
| I2 | 777788889999 | 111122223333 | 737399998888 | prod-o4grxfafcxxxx | INVOICED | SELLER\$1REV\$1SHARE | 
| I3 | 777788889999 | AWS | 737399998888 | prod-o4grxfafcxxxx | INVOICED | AWS\$1REV\$1TEILEN | 




| parent\$1billing\$1event\$1id | disbursement\$1billing\$1event\$1id | Betrag | currency | invoice\$1date | invoice\$1id | 
| --- | --- | --- | --- | --- | --- | 
|  |  | 100 | USD | 2018-12-31T00:00:00Z | 781216640 | 
|  |  | 20.6 | USD | 2018-12-31T00:00:00Z | 781216640 | 
|  |  | -80 | USD | 2018-12-31T00:04:07Z | 788576665 | 
|  |  | -0.2 | USD | 2018-12-31T00:04:07Z | 788576665 | 

Die folgenden Tabellen zeigen die relevanten Informationen im Daten-Feed von Paulo am Ende des Monats, nachdem Arnav die Rechnung bezahlt hat.


| billing\$1event\$1id  | from\$1account\$1id  | to\$1account\$1id  | end\$1user\$1account\$1id | product\$1id | action | transaction\$1type | 
| --- | --- | --- | --- | --- | --- | --- | 
| I10 | 737399998888 | 777788889999 | 737399998888 |  | DISBURSED | SELLER\$1REV\$1SHARE | 
| I12 | 777788889999 | 111122223333 | 737399998888 |  | DISBURSED | SELLER\$1REV\$1SHARE | 
| I13 | 777788889999 | AWS | 737399998888 | prod-o4grxfafcxxxx | DISBURSED | AWS\$1REV\$1TEILEN | 
| I14 | AWS | 777788889999 |  |  | DISBURSED | DISBURSEMENT | 




| parent\$1billing\$1event\$1id | disbursement\$1billing\$1event\$1id | Betrag | currency | invoice\$1date | invoice\$1id | 
| --- | --- | --- | --- | --- | --- | 
| I0 | I14 | -100 | USD | 2018-12-31T00:00:00Z | 781216640 | 
| I2 | I14 | 80 | USD | 2018-12-31T00:04:07Z | 788576665 | 
| I3 | I14 | 0.2 | USD | 2018-12-31T00:04:07Z | 788576665 | 
|  |  | 19.8 | USD |  |  | 

### Datenfeed zu Abrechnungsereignissen für Hersteller
<a name="billing-event-example-manufacturer"></a>

Die folgenden Tabellen zeigen die relevanten Informationen im Daten-Feed von Jane, wenn Paulo Arnav eine Rechnung stellt.


| billing\$1event\$1id  | from\$1account\$1id  | to\$1account\$1id  | end\$1user\$1account\$1id | product\$1id | action | transaction\$1type | 
| --- | --- | --- | --- | --- | --- | --- | 
| I5 | 777788889999 | 111122223333 |  | prod-o4grxfafcxxxx | INVOICED | SELLER\$1REV\$1SHARE | 
| I6 | 777788889999 | 111122223333 |  | prod-o4grxfafcxxxx | INVOICED | SELLER\$1TAX\$1SHARE | 
| I7 | 111122223333 | AWS |  | prod-o4grxfafcxxxx | INVOICED | AWS\$1REV\$1TEILEN | 




| parent\$1billing\$1event\$1id | disbursement\$1billing\$1event\$1id | Betrag | currency | invoice\$1date | invoice\$1id | 
| --- | --- | --- | --- | --- | --- | 
|  |  | 73.5 |  | 2018-12-31T00:04:07Z | 788576665 | 
|  |  | 6,5 |  | 2018-12-31T00:04:07Z | 788576665 | 
|  |  | -7.35 |  | 2018-12-31T00:04:07Z | 788576665 | 

Die folgenden Tabellen zeigen die relevanten Informationen im Daten-Feed von Jane am Ende des Monats, nachdem die Rechnung bezahlt wurde.


| billing\$1event\$1id  | from\$1account\$1id  | to\$1account\$1id  | end\$1user\$1account\$1id | product\$1id | action | transaction\$1type | 
| --- | --- | --- | --- | --- | --- | --- | 
| I30 | 777788889999 | 111122223333 |  | prod-o4grxfafcxxxx | DISBURSED | SELLER\$1REV\$1SHARE | 
| I31 | 777788889999 | 111122223333 |  | prod-o4grxfafcxxxx | DISBURSED | SELLER\$1TAX\$1SHARE | 
| I32 | 111122223333 | AWS |  | prod-o4grxfafcxxxx | DISBURSED | AWS\$1REV\$1TEILEN | 
| I33 | AWS | 111122223333 |  |  | DISBURSED | DISBURSEMENT | 




| parent\$1billing\$1event\$1id | disbursement\$1billing\$1event\$1id | Betrag | currency | invoice\$1date | invoice\$1id | 
| --- | --- | --- | --- | --- | --- | 
| I5 | I33 | -73.5 | USD |  |  | 
| I6 | I33 | -6.5 | USD |  |  | 
| I7 | I33 | 7.35 | USD |  |  | 
|  |  | 72.65 | USD |  |  | 

## Beispielabfragen
<a name="data-feeds-billing-event-query-examples"></a>

Wie unter beschrieben[Sammeln und Analysieren von Daten mit Datenfeeds](data-feed-using.md), können Sie [Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) verwenden, um Abfragen zu den Daten durchzuführen, die als Datenfeeds in Ihrem verwalteten Amazon S3 S3-Bucket gesammelt und gespeichert wurden. Dieser Abschnitt enthält einige Beispiele für häufige Methoden dafür. In allen Beispielen wird davon ausgegangen, dass eine einheitliche Währung verwendet wird.

## Beispiel 1: Fakturierter Betrag, einschließlich Steuern
<a name="data-feed-example-query-tax-invoice"></a>

Um herauszufinden, wie viel Käufern in Rechnung gestellt wurde, einschließlich Steuern, können Sie eine Abfrage ausführen, wie im folgenden Beispiel gezeigt. 

```
SELECT sum(amount) FROM billing_event 
WHERE 
  action = 'INVOICED'
  AND
  (
    (transaction_type in ('SELLER_REV_SHARE', 'SELLER_TAX_SHARE')
      -- to discard SELLER_REV_SHARE from Manufacturer to Channel Partner, aka cost of goods
      AND to_account_id='seller-account-id'
    )
  OR transaction_type= 'AWS_TAX_SHARE'
  );
```

## Beispiel 2: Betrag, der Käufern im Namen eines Verkäufers in Rechnung gestellt wurde
<a name="data-feed-example-query-invoice-for-seller"></a>

Um herauszufinden, wie viel Käufern im Namen eines Verkäufers in Rechnung gestellt wurde, können Sie eine Abfrage ausführen, wie im folgenden Beispiel gezeigt.

```
SELECT sum(amount) FROM billing_event 
WHERE
  action = 'INVOICED'
  AND transaction_type in ('SELLER_REV_SHARE', 'SELLER_TAX_SHARE')
  AND to_account_id='seller-account-id'
;
```

## Beispiel 3: Der Betrag AWS kann im Namen des Verkäufers eingezogen werden
<a name="data-feed-example-query-aws-collect"></a>

Um herauszufinden, wie viel Geld im Namen eines Verkäufers einziehen AWS kann, abzüglich aller Rückerstattungen, Gutschriften und vergebenen Konten, können Sie eine Abfrage ausführen, wie im folgenden Beispiel gezeigt.

```
SELECT sum(amount) FROM billing_event 
WHERE
  -- what is invoiced on behalf of SELLER, incl. refunds/ credits and cost of goods
  transaction_type like 'SELLER_%' 
  -- FORGIVEN action records will "negate" related INVOICED
  and action in ('INVOICED','FORGIVEN') 
;
```

## Beispiel 4: Betrag, den der Verkäufer einfordern kann
<a name="data-feed-example-query-seller-collect"></a>

Um herauszufinden, wie viel Verkäufer einziehen können, können Sie eine Abfrage ausführen, wie im folgenden Beispiel gezeigt. In diesem Beispiel werden die anfallenden Angebotsgebühren und Steuern entfernt und alle außergewöhnlichen Saldoanpassungen hinzugefügt. AWS 

```
SELECT sum(amount) FROM billing_event
WHERE
  (transaction_type like 'SELLER_%' -- what is invoiced on behalf of SELLER
  or transaction_type like 'AWS_REV_%' -- what is owed to AWS
  or transaction_type = 'BALANCE_ADJUSTMENT' -- exceptionnal case
  )
  and action in ('INVOICED','FORGIVEN')
;
```

Sie können auch die folgende Abfrage verwenden, um dieselben Informationen zu sammeln, wie im folgenden Beispiel gezeigt.

```
SELECT sum(amount) FROM billing_event
WHERE
  balance_impacting = 1
  and action in ('INVOICED','FORGIVEN')
;
```

Das folgende Beispiel zeigt dieselben Informationen, ist jedoch auf Transaktionen von 2018 beschränkt und geht davon aus, dass alle Käufer ihre Rechnungen bezahlt haben. 

```
SELECT sum(amount) FROM billing_event
WHERE
  invoice_date between '2018-01-01' and '2018-12-31'
  and balance_impacting = 1
  and action in ('INVOICED','FORGIVEN')
;
```

## Beispiel 5: Betrag der Auszahlungen
<a name="data-feed-example-query-disbursements"></a>

Um den ausgezahlten Betrag herauszufinden, können Sie eine Abfrage ausführen, wie im folgenden Beispiel gezeigt.

```
select sum(amount) FROM billing_event
WHERE
  action ='DISBURSED'
  and transaction_type like 'DISBURSEMENT%'
;
```

## Beispiel 6: Betrag der noch ausstehenden Auszahlungen
<a name="data-feed-example-query-pending-disbursement"></a>

Um den Betrag zu ermitteln, dessen Auszahlung noch aussteht, können Sie eine Abfrage ausführen, wie im folgenden Beispiel gezeigt. Diese Abfrage entfernt Beträge, die bereits ausgezahlt wurden. 

```
SELECT sum(amount) FROM billing_event targeted 
WHERE
   (transaction_type like 'SELLER_%'  -- what is invoiced on behalf of SELLER
    or transaction_type like 'AWS_REV_%'  -- what is owed to AWS
    or transaction_type = 'BALANCE_ADJUSTMENT' -- exceptionnal case
   ) 
  -- DISBURSEMENT action records will "negate" 'INVOICED'
  -- but do not take into account failed disbursements
   AND 
    (not exists
      (select 1 
        from billing_event disbursement
          join billing_event failed_disbursement
           on disbursement.billing_event_id=failed_disbursement.parent_billing_event_id
        where
         disbursement.transaction_type='DISBURSEMENT'
         and failed_disbursement.transaction_type='DISBURSEMENT_FAILURE'
         and targeted.disbursement_billing_event_id=disbursement.billing_event_id
      )
    ) 
;
```

Eine andere Möglichkeit, dieselben Informationen zu erhalten, besteht darin, eine Abfrage auszuführen, um den Saldo des Verkäufers abzurufen, wie im folgenden Beispiel gezeigt.

```
SELECT sum(amount) FROM billing_event
WHERE
 balance_impacting = 1
;
```

Die folgende Abfrage erweitert unser Beispiel. Es beschränkt die Ergebnisse auf Transaktionen von 2018 und gibt zusätzliche Details zu den Transaktionen zurück.

```
select sum(residual_amount_per_transaction)
from
 (SELECT
    max(billed_invoices.amount) invoiced_amount,
    sum(nvl(disbursed_invoices.amount,0)) disbursed_amount,
    -- Exercise left to the reader:
    -- use transaction_type to distinguish listing fee vs seller-owed money
    -- still pending collection
    max(transaction_type) transaction_type,
    max(billed_invoices.amount) 
      + sum(nvl(disbursed_invoices.amount,0)) residual_amount_per_transaction
  FROM billing_event billed_invoices
    -- find related disbursements
    left join billing_event disbursed_invoices
      on disbursed_invoices.action='DISBURSED'
      and disbursed_invoices.parent_billing_event_id=billed_invoices.billing_event_id
  WHERE
    billed_invoices.invoice_date between '2018-01-01' and '2018-12-31'
    and billed_invoices.transaction_type like 'SELLER_%' -- invoiced on behalf of SELLER
    and billed_invoices.action in ('INVOICED','FORGIVEN')
    -- do not take into account failed disbursements
    AND not exists
      (select 1 from billing_event failed_disbursement
       where disbursed_invoices.disbursement_billing_event_id = failed_disbursement.parent_billing_event_id
      )
   GROUP BY billed_invoices.billing_event_id
);
```

## Beispiel 7: Saldo einer Gruppe von Rechnungen
<a name="data-feed-example-query-balance-invoice-set"></a>

Um die Summe einer Reihe von Rechnungen zu ermitteln, können Sie eine Abfrage ausführen, wie im folgenden Beispiel gezeigt.

```
SELECT invoice_id, sum(amount) FROM billing_event targeted
WHERE
  -- invoice_id is only not null for invoiced records AND disbursed records 
  -- linking them to related disbursement -> no need to filter more precisely
  invoice_id in ('XXX','YYY') 
  -- filter out failed disbursements 
  AND not exists
      (select 1 
        from billing_event disbursement
          join billing_event failed_disbursement
           on disbursement.billing_event_id=failed_disbursement.parent_billing_event_id
        where
         disbursement.transaction_type='DISBURSEMENT'
         and failed_disbursement.transaction_type='DISBURSEMENT_FAILURE'
         and targeted.disbursement_billing_event_id=disbursement.billing_event_id
      ) 
  group by invoice_id;
```

# Täglicher Nutzungsdaten-Feed
<a name="data-feed-daily-usage"></a>

Dieser Datenfeed enthält detaillierte Informationen zur täglichen Nutzung Ihrer Produkte, einschließlich Messdaten zur Kundennutzung, geschätzter Umsätze und Preisinformationen. Mithilfe der Daten können Sie nachverfolgen, wie Kunden Ihre Produkte verwenden, und anhand der Nutzungsmuster den geschätzten Umsatz berechnen.

Der Datenfeed zur täglichen Nutzung wird alle 24 Stunden aktualisiert.

In der folgenden Tabelle werden die Elemente im Datenfeed aufgeführt und beschrieben.


| Spalte | Description | 
| --- | --- | 
| valid\$1from | Das erste Datum, für das der Wert für den Primärschlüssel in Bezug auf Werte für andere Felder gültig ist. | 
| insert\$1date | Das Datum, an dem ein Datensatz in den Datenfeed eingefügt wurde. | 
| update\$1date | Das Datum, an dem der Datensatz zuletzt aktualisiert wurde. | 
| delete\$1date | Das Datum, an dem der Datensatz vorläufig gelöscht wurde. | 
| usage\$1feed\$1id | Die eindeutige Kennung des Nutzungsdatensatzes. Dabei handelt es sich um einen Salted Hash pro Verkäufer, der den Datenschutz gewährleistet und gleichzeitig die Einzigartigkeit der Datensätze gewährleistet. | 
| Verwendungsdatum | Das Nutzungsdatum des Kunden ohne die Zeitkomponente. Die Uhrzeit wird weggelassen, da die Nutzung für jeden Tag aggregiert wird. | 
| product\$1id | Die benutzerfreundliche ID des Produkts. Kann zur Verknüpfung mit den `product_id` Feldern der Datenfeeds Account, Billing\$1Event und Offer\$1Product verwendet werden. | 
| agreement\$1id | Die eindeutige Kennung der Vereinbarung. Falls vorhanden, beginnt dies immer mit`agmnt-`. Dieses Feld kann gelegentlich leer sein oder nicht den entsprechenden Rechnungspositionen entsprechen. | 
| end\$1user\$1account\$1id | Das Konto, das das Produkt tatsächlich verwendet hat, dargestellt durch die GUID (Globally Unique Identifier) des Endbenutzerkontos. Kann verwendet werden, um dem Kontodatenfeed beizutreten. Dies ist ein Salted Hash pro Verkäufer, nicht die unformatierte AWS-Konto-ID. | 
| payer\$1account\$1id | Das Konto, von dem erwartet wird, dass es für die Nutzung des Produkts bezahlt, dargestellt durch die GUID (Global Unique Identifier) des Kontos des Zahlers. Kann verwendet werden, um dem Kontodatenfeed beizutreten. Dies ist ein Salted Hash pro Verkäufer, nicht die unformatierte AWS-Konto-ID. | 
| Region | Die AWS Region, in der die Nutzung durch den Käufer erfolgte. | 
| dimension\$1key | Der vom Verkäufer bei der Veröffentlichung des Angebots konfigurierte Dimensionsschlüssel. | 
| usage\$1unit | Eine Klassifizierung der Nutzungseinheiten, die die Art der Nutzungsmessung beschreibt. | 
| Nutzungsmenge | Der Nutzungswert für den AWS Dienst oder die Nutzungsart, der dem Abrechnungsdatensatz zugeordnet ist. Der Wert wird mit bis zu 2 Dezimalstellen angegeben. | 
| Preiswährung | Die Währung des geschätzten Umsatzes. | 
| geschätzter Umsatz in Preiswährung | Der geschätzte Umsatz, berechnet mit dem und. `usage_rate_per_unit` `usage_quantity` Der Wert wird mit bis zu 2 Dezimalstellen angegeben. Für ISV-Nutzungsdaten aus Angeboten von Wiederverkäufern muss dieser Wert mit dem Prozentsatz der Umsatzbeteiligung multipliziert werden. | 
| recipient\$1account\$1id | Das Konto des Verkäufers, der die Daten in den Feeds erhält. | 
| offer\$1id | Die freundliche ID des Angebots. Diese entspricht der Offer\$1ID des Kaufvertrags, sofern verfügbar. Kann verwendet werden, um den Zieldaten-Feeds „Angebot“ und „Angebot“ beizutreten. Aus Konsistenzgründen ist dieses Feld immer ungleich Null. | 
| usage\$1rate\$1per\$1unit\$1in\$1pricing\$1currency | Die Nutzungsrate pro Einheit, die mit dem multipliziert werden kann, um die zu überprüfen. `usage_quantity` `estimated_revenue_in_pricing_currency` Der Wert wird mit bis zu 6 Dezimalstellen angegeben. | 
| charge\$1item\$1description | Die vollständige Artikelbeschreibung, normalerweise im Format offer\$1term\$1description\$1region\$1dimension\$1description für nutzungsabhängige Gebühren. | 

## Beispiel für einen Feed mit Daten zur täglichen Nutzung
<a name="daily-usage-feed-example"></a>

Im Folgenden finden Sie ein Beispiel für den Datenfeed zur täglichen Nutzung mit wichtigen Spalten. Aus Gründen der besseren Lesbarkeit werden einige Spalten nicht angezeigt.


| Verwendungsdatum | product\$1id | vereinbarungsnummer | Region | dimension\$1key | Verwendungseinheit | Nutzungsmenge | Preiswährung | geschätzter Umsatz in Preiswährung | offer\$1id | Nutzungsrate pro Einheit in Preiswährung | Artikelbeschreibung in Rechnung stellen | 
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | 
| 15.01.2025 | prod-abcd1234efgh5678 | agmnt-wxyz9876abcd5432 | us-east-1 | USE1\$1InputTokenCount | Einheiten | 24,00 | USD | 12,00 | angebot-mnop5432qrst7890 | 0,500000 | Nutzung der AWS Marketplace Marketplace-Softwarenutzung\$1US-East-1\$1Millionen Eingabe-Token | 
| 2025-01-15 | prod-ijkl9876mnop1234 | agmnt-stuv5432wxyz9876 | us-west-2 | USE1\$1InputTokenCount | Einheiten | 1000,00 | USD | 5,50 | angebot-abcd9876efgh5432 | 0,005500 | Nutzung der AWS Marketplace Marketplace-Softwarenutzung\$1US-West-2\$1API-Aufrufe | 

# Datenfeed zu Legacy-Zuweisungen
<a name="data-feed-legacy-mapping"></a>

In diesem Datenfeed wird aufgeführt, wie Produkt IDs und IDs Angebot älteren global eindeutigen Identifikatoren (GUIDs) zugeordnet werden. Die alten GUIDs wurden in älteren Berichten verwendet, und die neuen IDs werden in Datenfeeds und in AWS Marketplace APIs verwendet.

Dieser Datenfeed enthält Informationen zu allen Produkten, die Sie als eingetragener Verkäufer erstellt haben, und zu allen Produkten, zu deren Weiterverkauf Sie autorisiert sind.

Der Datenfeed zu Legacy-Zuweisungen wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten. 


| Name der Spalte  | Description  | 
| --- | --- | 
| mapping\$1type | Gibt an, ob es sich um eine Produkt-ID oder eine Angebots-ID handelt.  | 
| legacy\$1id | Die Legacy-ID für dieses Produkt oder Angebot. | 
| new\$1id | Die Anzeige-ID für dieses Produkt oder Angebot. Diese ID wird als Primärschlüssel und mit allen aktuellen API-Aktionen verwendet.  | 

## Beispiel für Datenfeeds zu Legacy-Zuweisungen
<a name="data-feed-legacy-mapping-sample-data"></a>

Das folgende Beispiel zeigt einen Datenfeed zu Legacy-Zuweisungen. Zur besseren Lesbarkeit werden die Spalten zum Datenverlauf nicht angezeigt. Weitere Informationen zu Feldern zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization).


| mapping\$1type | legacy\$1id  | new\$1id | 
| --- | --- | --- | 
| ANGEBOT | 8a806c74-dbd6-403e-9362-bb08f417ff37 | offer-dacpxznflfwin | 
| PRODUKT | 1368541d-890b-4b6c-9bb9-4a55306ab642 | prod-o4grxfafcxxxy | 
| ANGEBOT | 558d8382-6b3a-4c75-8345-a627b552f5f1 | offer-gszhmle5npzip | 



# Angebotsdatenfeed
<a name="data-feed-offer"></a>

Der Angebotsdatenfeed enthält Informationen zu allen Angeboten, die Sie als registrierter Verkäufer erstellt haben. Wenn ein einzelnes Angebot mehrere Überarbeitungen aufweist, sind alle Änderungen im Datenfeed enthalten.

Wenn Sie ein Angebot überarbeiten und sich die Daten in einem offenen Feld ändern, wird im Datenfeed ein neuer Datensatz für denselben Primärschlüssel (`offer_id`Plus`offer_revision`) erstellt. Das `valid_from` Feld hat jedoch einen anderen Wert. Weitere Informationen zu den Datenfeed-Verlaufsspalten finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization).

Der Angebotsdatenfeed wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

Die folgende Tabelle enthält die Namen und Beschreibungen der Spalten des Datenfeeds. 


| Name der Spalte  | Description  | 
| --- | --- | 
| offer\$1id | Der Anzeigename für das Angebot.Kann verwendet werden, um eine Verbindung zum `offer_id` Feld des `Offer_Product` Datenfeeds herzustellen. | 
| offer\$1revision | Die Überarbeitung des Angebots. Dieses Feld und das Feld offer\$1id bilden zusammen den Primärschlüssel.Mit`offer_id`, kann verwendet werden, um eine Verbindung zu den `offer_revision` Feldern `offer_id` und des `Target_Offer` Datenfeeds herzustellen. | 
| name | Der vom Verkäufer definierte Name des Angebots.  | 
| expiration\$1date | Das Datum und die Uhrzeit, wann das Angebot abläuft. | 
| opportunity\$1name | Alle mit diesem Angebot verknüpften Daten zu Verkaufschancen. Wenn das Angebot an eine Verkaufschance in AWS gebunden ist, wird dieses Feld ausgefüllt. | 
| opportunity\$1description | Alle mit diesem Angebot verknüpften beschreibenden Informationen. Wenn das Angebot an eine Verkaufschance in AWS gebunden ist, wird dieses Feld ausgefüllt. | 
| seller\$1account\$1id | Die weltweit eindeutige Kennung (GUID) des Verkäuferkontos. Kann verwendet werden, um eine Verbindung mit dem account\$1id Feld im Kontodatenfeed herzustellen. | 
| opportunity\$1id | Eine ID für die Verkaufschance wird nur eingegeben, wenn ein Wiederverkäufer Ihr Produkt verkauft. Alle Angebote, die von verschiedenen Vertriebspartnern (oder Verkäufern) erstellt wurden, haben dasselbe, opportunity\$1id sofern es sich um dasselbe Produkt handelt.  | 
| recipient\$1account\$1id | Das Konto des Verkäufers, der die Daten in den Feeds erhält. Kann verwendet werden, um dem `Account` Datenfeed auf dem `account_id` Feld beizutreten. | 

## Beispiel für Angebotsdatenfeeds
<a name="data-feed-offer-sample-data"></a>

Das folgende Beispiel zeigt einen Angebotsdatenfeed. Zur besseren Lesbarkeit werden die Spalten zum Datenverlauf nicht angezeigt. Weitere Informationen zu Feldern zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization).


| offer\$1id  | offer\$1revision | Name | expiration\$1date | opportunity\$1name | opportunity\$1description | seller\$1account\$1id | Opportunity-ID | 
| --- | --- | --- | --- | --- | --- | --- | --- | 
| offer-dacpxznflfwin | 1 | Angebot zum Enterprise-Vertragsprogramm | 9999-01-01T00:00:00Z |  |  |  |  | 
| offer-gszhmle5npzip | 1 | Vom Verkäufer erstelltes privates Angebot | 2020-10-31T00:00:00Z |  |  |  |  | 
| offer-hmzhyle8nphlp | 1 | Angebot zum Enterprise-Vertragsprogramm | 9999-01-01T00:00:00Z |  |  |  |  | 

# Datenfeed zu Angebotsprodukten
<a name="data-feed-offer-product"></a>

Ein Angebot kann mehrere Produkte enthalten und ein Produkt kann in verschiedenen Angeboten enthalten sein. Dieser Datenfeed listet Informationen zu den Beziehungen zwischen Angeboten und Produkten auf. 

Dieser Datenfeed enthält Informationen zu allen Produktangeboten, die Sie als eingetragener Verkäufer erstellt haben.

Wenn Sie ein Produkt einem Angebot hinzufügen oder daraus entfernen, erstellen Sie eine Angebotsüberarbeitung. 

Der Datenfeed zu Angebotsprodukten wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten. Informationen zu den Datenfeed-Verlaufsspalten finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization).


| Spaltenname  | Beschreibung  | 
| --- | --- | 
| offer\$1id | Der Anzeigename dieses Angebots.Kann verwendet werden, um eine Verbindung zum `offer_id` Feld des `Offer` Datenfeeds herzustellen. | 
| offer\$1revision | Bildet zusammen mit dem Feld offer\$1id den Fremdschlüssel für die Angebotsüberarbeitung. | 
| product\$1id | Der Anzeigename des Produkts; dies ist der Fremdschlüssel für das Produkt, das zu diesem Angebot gehört. Kann verwendet werden, um eine Verbindung zum `product_id` Feld des `Product` Datenfeeds herzustellen. | 

## Beispiel für Datenfeeds zu Angebotsprodukten
<a name="data-feed-offer-product-sample-data"></a>

Das folgende Beispiel zeigt einen Datenfeed zu Angebotsprodukten. 


| offer\$1id  | offer\$1revision | product\$1id | 
| --- | --- | --- | 
| offer-dacpxznflfwin | 10 | prod-o4grxfafcxxxx | 
| offer-gszhmle5npzip | 24 | prod-o4grxfafcxxxy | 

# Datenfeed zum Angebotsziel
<a name="data-feed-offer-target"></a>

Dieser Datenfeed listet die Ziele der Überarbeitung eines Angebots für alle Angebote auf, die Sie als eingetragener Verkäufer erstellt haben. Wenn ein einzelnes Angebot mehrere Überarbeitungen aufweist, sind alle Änderungen im Datenfeed enthalten.

Wenn Sie ein Angebot überarbeiten und sich die Daten in einem angezeigten Feld ändern, wird im Datenfeed ein neuer Datensatz für denselben Primärschlüssel (`offer_id` plus `offer_revision`) erstellt, jedoch mit einem anderen Wert für das Feld `valid_from`. 

Der Datenfeed zum Angebotsziel wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten.


| Spaltenname  | Beschreibung  | 
| --- | --- | 
| offer\$1target\$1id | Der Primärschlüssel des Feeds. | 
| offer\$1id\$1offer\$1revision | Die Kennung und Überarbeitung des Angebots. Diese beiden Spalten verweisen auf das Angebot, auf das sich dieses Ziel bezieht.Kann verwendet werden, um die `offer_revision` Felder `offer_id` und des `Target` Datenfeeds zu verknüpfen. | 
| target\$1type | Gibt an, ob es sich bei dem Angebotsempfänger um BuyerAccounts handelt, was auf ein privates Angebot hinweist, oder um ParticipatingPrograms. | 
| polarity | Gibt an, ob das Angebot für den `target_type` gelten soll. Zulässige Werte sind: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-offer-target.html)  | 
| Wert | Eine Zeichenfolge, die das Ziel darstellt: entweder eine AWS Konto-ID oder ein Programm, das mit einem Angebot verwendet werden kann. Zum Beispiel [Standardvertrag für AWS Marketplace (SCMP)](standardized-license-terms.md#standard-contracts) oder [AWS Marketplace Felddemonstrationsprogramm (FDP)](field-demonstration-program.md). | 

## Beispiel für Datenfeeds zum Angebotsziel
<a name="data-feed-offer-target-sample-data"></a>

Das folgende Beispiel zeigt einen Datenfeed zum Angebotsziel. Zur besseren Lesbarkeit werden die Spalten zum Datenverlauf nicht angezeigt. Weitere Informationen zu Feldern zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization). 


| offer\$1target\$1id  | offer\$1id  | offer\$1revision | target\$1type | polarity | Wert | 
| --- | --- | --- | --- | --- | --- | 
| 925ddc73f6a373b7d5544ea3210610803b600 | offer-dacpxznflfwin | 1 | ParticipatingPrograms | PositiveTargeting | EnterpriseContract | 
| 471ff22ae3165278f1fb960d3e14517bcd601 | offer-gszhmle5npzip | 1 | ParticipatingPrograms | PositiveTargeting | FieldDemonstration | 
| 511ff22adfj65278f1fb960d3e14517bcd6e602 | offer-gszhmle5npzip | 1 | ParticipatingPrograms  | PositiveTargeting | EnterpriseContract | 

# Produktdatenfeed
<a name="data-feed-product"></a>

Dieser Datenfeed enthält Informationen zu allen Produkten, die Sie als eingetragener Verkäufer erstellt haben, und zu allen Produkten, zu deren Weiterverkauf Sie autorisiert sind.

Produktdaten sind veränderbar. Das heißt, wenn Sie den Wert für eins der folgenden Felder ändern, wird im Datenfeed ein neuer Datensatz mit einem anderen Wert für das Feld `valid_from` erstellt. Weitere Informationen zu den Datenfeed-Verlaufsspalten finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization). 

Der Produktdatenfeed wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten. 


| Spaltenname  | Beschreibung  | 
| --- | --- | 
| product\$1id | Der Anzeigename des Produkts.Kann verwendet werden, um eine Verbindung zu den `product_id` Feldern der `Offer_Product` Datenfeeds `Account``Billing_Event`, und herzustellen. | 
| manufacturer\$1account\$1id | Die Kennung des Produktinhabers. Dies ist ein Fremdschlüssel für den [Kontodatenfeed](data-feed-account.md).Kann verwendet werden, um eine Verbindung zum `account_id` Feld des `Account` Datenfeeds herzustellen. | 
| product\$1code | Der vorhandene Produktcode für die Berechtigung, der zum Messen des Produkts verwendet wird. Dieser Wert wird auch verwendet, um Daten mit einem Bericht zu verknüpfen oder um auf die im AWS Marketplace Metering Service bereitgestellten Informationen zu verweisen. | 
| Titel | Der Titel des Produkts.  | 

## Beispiel für Produktdatenfeeds
<a name="data-feed-product-sample-data"></a>

Das folgende Beispiel zeigt einen Datenfeed zum Angebotsziel. Zur besseren Lesbarkeit werden die Spalten zum Datenverlauf nicht angezeigt. Weitere Informationen zu Feldern zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization). 


| product\$1id  | manufacturer\$1account\$1id  | product\$1code | Titel | 
| --- | --- | --- | --- | 
| prod-o4grxfafcxxxx | 555568000000 | product\$1code\$11 | Product1 | 
| prod-t3grxfafcxxxy | 444457000000 | product\$1code\$12 | Product2 | 
| prod-x8faxxfafcxxy | 666678000000 | product\$1code\$13 | Product3 | 

# Daten-Feed für Steuerartikel
<a name="data-feed-tax-item"></a>

Dieser Datenfeed enthält Informationen zu Steuerberechnungen für eine Kundenrechnung.

Es können mehrere Einzelposten (`line_item_id`) für ein bestimmtes Produkt (`product_id`) eine bestimmten Kundenrechnung (`invoice_id`) vorhanden sein, mindestens eine für jede Steuergerichtsbarkeit. Dies ist beispielsweise bei nutzungsabhängigen Rechnungen für Kunden der Fall, die unterschiedliche AWS Regionsregeln von verschiedenen AWS Entitäten verwenden (z. B. in den USA und Irland). Weitere Informationen darüber, wo Umsatzsteuer, Mehrwertsteuer oder GST auf Ihre Verkäufe AWS erhoben und diese Steuern im Namen von AWS, Inc. an die lokalen Steuerbehörden überwiesen werden, finden Sie in der [Amazon Web Service Tax Help](https://aws.amazon.com/tax-help/).

Der Daten-Feed zum Steuerartikel wird alle 24 Stunden aktualisiert, sodass täglich neue Daten verfügbar sind.

Die Daten von Steuerartikeln sind unveränderlich. 

In der folgenden Tabelle finden Sie eine Übersicht über die Namen und Beschreibungen der Daten-Feed-Spalten. Weitere Informationen zu Spalten zum Datenverlauf finden Sie unter [Datenhistorisierung](data-feed-details.md#data-feed-historization). 


| Name der Spalte  | Description  | 
| --- | --- | 
| tax\$1item\$1id | Eine eindeutige Kennung für einen Steuerartikeldatensatz. | 
| invoice\$1id | Die AWS Rechnungs-ID. Sie können diesen Wert mit dem Wert von product\$1id verwenden, um zugehörige Steuerfakturierungsereignisse zu finden. | 
| line\$1item\$1id | Eine eindeutige Kennung für eine Einzelposition auf einer Kundenrechnung. Erstattungstransaktionen haben die gleiche Positions-ID wie ihre Steuertermintransaktionen. | 
| customer\$1bill\$1id | Die eindeutige Kennung der Kundenrechnung. Käufer können diese Kennung an den Verkäufer weitergeben, um Fragen zur Steuerberechnung zu identifizieren und zu lösen.  | 
| tax\$1liable\$1party | Entweder `AWS` oder `Seller`. Wenn der Verkäufer steuerpflichtig ist, werden Steuern erhoben. Wenn AWS es sich um die steuerpflichtige Partei handelt, wird die Umsatzsteuer von AWS erhoben und abgeführt. Weitere Informationen finden Sie unter [AWS Marketplace Verkäufer und Steuereinzug](https://aws.amazon.com/tax-help/marketplace). Wenn keine Steuern erhoben werden, wird hier kein Wert angezeigt. Der Verkäufer muss feststellen, ob für jede Rechnung bestimmte Steuern erhoben wurden, da der Verkäufer für die Steuererhebung verantwortlich ist.  | 
| transaction\$1type\$1code | Der Typ der Transaktion. Die möglichen Werte lauten wie folgt: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-tax-item.html) Rückerstattungstransaktionen haben die Positions-ID mit ihren ursprünglichen Termintransaktionen gemeinsam. | 
| product\$1id | Ein Fremdschlüssel für das Produkt.Kann verwendet werden, um dem `Product` Datenfeed auf dem `product_id` Feld beizutreten. | 
| product\$1tax\$1code | Ein Standard-Code zum Identifizieren der Steuer-Eigenschaften für ein Produkt. Verkäufer wählen die Eigenschaften aus, wenn sie das Produkt erstellen oder ändern. | 
| invoice\$1date | Das Datum, an dem die Rechnung erstellt wurde.  | 
| taxed\$1customer\$1account\$1id | Ein Fremdschlüssel für die Kontoentität, die besteuert wird.Kann verwendet werden, um eine Verbindung zum `Account` Datenfeed auf dem `account_id` Feld herzustellen. | 
| taxed\$1customer\$1country | Der ISO 3166 Alpha 2-Ländercode der Adresse, die für Steuerberechnungen verwendet wird.  | 
| taxed\$1customer\$1state\$1or\$1region | Das Bundesland, die Region oder die Provinz, die für Steuerberechnungen verwendet wird. | 
| taxed\$1customer\$1city | Die Stadt, die für Steuerberechnungen verwendet wird. | 
| taxed\$1customer\$1postal\$1code | Die Postleitzahl, die für Steuerberechnungen verwendet wird. | 
| tax\$1location\$1code\$1taxed\$1jurisdiction | Der Vertex-Geocode, der dem Steuerstandort zugeordnet ist.  | 
| tax\$1type\$1code | Der Typ der Steuer, der für die Transaktion angewendet wird. Die möglichen Werte sind None, Sales und SellerUse. | 
| jurisdiction\$1level | Die Zuständigkeitsebene der Adresse, die für den Steuerstandort verwendet wird. Die möglichen Werte sind State, County, City.und District. | 
| taxed\$1jurisdiction | Name der Steuergerichtsbarkeit.  | 
| display\$1price\$1taxability\$1type | Ob der Preis, den Käufer sehen, inklusive oder exklusive Steuern angegeben wird. Alle AWS Marketplace Angebote verstehen sich zuzüglich Steuern.  | 
| taxable\$1amount | Der steuerpflichtige Betrag der Transaktion auf dieser Gerichtsbarkeitsebene. | 
| nontaxable\$1amount | Der nicht steuerpflichtige Betrag der Transaktion nach Gerichtsbarkeitsebene. | 
| tax\$1jurisdiction\$1rate | Der Steuersatz der auf dieser Gerichtsbarkeitsebene angewendet wird. | 
| tax\$1amount | Die Höhe der Steuer, die auf dieser Gerichtsbarkeitsebene berechnet wird. | 
| tax\$1currency | Der ISO 4217 Alpha 3-Währungscode für oben genannte Beträge. | 
| tax\$1calculation\$1reason\$1code | Nach Jurisdiktionsbereich: ein Kennzeichen, ob die Transaktion steuerpflichtig, nicht steuerpflichtig, steuerbefreit oder steuerfrei ist. | 
| date\$1used\$1for\$1tax\$1calculation | Das Datum, das zur Berechnung der Steuer auf die Transaktion verwendet wird. | 
| customer\$1exemption\$1certificate\$1id | Die Zertifikat-ID der Freistellungsbescheinigung. | 
| customer\$1exemption\$1certificate\$1id\$1domain | Der Speicherort, an dem das Zertifikat auf Amazon-Systemen gespeichert ist.  | 
| customer\$1exemption\$1certificate\$1level | Die Zuständigkeitsebene, die die Freistellung genehmigt hat. | 
| customer\$1exemption\$1code | Der Code für die Befreiung, z. B. RESALE. | 
| customer\$1exemption\$1domain | Das Amazon-System, das verwendet wird, um die Kundenfreistellungsinformationen zu erfassen (falls verfügbar). | 
| transaction\$1reference\$1id | Eine Kennung, mit der Sie Querverweise zu Daten aus den folgenden Berichten erstellen können: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/de_de/marketplace/latest/userguide/data-feed-tax-item.html)  | 
| legal\$1amount | Der Steuerbetrag in der gesetzlichen Währung für die zu zahlende Steuer. | 
| legal\$1currency | Die gesetzliche Währung für die zu zahlende Steuer. | 
| tax\$1invoice\$1id | Die Steuerrechnungsnummer für die Steuerposition bei doppelter Rechnungsstellung. Für Szenarien mit einheitlicher Rechnungsstellung ist dieses Feld leer. | 
| tax\$1invoice\$1date | Das Datum der Steuerrechnung. Dieses Feld ist für Szenarien mit einheitlicher Rechnungsstellung leer. | 

**Anmerkung**  
Ab dem 5. August 2021 werden die internationalen Marketplace Facilitator-Steuern für AWS Marketplace Verkäufe Einträge im Datenfeed für Steuerartikel enthalten. Das bedeutet, dass ab dem 5. August 2021 für jeden AWS\$1TAX\$1SHARE SELLER\$1TAX\$1SHARE-Datensatz im Datenfeed mit Abrechnungsereignissen ein entsprechender Datensatz im Datenfeed für Steuerartikel erwartet wird.

## Beispiel für den Daten-Feed für Steuerartikel
<a name="data-feed-tax-item-sample-data"></a>

Das folgende Beispiel zeigt einen Daten-Feed zum Steuerartikel. Im Datenfeed werden diese Informationen in einer einzigen Tabelle dargestellt. Zur Lesbarkeit werden die Daten hier in mehreren Tabellen angezeigt, und nicht alle Spalten werden angezeigt. 


| tax\$1item\$1id | invoice\$1id | line\$1item\$1id | customer\$1bill\$1id | 
| --- | --- | --- | --- | 
| 6p2ni6tu041xagvhbyanbgxl3xameha16txjoav\$10001 | 781216640 | 71000000000000000000 | 2210000000000000000 | 
| 6p2ni6tu041xagvhbyanbgxl3xameha16txjoav\$10002 | 781216640 | 53000000000000000000 | 2210000000000000000 | 
| flr4jobxjzww8czdsrq4noue2uxd56j39wxw0k7\$10001 | 250816266 | 76400000000000000000 | 5720000000000000000 | 
| gfkjjobxjzw56jgkrsrqgjtk52uxd56j39wgj567d\$10002 | 280336288 | 76400000000000000000 | 5724390000000000000 | 
| wwk1qpvb8ran3geiw8e3mp6dgs2qj7wpkuwhgk1\$10001 | 451431024 | 99300000000000000000 | 1230000000000000000 | 
| wwk1qpvb8ran3geiw8e3mp6dgs2qj7wpkuwhgk1\$10002 | 451431024 | 99300000000000000000 | 3120000000000000000 | 
| fnohdid8kwgqq9lvii2k30spn3ftgwihbe8h75x\$10001 | 229987654 | 92100000000000000000 | 6390000000000000000 | 




| tax\$1liable\$1party | transaction\$1type\$1code | product\$1id | product\$1tax\$1code | invoice\$1date | 
| --- | --- | --- | --- | --- | 
| Verkäufer | AWS | prod-o4grxfafcxxxx | AWSMP\$1SOFTWARE\$1RA | 2018-12-31T00:00:00Z | 
| Verkäufer | AWS | prod-o4grxfafcxxxx | AWSMP\$1SOFTWARE\$1RA | 2018-12-31T00:00:00Z | 
| Verkäufer | AWS | prod-t3grxfafcxxxy | AWS\$1REMOTE\$1ZUGANGSSOFTWARE | 2018-08-31T00:00:00Z | 
| Verkäufer | ERSTATTUNG | prod-t3grxfafcxxxy | AWS\$1REMOTE\$1ZUGANGSSOFTWARE | 2018-08-31T00:00:00Z | 
| Verkäufer | AWS | prod-x8faxxfafcxxy | AWS\$1REMOTE\$1ZUGANGSSOFTWARE | 2018-08-31T00:00:00Z | 
| Verkäufer | TAXONLYREFUND | prod-x8faxxfafcxxy | AWS\$1REMOTE\$1ZUGANGSSOFTWARE | 2018-05-31T00:00:00Z | 
| AWS | AWS | prod-wghj8xfafrhgj | AWS\$1REMOTE\$1ZUGANGSSOFTWARE | 2019-07-31T00:00:00Z | 




| taxed\$1customer\$1account\$1id | taxed\$1customer\$1country | taxed\$1customer\$1state\$1or\$1region | taxed\$1customer\$1city | taxed\$1customer\$1postal\$1code | 
| --- | --- | --- | --- | --- | 
| VIeGA2T9J3MUXIOH9WC8LSND XRIOCm5 XXCg GCGUree | US | GA | MILTON | 48573-4839 | 
| VIeGA2T9J3MUXIOH9WC8LSND XRIOCm5 XXCg GCGUree | US | GA | MILTON | 48573-4839 | 
| 7NYO5JW PLYX81VX9JI04 O1FF8BIQI88W8 TRo eEwTur | US | NC | DURHAM | 27517-4834 | 
| 7nyo5jw TRo PLYX81VX9JI04 O1FF8BIQI88W8 eEwTur | US | NC | DURHAM | 27517-4834 | 
| 7nyo5jw TRo PLYX81VX9JI04 O1FF8BIQI88W8 eEwTur | US | TX | NICHT VERFÜGBAR | 75844-1235 | 
| 7nyo5jw TRo PLYX81VX9JI04 O1FF8BIQI88W8 eEwTur | US | TX | HOUSTON | 75844-1235 | 
| 192a0421313e41f069b52962ed7babf716291b688 | US | CT | NEW HAVEN | 06002-2948 | 




| tax\$1location\$1code\$1taxed\$1jurisdiction | tax\$1type\$1code | jurisdiction\$1level | taxed\$1jurisdiction | display\$1price\$1taxability\$1type | taxable\$1amount | nontaxable\$1amount | 
| --- | --- | --- | --- | --- | --- | --- | 
| 460473664 | Vertrieb | Status | GA | Exklusiv | 100 | 0 | 
| 66301164 | Vertrieb | Bezirk | FULTON | Exklusiv | 0 | 100 | 
| 692938178 | SellerUse | Status | NC | Exklusiv | 58,1 | 523,8 | 
| 692938178 | SellerUse | Status | NC | Exklusiv | -58,1 | 523,8 | 
| 356794387 | Vertrieb | Status | TX | Exklusiv | 1105,14 | 0 | 
| 528887443 | Vertrieb | Ort | HOUSTON | Exklusiv | -36 | 0 | 
| 171248162 | Vertrieb | Status | CT | Exklusiv | 0 | 114,55 | 




| tax\$1jurisdication\$1rate | tax\$1amount | tax\$1currency | tax\$1calculation\$1reason\$1code | date\$1used\$1for\$1tax\$1calculation | 
| --- | --- | --- | --- | --- | 
| 0.206 | 20.6 | USD | Taxable | 2018-10-31T00:00:00Z | 
| 0 | 0 | USD | NonTaxable | 2018-10-31T00:00:00Z | 
| 0.1 | 5,8 | USD | Taxable | 2018-07-31T00:00:00Z | 
| 0.1 | -5,8 | USD | Taxable | 2018-07-31T00:00:00Z | 
| 0,06 | 66,3 | USD | Taxable | 2018-07-31T00:00:00Z | 
| 0.01 | -0,36 | USD | NonTaxable | 2018-07-31T00:00:00Z | 
| 0 | 0 | USD | Freigestellt | 2019-06-30T00:00:00Z | 

