当1个表在2个表之间为空时,不返回任何内容

时间:2015-11-01 05:09:01

标签: sql-server tsql

SELECT
  A.AccID,
  ISNULL(A.Camt, 0) AS Camt,
  ISNULL(B.Damt, 0) AS Damt
FROM (
  SELECT SUM(J.Amount) AS Camt,
    J.AccID
  FROM dbo.Journal AS J
  INNER JOIN dbo.Voucher AS V ON J.Vid = V.Vid
  WHERE
    J.DRCR = 'D' AND
    AccID = 1200181
  GROUP BY J.AccID
  ) AS A
FULL JOIN (
  SELECT SUM(J.Amount) AS Damt,
    J.AccID
  FROM dbo.Journal AS J
  INNER JOIN dbo.Voucher AS V ON J.Vid = V.Vid
  WHERE
    J.DRCR = 'C' AND
    AccID = 1200181
  GROUP BY J.AccID
  ) AS B ON A.AccID = B.AccID

当子查询A或子查询B为空时,不返回任何内容。

如果任何表有数据,我想返回。有可能吗?

1 个答案:

答案 0 :(得分:0)

正如评论中所述,我相信您的回答是对数据的错误假设。不过,以下查询不会为您提供您要查找的结果(假设数据正确)?

SELECT SUM(CASE WHEN J.DRCR = 'D' THEN J.Amount END) AS Damt,
  SUM(CASE WHEN J.DRCR = 'C' THEN J.Amount END) AS Camt,
  J.AccID
FROM dbo.Journal AS J
--INNER JOIN dbo.Voucher AS V ON J.Vid = V.Vid
WHERE j.AccID = 1200181
GROUP BY J.AccID
HAVING SUM(CASE WHEN J.DRCR IN ('D','C') THEN J.Amount END) > 0

注意评论表,我在现有查询中没有看到任何用途。唯一的功能可能是过滤Journal中与Voucher不匹配的行。