0

下面是我的要求

Table1 - QuotationMaster - QuoteID,CustomerID,Date,InvoiceNo
Table2 - QuoteItems - QuoteID,ItemID,CurrencyID,Amount
Table3 - CurrencyMaster - CurrencyID,CurrencyCode

例子:

如果我搜索特定日期的发票报表,最终结果必须是

日期、客户名称、货币代码、金额

对于特定发票,如果它有 2 个具有相同 CurrencyID 的项目,则结果应显示如下

第 1 项 - 金额 (2.00) 第 2 项 - 金额 (3.00)

Date   InvoiceNo  CustomerName    CurrencyCode   Amount
June    INV123     TESTING          INR           5.00

对于特定发票,如果它有 2 个具有不同 CurrencyID 的项目,则结果应显示如下

Date   InvoiceNo  CustomerName    CurrencyCode   Amount
June    INV123     TESTING          0          0.00

为简单起见,如果发票有两个使用不同货币的项目,则货币代码和金额必须为 0。

我无法清楚地了解如何解决这个问题,因为我最终使用 groupby currencyid 并打印了两次相同的结果

Date   InvoiceNo  CustomerName    CurrencyCode   Amount
June    INV123     TESTING          INR          2.00
June    INV123     TESTING          GBP          3.00

你能帮我解决这个问题吗?

4

2 回答 2

0

当我理解这一点时,您基本上想要对项目进行分组quoteid并过滤子句中最大值currencyid不等于最小值currencyid的那些。HAVING(如果所有货币 ID 都相同,则最小值等于最大值。)

然后将其加入您的报价表并左加入货币表以获取代码。

如果是货币 ID,请检查一个案例IS NULL。如果是,则报价中的项目具有不同的货币 ID(或者全部都是NULL,这意味着它们是不同的,根据三态逻辑)。

由于您没有描述您的客户表,因此未选择客户名称。您必须自己添加。

SELECT qm1.date,
       qm1.invoiceno,
       CASE
         WHEN qi2.quoteid IS NULL
           THEN cm1.currencycode
         ELSE
           '0'
       END currencycode,
       CASE
         WHEN qi2.quoteid IS NULL
           THEN qi2.amount
         ELSE
           0
       END amount
       FROM quotationmaster qm1
            LEFT JOIN (SELECT qi1.quoteid,
                              sum(qi1.amount) amount,
                              max(qi1.currencyid) currencyid
                              FROM quoteitems qi1
                              GROUP BY qi1.quoteid
                              HAVING max(qi1.currencyid) = min(qi1.currencyid)) qi2
                      ON qi2.quoteid = qm1.quoteid
            LEFT JOIN currencymaster cm1
                      ON cm1.currencyid = cm1.qurrencyid;
于 2018-06-28T12:18:11.883 回答
0

你可以试试这个:

SELECT sub.QuoteID,
    sub.CustomerID,
    sub.Date,
    sub.InvoiceNo,
    sub.ItemID,
    IIF(sub.ItemCount = sub.CurrencyCount, sub.CurrencyID, 0) AS CurrencyID
    sub.Amount,
FROM (
    SELECT qm.QuoteID,
        qm.CustomerID,
        qm.Date,
        qm.InvoiceNo,
        qi.ItemID,
        qi.CurrencyID,
        qi.Amount,
        COUNT(*) OVER (PARTITION BY qi.QuoteID) AS ItemCount,
        COUNT(*) OVER (PARTITION BY qi.QuoteID, qi.CurrencyID) AS CurrencyCount
    FROM QuotationMaster AS qm
        INNER JOIN QuoteItems AS qi
            ON qi.QuoteID = qm.QuoteID
) AS sub
-- You can use it also for a join (a 'n/a'-Currency in CurrencyMaster with ID=0 is required)
-- INNER JOIN CurrencyMaster AS cm
--  ON cm.CurrencyID = IIF(sub.ItemCount = sub.CurrencyCount, sub.CurrencyID, 0)
-- OR Use LEFT OUTER JOIN if you dont have a Fallback-Value in CurrencyMaster.
于 2018-06-28T12:43:36.837 回答