我有一个Query,当我在选择列表中有主键时会返回两个不同的结果,而当主键不存在时会返回另一个结果。
以下是使用主键'FDReciptNo'的查询。
使用Primary键结果是(3478)记录,在内部select语句的select语句中没有主键我有1274条记录。
想了解为何会有这样的差异?
SELECT SUM(PrincipleAmount) AS PrincipleAmount FROM
(
SELECT
FDReceiptNo, PrincipleAmount
FROM mFixedDeposit
WHERE CurrentStatus = ' ' AND
DepositDate <= '9/20/2013 12:00:00 AM' AND
FDReceiptNo NOT IN
(
SELECT FDReceiptNo FROM mFixedDeposit
WHERE
TransactionDate > '9/20/2013 12:00:00 AM' AND MaturityDate <= '9/20/2013 12:00:00 AM'
)
UNION
SELECT
FDReceiptNo, PrincipleAmount
FROM mFixedDeposit
WHERE TransactionDate > '9/20/2013 12:00:00 AM' AND
MaturityDate <= '9/20/2013 12:00:00 AM'
) AS tbl
答案 0 :(得分:11)
UNION
也会执行DISTINCT
,因此如果没有PK,您会多次出现其余列,这些将减少为一个。
尝试UNION ALL
,这并不意味着DISTINCT
。
答案 1 :(得分:0)
作为geomagas pointed out,UNION存在隐式DISTINCT,但由于涉及相同的表和字段,因此您只需使用OR
即可。这也允许您删除内联视图
SELECT
SUM(PrincipleAmount) AS PrincipleAmount
FROM mFixedDeposit
WHERE (CurrentStatus = ' ' AND
DepositDate <= '9/20/2013 12:00:00 AM' AND
FDReceiptNo NOT IN
(
SELECT FDReceiptNo FROM mFixedDeposit
WHERE
TransactionDate > '9/20/2013 12:00:00 AM' AND MaturityDate <= '9/20/2013 12:00:00 AM'
))
OR
(
TransactionDate > '9/20/2013 12:00:00 AM' AND
MaturityDate <= '9/20/2013 12:00:00 AM'
)