我想得到按日期排序的费用和付款的综合结果。这是我正在尝试的查询:
SELECT ClientID, TheDate, Payment, Cost
FROM
(
SELECT PaymentDate AS TheDate, Amount AS Payment, ClientID
FROM Payment
UNION ALL
SELECT BookedDate AS TheDate, Cost, ClientID
FROM [All Bookings Query]
)
ORDER BY TheDate DESC;
它几乎可以工作......但是,弹出一个框为我输入“付款”的值(就像字段不存在一样)。如果我将其留空并点击OK,我会得到一个结果集,其中“Payment”列完全空白,而“Cost”列包含两个表中的金额。我正在使用的字段名称是100%正确的。
我认为问题在于UNION正在尝试将两个表压缩成一个包含3列的结果,而我正在尝试选择4.我以前从未做过这样的查询,所以我不知道如何绕过那个。
我想要的是付款和费用在不同的列中。我的查询出了什么问题?
答案 0 :(得分:1)
您需要在每个子查询中包含4列,将0列入付款的费用列,将0列入预订的付款列。
SELECT ClientID, TheDate, Payment, Cost
FROM
(
SELECT PaymentDate AS TheDate, Amount AS Payment, 0 AS Cost, ClientID
FROM Payment
UNION ALL
SELECT BookedDate AS TheDate, 0 As Payment, Cost, ClientID
FROM [All Bookings Query]
)
ORDER BY TheDate DESC;