Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
1.3 kB
1
Indexable
Never
-- Шаг 1: Объединение таблиц MO и KP
SELECT 
    client_inn_dil,
    transaction_date,
    SUM(CASE WHEN label = 'dil_MO' THEN total_monthly_ton_dil ELSE 0 END) AS MO_dealer_monthly_ton,
    SUM(CASE WHEN label = 'dil_KP' THEN total_monthly_ton_dil ELSE 0 END) AS KP_dealer_monthly_ton
INTO #CombinedVolumes
FROM (
    SELECT client_inn_dil, transaction_date, total_monthly_ton_dil, 'dil_MO' AS label
    FROM [SANDBOX_DB_TEAM_21].[dbo].[TIT_dealer_MO_final]
    UNION ALL
    SELECT client_inn_dil, transaction_date, total_monthly_ton_dil, 'dil_KP' AS label
    FROM [SANDBOX_DB_TEAM_21].[dbo].[TIT_dealer_KP_final]
) AS CombinedData
GROUP BY client_inn_dil, transaction_date;

-- Шаг 2: Обновление объемов для клиентов с лейблом dil_MO+KP в итоговой таблице
UPDATE final
SET 
    MO_dealer_monthly_ton_GZPN = cv.MO_dealer_monthly_ton,
    KP_dealer_monthly_ton_GZPN = cv.KP_dealer_monthly_ton,
    MO_KP_monthly_ton_GZPN = cv.MO_dealer_monthly_ton + cv.KP_dealer_monthly_ton
FROM [SANDBOX_DB_TEAM_21].[dbo].[clients_dealer_labeled_final] AS final
INNER JOIN #CombinedVolumes AS cv ON final.client_inn_dil = cv.client_inn_dil AND final.transaction_date = cv.transaction_date
WHERE final.label = 'dil_MO+KP';
Leave a Comment