根据值从结果集中选择特定记录

时间:2011-08-09 18:00:03

标签: sql ms-access

我有一个查询尝试编制费用和信用报告,按项目代码和结算周期分组。它从中提取的Charge表具有以下格式:

BillingPeriod|ItemCode|ItemName|Charge|IsAdjustment|AdjustmentDate|ReportTimestamp

我认为,我遇到了一些问题,我当前的查询处理得非常好。由于有些时候计费代码没有出现在收费表中,因为我们没有收费,但是我想要一个显示每个结算周期的统一表,所以我制作了一个充满计费周期和零的虚拟表,和Union一起使用Charges表的结果,如下:

SELECT BillingPeriod, SumOfCharge AS Total FROM (
        SELECT BillingPeriod, 0 AS SumOfCharge
        FROM Charges
        UNION
        SELECT BillingPeriod, SUM(Charge) AS SumOfCharge
        FROM Charges
        WHERE (ItemCode Between 1900 and 1995)
        GROUP BY BillingPeriod
);

所以最终发生的事情是这样的:例如,比如我在2011年1月和3月收取一笔费用,但没有别的。该表将返回如下输出:

BillingPeriod|Charge
1/1/2011     |100.00
1/1/2011     |0
2/1/2011     |0
3/1/2011     |0
3/1/2011     |-23.00
4/1/2011     |0
5/1/2011     |0
6/1/2011     |0
7/1/2011     |0

我要做的是摆脱那些0值的行,并选择要在报告中显示的正确行。唯一棘手的部分是值可能是正数,负数或零,所以只做MAX就行不通。我也试过FIRST()或LAST(),(COALESCE())不起作用,我正在访问)。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

只需按SumOfCharge总结BillingPeriod字段和分组:

SELECT BillingPeriod, SUM(SumOfCharge) AS Total FROM (
    SELECT BillingPeriod, 0 AS SumOfCharge
    FROM Charges
    UNION
    SELECT BillingPeriod, SUM(Charge) AS SumOfCharge
    FROM Charges
    WHERE (ItemCode Between 1900 and 1995)
    GROUP BY BillingPeriod
) GROUP BY BillingPeriod;

答案 1 :(得分:1)

怎么样:

SELECT P.BillingPeriod, 
ISNULL(C.SumOfCharge,0) AS SumOfCharge
FROM (
    SELECT Distinct BillingPeriod
    FROM Charges) AS P
LEFT JOIN 
    (SELECT BillingPeriod, SUM(Charge) AS SumOfCharge
    FROM Charges
    WHERE (ItemCode Between 1900 and 1995)
    GROUP BY BillingPeriod) as C
ON P.BillingPeriod = C.BillingPeriod
ORDER BY P.BillingPeriod

答案 2 :(得分:0)

这样的事情会起作用吗?

SELECT C.BillingPeriod,
       ISNULL(C1.SumOfCharge, 0) AS Total
FROM Charges
LEFT OUTER JOIN (SELECT BillingPeriod, SUM(Charge) AS SumOfCharge
                 FROM Charges
                 WHERE (ItemCode Between 1900 and 1995)
                 GROUP BY BillingPeriod) C1 ON C.BillingPeriod = C1.BillingPeriod