0

我有一个查询,按会计月份按客户提取销售额。但是,我有一些客户在给定月份没有购买。对于这些情况,我希望 MonthNum 字段的 SalesDlr 值为 0,但 MonthNum 值仍需要是实际的月份数。目前,我在下面的查询中没有得到 MonthNum 值:

SELECT
    a.Customer,
    a.CustomerName,
    a.MonthNum,
    a.FiscalYear,
    a.SalesDlr
FROM
(SELECT
    sd.SBCUST AS Customer,
    sd.RMNAME AS CustomerName,
    fc.FiscalMonthNum AS MonthNum,
    fc.FiscalYear,
    SUM(sd.SBEPRC) AS SalesDlr
FROM
    dbo.SalesData sd
    LEFT OUTER JOIN dbo.FiscalCalendar fc ON fc.FiscalDate = sd.SBINDT
WHERE
    sd.SBTYPE = 'O'
AND
    sd.SBINDT > '2012-12-31'
AND
    sd.SBCLS NOT IN ('1500')
GROUP BY
    sd.SBCUST,
    sd.RMNAME,
    fc.FiscalMonthNum,
    fc.FiscalYear
)a
GROUP BY
    a.Customer,
    a.CustomerName,
    a.MonthNum,
    a.FiscalYear,
    a.SalesDlr
ORDER BY
    a.Customer,
    a.MonthNum,
    a.FiscalYear

我该如何解决?

4

1 回答 1

1

我猜您的 SalesData 每个月都没有每个客户的条目。如果客户 Curtis 在 5 月份没有进行购买,那么他可能在 5 月份的 SalesData 中没有任何条目。因此,当您使用左侧的 SalesData 离开联接时,Curtis 将不会有 May 的一行。

切换左连接的顺序也是不够的,因为这只会为丢失的客户生成一个日期。因此,您真的想要不同客户和不同月份之间的交叉连接,然后得到这些的总和:

with FilteredSalesData as (
    SELECT  
        sd.SBCUST as Customer,
        sd.RMName as CustomerName,
        sd.SBEPRC,
        fc.FiscalMonthNum as MonthNum,
        fc.FiscalYear
    FROM dbo.SalesData sd
    join FiscalCalendar fc ON fc.FiscalDate = sd.SBINDT
        WHERE
            sd.SBTYPE = 'O'
        AND
            sd.SBCLS NOT IN ('1500')
), DistinctCustomers as (
    select distinct 
        SBCUST as Customer,
        RMName as CustomerName
    from FilteredSalesData
), DistinctMonths as (
    select distinct
        FiscalMonthNum as MonthNum,
        FiscalYear
    From FiscalCalendar
    WHERE FiscalDate > '2012-12-31'
)
select
    Customer,
    CustomerName,
    MonthNum,
    FiscalYear,
    SUM(sd.SBEPRC) as SalesDlr
From DistinctCustomers dc
CROSS JOIN DistinctMonths dm
left Join FilteredSalesData sd 
    on sd.customer = dc.Customer 
    and sd.CustomerName = dc.CustomerName
    and sd.MonthNum = dm.MonthNum
    and sd.FiscalYear = dm.FiscalYear
group by Customer, CustomerName, MonthNum, FiscalYear
order by Customer, MonthNum, FiscalYear
于 2013-06-21T00:28:32.093 回答