SELECT 
    so.external_ref AS "Bestellnummer",
    TO_CHAR(so.order_date, 'YYYY-MM-DD"T"HH24:MI:SS') AS "Bestelldatum",
    TO_CHAR(so.shipping_date, 'YYYY-MM-DD') AS "Versanddatum",
    COALESCE(ad.first_name, '') AS "Vorname",
    COALESCE(ad.last_name, '') AS "Nachname",
    COALESCE(ad.street, '') AS "Strasse",
    COALESCE(ad.house_number, '') AS "Hausnummer",
    COALESCE(ad.zip, '') AS "PLZ",
    COALESCE(ad.city, '') AS "Stadt",
    COALESCE(ad.country_name, '') AS "Land",
    COALESCE(pm.code, '') AS "Zahlungsart",
    COALESCE(so.amount_net, 0) AS "Gesamtbetrag_netto",
    COALESCE(so.amount_shipping, 0) AS "Versandkosten",
    COALESCE(so.total_amount, 0) AS "Gesamtbetrag_brutto",
    COALESCE(so.amount_discount, 0) AS "Rabatt",
    COALESCE(SUM(CASE WHEN p.id = 8 THEN a.qty ELSE 0 END), 0) AS "#_ChagaFlaschen",
    COALESCE(SUM(CASE WHEN p.id = 5 THEN a.qty ELSE 0 END), 0) AS "#_ReishiFlaschen",
    COALESCE(SUM(CASE WHEN p.id = 9 THEN a.qty ELSE 0 END), 0) AS "#_ShiitakeFlaschen",
    COALESCE(SUM(CASE WHEN p.id = 6 THEN a.qty ELSE 0 END), 0) AS "#_LionsManeFlaschen"
FROM sales_order so
LEFT JOIN address ad ON so.party_id = ad.party_id AND ad.type = 'shipping'
LEFT JOIN payment_method pm ON so.payment_method_id = pm.id
LEFT JOIN sales_order_line sol ON so.id = sol.sales_order_id
LEFT JOIN sales_order_line_lot_allocation a ON sol.id = a.sales_order_line_id
LEFT JOIN product p ON a.product_id = p.id AND p.status = 'active'
WHERE so.external_ref = $1
GROUP BY so.id, ad.id, pm.id