0

这是我的查询的样子:

DECLARE @month date
DECLARE @CustomerId int
DECLARE @InterfacedSystemId int

SET @month = '2013-05-01'
SET @CustomerId = 24
SET @InterfacedSystemId = 1

SELECT * FROM
(
SELECT CONVERT(BIGINT,MisparHeshbonit) AS PreProcInvoiceNumber ,CONVERT(DATE,TaarichErech,103) AS PreProcDate , ROUND(sum(convert(float,SchumBruto)),2) AS PreProcSum  
FROM [VisaCalCredit] VCC
WHERE CONVERT(DATE,TaarichErech,103) BETWEEN @month AND DATEADD(DAY,-1,DATEADD(MONTH,1,@month))
      AND VCC.CustomerID = @CustomerID
GROUP BY MisparHeshbonit , CONVERT(DATE,TaarichErech,103)

) AS PreTable
ORDER BY PreProcInvoiceNumber, PreProcDate

SELECT * FROM
(
SELECT InvoiceNumber AS PostProcInvoiceNumber,ActualPaymentTime AS PostProcDate ,ROUND(sum(GrossAmount),2) AS PostProcSum 
FROM [CreditAndDebit] C INNER JOIN [Transaction] T ON C.TransactionID = T.ID 
WHERE ActualPaymentTime BETWEEN @month AND DATEADD(DAY,-1,DATEADD(MONTH,1,@month))
      AND T.CustomerID = @CustomerId
      AND T.InterfacedSystemID = 1
GROUP BY InvoiceNumber , ActualPaymentTime

) AS PostTable
ORDER BY PostProcInvoiceNumber ,PostProcDate

我需要在这些表中找到 PreProcSum 和 PostProcSum 之间的差异 - 我不能在内部表本身之间进行内部连接(触发其他问题)。

如何在此查询中定义的这两个表之间进行内部连接?

4

1 回答 1

3

如果您的密钥是 (InvoiceNumber, Date),我相信您可以这样做:

;WITH PreTable AS (
  SELECT 
    CONVERT(BIGINT,MisparHeshbonit) AS PreProcInvoiceNumber,
    CONVERT(DATE,TaarichErech,103) AS PreProcDate,
    ROUND(sum(convert(float,SchumBruto)),2) AS PreProcSum  
  FROM [VisaCalCredit] VCC
  WHERE 
    CONVERT(DATE,TaarichErech,103) BETWEEN @month AND DATEADD(DAY,-1,DATEADD(MONTH,1,@month))
    AND VCC.CustomerID = @CustomerID
  GROUP BY MisparHeshbonit, CONVERT(DATE,TaarichErech,103)
),
PostTable AS (
  SELECT 
    InvoiceNumber AS PostProcInvoiceNumber,
    ActualPaymentTime AS PostProcDate,
    ROUND(sum(GrossAmount),2) AS PostProcSum 
  FROM [CreditAndDebit] C INNER JOIN [Transaction] T ON C.TransactionID = T.ID 
  WHERE ActualPaymentTime BETWEEN @month AND DATEADD(DAY,-1,DATEADD(MONTH,1,@month))
    AND T.CustomerID = @CustomerId
    AND T.InterfacedSystemID = 1
  GROUP BY InvoiceNumber, ActualPaymentTime
),
MergedKeys AS (
  SELECT 
    PreProcInvoiceNumber AS InvoiceNumber,
    PreProcDate AS TheDate
  FROM PreTable
  UNION ALL
  SELECT 
    PostProcInvoiceNumber,
    PostProcDate
  FROM PostTable
)
SELECT *
FROM 
  MergedKeys mk
  LEFT JOIN PreTable prt
    ON prt.PreProcInvoiceNumber = mk.InvoiceNumber
    AND prt.PreProcDate= mk.TheDate
  LEFT JOIN PostTable pot
    ON pot.PostProcInvoiceNumber = mk.InvoiceNumber
    AND pot.PostProcDate= mk.TheDate
ORDER BY 
  mk.InvoiceNumber,
  mk.TheDate

如果您确定将在两个选择中获得所有发票数据,请将 LEFT JOIN 替换为 JOIN。

于 2013-07-29T08:11:38.200 回答