DECLARE @run_date DATETIME
SELECT @run_date = '2016/05/30'
SELECT PAYMENT_LINE.active,
PAYMENT_LINE.alloc_date,
PAYMENT_LINE.allocation_ind,
PAYMENT_LINE.amount,
PAYMENT_LINE.fund_charge_id,
PAYMENT_LINE.paid_td,
PAYMENT_LINE.payment_id,
PAYMENT_LINE.payment_line_id,
PAYMENT_LINE.payment_type_code,
PAYMENT_LINE.period,
PAYMENT_LINE.reference_id,
PAYMENT_LINE.reversal_date,
PAYMENT_LINE.src_id
INTO #pym
FROM PAYMENT_LINE
WHERE alloc_date IS NOT NULL
AND alloc_date < @run_date
/*DELETE FROM #pym WHERE reversal_date IS NULL*/
DELETE
FROM #pym
WHERE reversal_date > @run_date
SELECT payment_id,
Total = SUM(amount)
INTO #pym1
FROM #pym
GROUP BY
payment_id
SELECT PAYMENT.payment_id,
PAYMENT.payment_amount,
Total
INTO #pym2
FROM #pym1,
PAYMENT
WHERE PAYMENT.payment_id = #pym1.payment_id
GROUP BY
PAYMENT.payment_id
HAVING Total > PAYMENT.payment_amount
SELECT MANUFACTURER.manufacturer_id,
MANUFACTURER.manufacturer_name,
alloc_date,
PAYMENT.payment_id,
PAYMENT.payment_amount,
Total
INTO #pym3
FROM #pym2,
PAYMENT,
MANUFACTURER,
PAYMENT_LINE
WHERE Total > PAYMENT.payment_amount
SELECT payment_id,
Total_payment = SUM(payment_amount - Total)
INTO #pym4
FROM #pym3
GROUP BY
payment_id
SELECT MANUFACTURER.manufacturer_id,
MANUFACTURER.manufacturer_name,
alloc_date,
PAYMENT.payment_id,
PAYMENT.payment_amount,
Total,
Total_payment
FROM #pym4,
#pym2,
PAYMENT,
MANUFACTURER,
PAYMENT_LINE
答案 0 :(得分:1)
我已经看了一下这个查询,如果没有更多的信息,它真的没有多大意义。前三个查询;
SELECT PAYMENT_LINE.active,
PAYMENT_LINE.alloc_date,
PAYMENT_LINE.allocation_ind,
PAYMENT_LINE.amount,
PAYMENT_LINE.fund_charge_id,
PAYMENT_LINE.paid_td,
PAYMENT_LINE.payment_id,
PAYMENT_LINE.payment_line_id,
PAYMENT_LINE.payment_type_code,
PAYMENT_LINE.period,
PAYMENT_LINE.reference_id,
PAYMENT_LINE.reversal_date,
PAYMENT_LINE.src_id
INTO #pym
FROM PAYMENT_LINE
WHERE alloc_date IS NOT NULL
AND alloc_date < @run_date
DELETE
FROM #pym
WHERE reversal_date > @run_date
SELECT payment_id,
Total = SUM(amount)
INTO #pym1
FROM #pym
GROUP BY
payment_id
可以全部合并到此;
SELECT payment_id,
Total = SUM(amount)
INTO #pym
FROM PAYMENT_LINE
WHERE alloc_date IS NOT NULL
AND alloc_date < @run_date
AND reversal_date <= @run_date
GROUP BY payment_id
你真的需要阅读正确的连接语法,你在这里使用了非常古老的语法;
SELECT PAYMENT.payment_id,
PAYMENT.payment_amount,
Total
INTO #pym2
FROM #pym1,
PAYMENT
WHERE PAYMENT.payment_id = #pym1.payment_id
GROUP BY
PAYMENT.payment_id
HAVING Total > PAYMENT.payment_amount
请阅读Aaron Bertrand的文章
你还需要注意笛卡尔连接及其所需要的内容,你的最终查询会以多种方式搞乱你的数据;
SELECT MANUFACTURER.manufacturer_id,
MANUFACTURER.manufacturer_name,
alloc_date,
PAYMENT.payment_id,
PAYMENT.payment_amount,
Total,
Total_payment
FROM #pym4,
#pym2,
PAYMENT,
MANUFACTURER,
PAYMENT_LINE
您还应该阅读使用表别名,这些将使您的角色在长期内变得更加简单;
我认为你需要重温你正在尝试做的事情,并问自己你所使用的临时表逻辑是否必要。对我来说,看起来你的数据将会变得非常混乱。考虑是否可以将所有这些都放入一个查询中,每个部分都是您加入的子选择,以便检索所需的数据;
http://www.techrepublic.com/article/use-sql-subselects-to-consolidate-queries/