Hello group!
I am having a problem with simplying my query...
I would like to get customers' balance info based on how many months
since they opened their accounts. The tricky part here is accounts
starting with '28' are treated differently than other accounts, they
are given 3 months grace period. In other words, for all other
accounts, their month0 balance is the balance of their open_month, and
month1 balance is the balance after the account is opened 1 month, and
so on. But accounts starting with '28' month0 balance would be the
balance after the account is opened 3 months, and month1 balance would
be the balance after the account is opened 4 months, and so on.
My query below works, but since some customers are more than 10 years
old (more than 120 months), my query is endless! Does anyone know a
better way to do the same job? Many thanks!
create table a
(person_id int
,account int
,open_date datetime)
insert into a values(1,200001 ,'11/15/2004')
insert into a values(2,280001 ,'8/20/2004')
create table b
(account int
,balance_date datetime
,balance money)
insert into b values(200001,' 11/30/2004',700)
insert into b values(200001,' 12/31/2004',800)
insert into b values(200001,' 1/31/2005',900)
insert into b values(200001,' 2/28/2005',1000)
insert into b values(280001,' 8/30/2004',7000)
insert into b values(280001,' 9/30/2004',8000)
insert into b values(280001,' 10/31/2004',9000)
insert into b values(280001,' 11/30/2004',10000)
insert into b values(280001,' 12/31/2004',15000)
insert into b values(280001,' 1/31/2005',20000)
insert into b values(280001,' 2/28/2005',30000)
--Ideal output--
person_id acc_no month0_balance month1_balance month2_balance month3_balance
1 2000001 700 800 900 1000
2 2800001 10000 15000 20000 30000
select a.person_id
,a.account
,month0_balance =case
when a.account like '2%' and a.account not like '28%'
then
sum(case datediff(mm, a.open_date, balance_date) when 0
then b.balance else 0 end)
else sum(case datediff(mm, a.open_date, balance_date)
when 3 then b.balance else 0 end)
end
,month1_balance =case
when a.account like '2%' and a.account not like '28%'
then
sum(case datediff(mm, a.open_date, balance_date) when 1
then b.balance else 0 end)
else sum(case datediff(mm, a.open_date, balance_date)
when 4 then b.balance else 0 end)
end
from a as a
join b as b
on a.account=b.acc ount
group by a.person_id, a.account 3 1478
(ro******@gmail .com) writes: My query below works, but since some customers are more than 10 years old (more than 120 months), my query is endless! Does anyone know a better way to do the same job? Many thanks!
Hm, first I read endless as "query runs forever", but now I realize
that you want one column for each month.
That's a dynamic cross-tab, which you cannot to in SQL out-of-box,
since a query always produces a table with a well-defined set of
columns.
You could use dynamic SQL to create the beast; you can read about
dynamic SQL on my web site: http://www.sommarskog.se/dynamic_sql.html.
You may also consider the third-party tool RAC, which is very good
for this sort of things. (They say. I have never used it myself, but
it's a standard recommendation. ) It's at http://www.rac4sql.net/.
Since I first misread your question, I looked at improving the query.
Since this is a simple join, good indexing is probably the best for
performance. But this maybe somewhat more effective:
select a.person_id, a.account,
month0_balance = SUM(CASE datediff(mm, a.open_date, balance_date)
WHEN CASE WHEN a.account LIKE '2%' AND
a.account NOT LIKE '28%'
THEN 0
ELSE 3
END THEN b.balance
ELSE 0
END),
month1_balance = SUM(CASE datediff(mm, a.open_date, balance_date)
WHEN CASE WHEN a.account LIKE '2%' AND
a.account NOT LIKE '28%'
THEN 1
ELSE 4
END THEN b.balance
ELSE 0
END)
from a as a
join b as b on a.account=b.acc ount
group by a.person_id, a.account
(Egads! I have never had a CASE in the WHEN part of a CASE expression
before!)
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se
Books Online for SQL Server SP3 at http://www.microsoft.com/sql/techinf...2000/books.asp
Thanks, Erland!
Sorry for the misleading word 'endless'... And you are right, I've
never had a CASE in the WHEN part of a CASE expression:-)) but it is so
exciting to learn! Thanks again!
On Fri, 18 Mar 2005 23:20:17 +0000 (UTC), Erland Sommarskog wrote: (ro******@gmail .com) writes: My query below works, but since some customers are more than 10 years old (more than 120 months), my query is endless! Does anyone know a better way to do the same job? Many thanks!
Hm, first I read endless as "query runs forever", but now I realize that you want one column for each month.
That's a dynamic cross-tab, which you cannot to in SQL out-of-box, since a query always produces a table with a well-defined set of columns.
I would start with this (perhaps as a view) to collect the monthly balances
and do the 3 month correction for 28s:
select a.person_id, a.account,
sum(b.balance) AS MonthBalance,
'Month' + convert(varchar (),
datediff(mm, a.open_date, balance_date) -
case when a.account LIKE '2%' AND a.account NOT like '28%' then 0
else 3 END)
AS MonthNum
FROM a as a
JOIN b as b on a.account=b.acc ount
GROUP BY a.person_id, a.account,
datediff(mm, a.open_date, balance_date) -
case when a.account LIKE '2%' AND a.account NOT like '28%' then 0
else 3 END
Then I'd put a crosstab tool on the client to consume this. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Stylus Studio |
last post by:
Stylus Studio 6 XML Enterprise Edition Now Integrates with TigerLogic
XDMS XQuery and Native XML Database
Bedford, MA, -- Stylus Studio ( http://www.stylusstudio.com ), the
industry-leading provider of XML development tools for advanced XML
data integration, and Raining Data Corporation (NASDAQ: RDTA), a
leading provider of reliable data management solutions, today announced
a new partnership to accelerate and make easier development of...
|
by: Stylus Studio |
last post by:
DataDirect XQuery(TM) is the First Embeddable Component for XQuery That
is Modeled after the XQuery API for Java(TM) (XQJ)
BEDFORD, Mass.--Sept. 20, 2005--DataDirect Technologies
(http://www.datadirect.com), the software industry leader in
standards-based components for connecting applications to data and an
operating unit of Progress Software Corporation, today announced the
release of DataDirect XQuery(TM), the first embeddable...
|
by: Herr Lukas |
last post by:
hello
I'm from germany
- 1 form bounded at 1 tableI with IDaqi and IDarbG, ok, it' works.
- the form is kind endless, not surprising
- in the detail-section I want to built 1 listbox
its rowsource type query with select * from query23
where IDaqi=aqiID
(the main-key from query23 its tableII and tableIII)
|
by: Skybuck Flying |
last post by:
I was just trying to figure out how some C code worked... I needed to make a
loop to test all possible values for a 16 bit word.
Surprise Surprise... C sucks at it... once again :D lol... C is such a bad
language it amazes me everytime :D
Just look at this shit:
unsigned short int i;
|
by: Claudio Grondi |
last post by:
In the process of learning about some deeper details of Python I am
curious if it is possible to write a 'prefix' code assigning to a and b
something special, so, that Python gets trapped in an endless loop in a
line with:
if a==b: print 'OK'
I mean, it would be of much help to me on my way to understanding Python
to know how such prefix code leading to an endless loop can look like
and if it is eventually not possible to write such...
| |
by: Bob Bedford |
last post by:
hello
I'm looking for some functions or objects allowing to
select-insert-update-delete from any table in a mysql database without the
need to create a new query every time. Example:
selectdatas(array('field1','field2','fieldn'),array('table1','tablen'),array('left
join,idy','inner join, idx'))
then the function build the query, execute it and then return an object with
|
by: steve728 |
last post by:
My current employer has MANY graphically created NESTED JOIN queries. They drive me crazy with their complexities and normally have duplications. Is there a a reference some place on-line or a textbook that will serve as a good help in re-constructing them into a more straight-forward simpler format.
I would just like to have a reference showing the typical way to simplify the complex query designer results.
I found the following posting...
|
by: Jon Skeet [C# MVP] |
last post by:
On Sep 9, 9:41 am, raylopez99 <raylope...@yahoo.comwrote:
It's tricky in .NET for two reasons:
1) LINQ doesn't have any concept of "remove"
2) List<T>.RemoveAll doesn't pass in the index (which makes sense as
it would then need to
If List<Tsupported some sort of "view" which also exposed RemoveAll,
it would be easy:
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |