如何为下面的结果编写sql查询:
我有下表:
Amount Date Code
100 01-11-2014 USD
200 02-11-2014 USD
200 02-11-2014 INR
NULL 03-11-2014 NULL
NULL 04-11-2014 NULL
200 05-11-2014 INR
NULL 06-11-2014 NULL
NULL 07-11-2014 NULL
200 08-11-2014 USD
我需要以下结果:
如果给定日期的金额为NULL,则需要将两个代码的金额显示为零。 对于日期03-11-2014,Amount为NULL,因此在输出中,该日期有两行用于US,一行用于INR,Amount为Zero。
Amount Date Code
100 01-11-2014 USD
200 02-11-2014 USD
200 02-11-2014 INR
0 03-11-2014 USD
0 03-11-2014 INR
0 04-11-2014 USD
0 04-11-2014 INR
200 05-11-2014 INR
0 06-11-2014 INR
0 07-11-2014 INR
200 08-11-2014 USD
答案 0 :(得分:0)
select isnull(Amount,0) as amount, Date, Code
from table
答案 1 :(得分:0)
需要使用CROSS APPLY
将CODES的值作为零,其中Amount为NULL。
SELECT Amount, DATE, code
FROM Table1 WHERE Amount is not NULL
UNION
SELECT 0, DATE , A.Code
FROM Table1
CROSS APPLY ( SELECT distinct Code from Table1 where code is NOT NULL) A
WHERE Amount IS NULL
ORDER By Date
答案 2 :(得分:0)
这是我的方法。枚举code
为NULL
的行。当代码为空且顺序值为1时,则为'USD'
,当为2时,则为'INR'
。以下使用amount
作为amount
和code
缺失数据的指标:
select (case when amount is null then amount else 0 end) as amount,
date,
(case when amount is not null then code
when seqnum = 1 then 'USD'
when seqnum = 2 then 'INR'
end) as code
from (select t1.*,
row_number() over (partition by date, amount order by (select null)) as seqnum
from table1 t1
) t
答案 3 :(得分:0)
以下使用外部申请的查询将为您提供所需内容:
SELECT COALESCE(Amount, 0), t1.Dates,
CASE WHEN t1.Code IS NOT NULL THEN t1.Code
ELSE t2.Code
END As Code
FROM MyTable AS t1
OUTER APPLY (
SELECT Dates, Code, RANK() OVER (ORDER BY t.Dates DESC) AS DatesRank
FROM MyTable AS t
WHERE t1.Code IS NULL AND t.Code IS NOT NULL AND t1.Dates > t.Dates
) t2
Where DatesRank IS NULL OR DatesRank = 1
上述查询背后的基本思想是仅在Code为null时执行OUTER APPLY
。当执行OUTER APPLY
时,我们将“有问题”的记录加入以下所有记录:
'属于同一天'(例如(200,'2014-11-02','USD'),(200,'2014-11-02','INR'), )和
'没有问题'(即代码不为空)和
'是有问题的记录之前的第一个'。
我希望我没有迷惑你! :=)
P.S。即使您的数据中有更多货币案例,上述查询也会有效,例如: (200,'2014-11-02','USD'),(200,'2014-11-02','INR'),(200,'2014-11-02','EUR')。
答案 4 :(得分:0)
我已在SQLFIDDLE中尝试了您的方案,并达到了您所需输出的某些限制:
请查看上面超链接中的输入和所需输出。
select ISNULL(c.Amount,d.Amount),c.MyDate,ISNULL(c.Code,d.Code) from
sample c
left outer join
(
select COALESCE(a.Amount,0) as Amount,
ISNULL(b.mydate,a.MyDate) as Mydate,
ISNULL(a.Code,'USD') as Code
from
sample a
left outer join
(select Amount,MyDate,Code
from sample where Code = 'USD') b
on a.MyDate=b.MyDate
where a.Amount IS NULL
union all
select COALESCE(a.Amount,0) as Amount,
ISNULL(b.mydate,a.MyDate) as Mydate,
ISNULL(a.Code,'INR') as Code
from
sample a
left outer join
(select Amount,MyDate,Code
from sample where Code = 'INR') b
on a.MyDate=b.MyDate
where a.Amount IS NULL) d
on c.Mydate = d.Mydate