我有以下SQl声明:
SELECT id + 100000000000000000 AS id,
a.external_code + CAST(id AS varchar(15)) as crUniqueId,
m.check_amount,
'C' as crType,
m.postprint_date as activationDate,
m.postprint_date as creationDate,
m.memo_explanation as reasonLine1,
m.check_no,
m.check_amount - sh.sumAmount As dispositionAmount
FROM md_master m
Join accounts a on m.account_tag = a.acct_id
LEFT JOIN (SELECT master_id,
SUM(md_cr_pending.current_amount) as sumAmount
FROM md_cr_pending
Group BY master_id) sh ON master_id = m.ID
WHERE (m.postprint_tag = 2) OR (m.postprint_tag = 4) OR
(m.postprint_tag = 5) OR (m.postprint_tag = 7)
UNION ALL
SELECT id + 200000000000000000 as id,
'PERCHK' + CAST(id AS varchar(15)) as crUniqueId,
check_amount,
'P' as crType,
business_date as activationDate,
business_date as creationDate,
identify_description as reasonLine1,
check_no,
check_amount - sh.sumAmount As dispositionAmount
FROM cd_personal_checks
LEFT JOIN (SELECT cd_personal_checks_id,
SUM(md_cr_pending.current_amount) as sumAmount
FROM md_cr_pending
Group BY cd_personal_checks_id) sh
ON sh.cd_personal_checks_id = cd_personal_checks.ID
我想为UNION的每个select语句添加一个额外的列。但是,我需要使用创建为前一列的别名。
例如。我想做以下
m.check_amount - sh.sumAmount As dispositionAmount, m.check_amount-dispositionAmount AS openBalance
和
check_amount - sh.sumAmount As dispositionAmount, check_amount-dispositionAmount AS openBalance
分别
可以这样做吗?目前,我在上面的方式,我得到一个“无效的列名'dispositionAmount'”
感谢名单
答案 0 :(得分:2)
不能它不能在同一级别上,因为您在“按顺序”部分中仅选择“可用”中的别名。这是因为逻辑查询处理。
为此你应该建立更多关卡,或者再次使用表达式。
我不知道,你想这样做:
m.check_amount - sh.sumAmount As dispositionAmount,
m.check_amount - dispositionAmount AS openBalance
因为它等于:
m.check_amount - sh.sumAmount As dispositionAmount,
m.check_amount - m.check_amount + sh.sumAmountAS AS openBalance
这是:
m.check_amount - sh.sumAmount As dispositionAmount,
sh.sumAmountAS AS openBalance
答案 1 :(得分:0)
不,它无法完成。您需要重复计算dispositonAmount
。
...
m.check_amount - sh.sumAmount As dispositionAmount,
m.check_amount - (m.check_amount - sh.sumAmount) AS openBalance
...
答案 2 :(得分:0)
表达式check_amount-dispositionAmount
与check_amount-(check_amount - sh.sumAmount)
相同,与(check_amount-check_amount) + sh.sumAmount
相同,因此只有sh.sumAmount
。
所以:
check_amount - sh.sumAmount As dispositionAmount, sh.sumAmount AS openBalance
答案 3 :(得分:0)
您可以使用CROSS APPLY CROSS APPLY
SELECT my_num, my_num*5 AS another_number FROM table CROSS APPLY (SELECT 5 AS my_num) X