SQL查询不能得到期望的输出

问题描述:

当我使用此查询,SQL查询不能得到期望的输出

select 
    receipt_num, trx_num, 
    (case when receipt_amount > 5000 then '1' else 'null') as stamp_value,receipt_amount 
from ra_customer_all where receipt_amount > 5000; 

它给输出LIK这样的:

receipt_num    trx_num   stamp_value  receipt_amount 
    23679    sf35fd     1    5400 
    23679    sdf2424    1    5400 
    23679    rer434     1    5400 
    987444    dgd343     1    98432 
    7610    sdf23     1    6756 
    7610    dfg242     1    6756 

但我想输出看起来像这样:

receipt_num  trx_num  stamp_value  receipt_amount 
    23679   sf35fd    1     5400 
    23679   sdf2424   null    5400 
    23679   rer434    null    5400 
987444   dgd343    1     98432 
    7610   sdf23    1     6756 
    7610   dfg242    null    6756 

如果每张收据num> 5000,邮票值只应打印一次。

(*单个收据可能包含一个或多个trx_num *)

请帮我这个。

select 
acra.attribute6 office_code, 
acra.attribute5 collection_number, 
acra.receipt_number instrument_number, 
acra.receipt_date collection_date, 
acra.amount collected_amount, 
ac.customer_name, 
rcta.trx_number , 
(case row_number() over (partition by acra.receipt_number order by rcta.trx_number) when acra.amount > 5000 then '1' else 'NULL' end) stamp_value, 
from 
ar_cash_receipts_all acra, 
ar_customers ac, 
ra_customer_trx_all rcta, 
ar_receivable_applications_all araa 
where 
acra.pay_from_customer=ac.customer_id and 
acra.cash_receipt_id = araa.cash_receipt_id and 
araa.applied_customer_trx_id=rcta.customer_trx_id 
and acra.amount > 5000 

好吧,我更新我的加盟,我通过添加分区,但给人错误失踪keyword.Can人编辑此为所需的输出

+0

:请还发布receipt_amount值。 – 2012-07-06 10:09:05

+0

我添加了收据金额。 – sat33man 2012-07-06 10:13:29

+0

但是'receipt_amount'的所有值都大于5000.还有什么其他的你可能会在'receipt_amount'列中尝试一个小于5000的值。 – 2012-07-06 10:21:35

所以你想stamp_value为1组的第一行和NULL为所有后续行?使用PARTITION BY:

select 
    receipt_num, trx_num, 
    (case row_number() over (partition by receipt_num order by trx_num) 
    when 1 then 1 
    else NULL 
    end) stamp_value, 
    receipt_amount 
from ra_customer_all 
where receipt_amount > 5000 

这将设置stamp_value为1的第一行(使用trx_num排序)和NULL对于所有后续行。

+0

你可以说如何使用它加入conditon喜欢receipt_num X,trx_num Y. – sat33man 2012-07-06 10:50:17

+0

只需像往常一样添加where子句(我更新了我的帖子)。但是,这并不会更改您提供的数据的值,因为所有receipt_amount值都大于5000. – 2012-07-06 11:04:07

+0

我使用我的连接查询更新了我的文章。 – sat33man 2012-07-06 11:20:25

可以通过同时包括在你的SELECT语句receipt_amount开始查询检查目的?这可能是因为您对receipt_amount的期望不正确,并且脚本的行为正确。

此外,您的null不应该在case语句中使用单引号,您将在结果集中获得一个字符串,而不是null值,正如您所期望的那样。

+0

什么都没有:你可以发表评论,这可能不是这个答案这就是为什么 – 2012-07-06 10:11:28

+0

我补充amount.I认为现在我的问题是clear.can有人给了我一个主意。 – sat33man 2012-07-06 10:18:34

试试这个

select receipt_num,trx_num, result= 
case when receipt_amount >500 then 1 else null end,receipt_amount from ra_customer_all 

演示 http://sqlfiddle.com/#!3/f29a6/1

http://sqlfiddle.com/#!3/f29a6/2