假设我有一张包含以下数据的表
客户表:
Name amount date_created invoice_number
--------------------------------------------------
John 50 11April2012 12
Bob 150 15April2012 32
David 506 10May2012 52
Paul 80 12Aug2012 12
Mark 10 11Jan2012 52
汇总表:
Name amount
---------------------
Sally 250
Darren-32 150
我想选择date_created位于current_quarter的start_date和end_date之间的所有行。如果date_created在当前季度内,我想在执行insert语句之前将invoice_number附加到名称(请参阅上面的摘要表中的示例)。
INSERT summary(name, amount)
SELECT name|| '-' || invoice_number, date_created, invoice_number
From Customer;
如何修改上述内容以使用“解码”功能或“大小写”功能(或任何其他“IF语句”类型函数)来检查date_created的值,如果date_created在date_created内,则附加invoice_number本季度。
显然我需要知道当前季度的开始和结束日期,并且需要在进行比较之前将它们存储在某处。纯SQL可以实现这一点吗? PL / SQL不是一个选项。
假设我们在Q1(4月 - 6月),最终结果应为:
Name amount
---------------------
Sally 250
Darren-32 150
John-12 50
Bob-32 150
David-52 506
Paul 80
Mark 10
我正在从Oracle 10G数据库中读取Customer表,并将摘要填充到驻留在SQL Server数据库中的“Summary”表中。我插入SQL Server数据库的事实应该不重要。我正在从Oracle数据库中读取数据,因此语法应该与Oracle兼容。
答案 0 :(得分:1)
declare @CurrentQtr int
set @CurrentQty = CASE
WHEN datepart(month, getdate()) in (1,2,3) THEN 1
WHEN datepart(month, getdate()) in (4,5,6) THEN 2
WHEN datepart(month, getdate()) in (7,8,9) THEN 3
ELSE 4 END
SELECT name + case
WHEN datepart(month, date_created) in (1,2,3) AND @CurrentQtr = 1 THEN '-' + invoice_number
WHEN datepart(month, date_created) in (4,5,6) AND @CurrentQtr = 2 THEN '-' + invoice_number
WHEN datepart(month, date_created) in (7,8,9) AND @CurrentQtr = 3 THEN '-' + invoice_number
WHEN datepart(month, date_created) in (10,11,12) AND @CurrentQtr = 4 THEN '-' + invoice_number
ELSE '' end as Name, amount
From Customer;
答案 1 :(得分:1)
执行您在两个要点中描述的内容的Oracle语法将是
SELECT (CASE WHEN date_created >= trunc(sysdate,'Q')
AND date_created < trunc(add_months(sysdate,3),'Q')
THEN name || '-' || invoice_number
ELSE name
END),
date_created,
invoice_number
FROM Customer;
答案 2 :(得分:1)
这样的东西?
insert summary
Select
Name || case
when datepart(dp_quarter, sysdate)=datepart(dp_quarter, date_Created)
and extract(year from sysdate) = extract(year from date_Created)
then '-' || invoice_number
else '' end,
amount from Customer