473,386 Members | 1,785 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Help!? Combining SQL Queries? Can it be done??

Hi All,

I have a problem with a table that I want to get nice data out of in a
single query. The guys here reckon it can't be done in a single query
but I wanted to prove them wrong !! Essentially, I want to get the same
column out of the single table, but in one case the column must have a
where clause associated with it, and the other case it does not have a
where clause...

Lets say have a table like this :-

date || user || transaction type || Amount

so, each row contains a transaction type, and a corresponding amount
for this transaction.

There can be any number of transactions (and transaction types) per
user per day.

Here is what I want :

I want to get one particular transaction type as a percentage of the
total transactions : for example, a list of the % amount that Debit
transactions have occurred for a user for a day, with respect to all
transactions that the user has done that day, so :

Debits Jim performed on day 1 are 50% of all transactions he performed
Debits Jim performed on day 2 are 55% of all transactions he performed
... and so on.

At the moment, I do this :

select date, user, sum(amount) as debit_Amount where transaction_type
='debit'
group by date, user

and dump that into tmp table Debits

then I do

select date, user, sum(amount) as total_Amount
group by date, user

and dump this into tmp table Totals

and then I have to do a :

SELECT Debits.User, (Debits.debit_Amount / Totals.total_Amount) as
perc_Debit , Debits.date
FROM Debits, Totals
WHERE Debits.date = Totals.date AND Debits.User = Totals.User

Can anyone suggest a way of doing this without the need for these
temporary tables???

Thanks!

Dec 18 '06 #1
7 2220
select date,
user,
sum(case when transaction_type ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user

Dec 18 '06 #2
is*********@hotmail.com wrote:
date || user || transaction type || Amount
I hope this table has a primary key, and you just omitted mentioning it
because this particular case doesn't use it.
I want to get one particular transaction type as a percentage of the
total transactions : for example, a list of the % amount that Debit
transactions have occurred for a user for a day, with respect to all
transactions that the user has done that day, so :

Debits Jim performed on day 1 are 50% of all transactions he performed
Debits Jim performed on day 2 are 55% of all transactions he performed
[snip]
Can anyone suggest a way of doing this without the need for these
temporary tables???
Untested:

select date, user,
coalesce(
sum(case transaction_type when 'debit' then amount else 0 end)
, 0
) / sum(amount) as perc_debit
from the_table
group by date, user
Dec 18 '06 #3
ma******@hotmail.com wrote:
select date,
user,
sum(case when transaction_type ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user
You're right, I guess coalesce() isn't needed. (It would have been
needed in the temp-tables approach, if you wanted to pick up date/user
combinations with 0% debits.)
Dec 18 '06 #4
Thanks Guys,

I will give this a go. Is this T-SQL / pl-SQL or is this a technique
used only on SQL Server ?

Yes, Ed, there's primary keys, indices, etc etc on this table. Just
wanted to post the bare bones of the problem, rather than labour you
with all the other details..

cheers,

Scripty.
Ed Murphy wrote:
ma******@hotmail.com wrote:
select date,
user,
sum(case when transaction_type ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user

You're right, I guess coalesce() isn't needed. (It would have been
needed in the temp-tables approach, if you wanted to pick up date/user
combinations with 0% debits.)
Dec 18 '06 #5
Just a quick note:

this nested "case when" works in MSSQL Server. It it better than the
temporary table approach not only as it is faster, but also because it
picks up dates where zero debits occur, as well as days when they do.
My original temporary table approach only picks out dates that match
from both initial queries.
I must read up on using 'case when....' in statements.

Thanks again

S
Scripty wrote:
Thanks Guys,

I will give this a go. Is this T-SQL / pl-SQL or is this a technique
used only on SQL Server ?

Yes, Ed, there's primary keys, indices, etc etc on this table. Just
wanted to post the bare bones of the problem, rather than labour you
with all the other details..

cheers,

Scripty.
Ed Murphy wrote:
ma******@hotmail.com wrote:
select date,
user,
sum(case when transaction_type ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user
You're right, I guess coalesce() isn't needed. (It would have been
needed in the temp-tables approach, if you wanted to pick up date/user
combinations with 0% debits.)
Dec 18 '06 #6
Ok, So here is the next question:

What if I want a view of every transaction type, with a corresponding
figure of the overall transaction value, per row in the query ?

just for the record, the transact table looks like this:

date|| userID || transaction_type || amount

MarkC gave me this:-
----
select date,
user,
sum(case when transaction_type ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user
----

Which is great for creating a table of stats for each user's 'debit'
transactions:

date || User1 || 60% Debit transactions ||

So now lets say I want this instead:

date1 || User1 || Debit || 60%
date1 || User1 || Credit || 35%
date1 || User1 || Enquiry || 5%

So we could go for something like this :
--
select date,
user,
transaction_type,
sum(
case
when transaction_type ='debit' then amount else
when transaction_type ='credit' then amount else
when transaction_type ='...' then amount else
....
0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user
---

But! that is no good because in the particular application we have
(Don't ask) we cannot be sure of all transaction types, indeed, new
ones can be added all the time. The actual table I'm dealing with is
normalised as well (I'm leaving out the exact details here because I
don't want to swamp people with schemas / ER diagrams that aren't
entirely relevant). So I really need something like:

--- DOES NOT WORK ---
select date,
user,
transaction_type,
sum(
case
when transaction_type
IN (SELECT DISTINCT transactionTypeID FROM Transaction_List) then
amount
else
0
end)
/
sum(amount) as perc_Item
from mytable
group by date, user

--- DOES NOT WORK ---

Thats not going to work is it?? Is there some sort of foreach statement
I can run here or should I be building up a table by running the first
query many times , once for each transaction type?

Any ideas on the new problem?? If not I think I'll create stored proc
that I can run on (say) the top 5 transaction_types per day per
user...

Scripty wrote:
Just a quick note:

this nested "case when" works in MSSQL Server. It it better than the
temporary table approach not only as it is faster, but also because it
picks up dates where zero debits occur, as well as days when they do.
My original temporary table approach only picks out dates that match
from both initial queries.
I must read up on using 'case when....' in statements.

Thanks again

S
Scripty wrote:
Thanks Guys,

I will give this a go. Is this T-SQL / pl-SQL or is this a technique
used only on SQL Server ?

Yes, Ed, there's primary keys, indices, etc etc on this table. Just
wanted to post the bare bones of the problem, rather than labour you
with all the other details..

cheers,

Scripty.
Ed Murphy wrote:
ma******@hotmail.com wrote:
>
select date,
user,
sum(case when transaction_type ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user
>
You're right, I guess coalesce() isn't needed. (It would have been
needed in the temp-tables approach, if you wanted to pick up date/user
combinations with 0% debits.)
Dec 19 '06 #7
Scripty (is*********@hotmail.com) writes:
What if I want a view of every transaction type, with a corresponding
figure of the overall transaction value, per row in the query ?

just for the record, the transact table looks like this:

date|| userID || transaction_type || amount

MarkC gave me this:-
----
select date,
user,
sum(case when transaction_type ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user
----

Which is great for creating a table of stats for each user's 'debit'
transactions:

date || User1 || 60% Debit transactions ||

So now lets say I want this instead:

date1 || User1 || Debit || 60%
date1 || User1 || Credit || 35%
date1 || User1 || Enquiry || 5%

I think this would work on SQL 2005:

SELECT date, user, transaction_type,
100 * SUM(amount) / SUM(amount) OVER (PARTITION BY date, user)
FROM mytable
GROUP BY date, user, transaction_type

On SQL 2000 you could maybe do:

SELECT a.date, a.user, a.transaction_type, 100 * SUM(a.amount) / b.amt
FROM mytable a
JOIN (SELECT date, user, SUM(amount)
FROM mytable
GROUP BY date, user) AS b ON a.user = b.user
AND a.date = b.date
GROUP BY a.date, a.user, a.transaction_type, b.amt

Both these solutions are untested, since you did not include CREATE
TABLE statements, INSERT statements with sample data, and the desired
result from the sample.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Dec 19 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Dave | last post by:
After following Microsofts admonition to reformat my system before doing a final compilation of my app I got many warnings/errors upon compiling an rtf file created in word. I used the Help...
9
by: Tom | last post by:
A question for gui application programmers. . . I 've got some GUI programs, written in Python/wxPython, and I've got a help button and a help menu item. Also, I've got a compiled file made with...
4
by: Sarir Khamsi | last post by:
Is there a way to get help the way you get it from the Python interpreter (eg, 'help(dir)' gives help on the 'dir' command) in the module cmd.Cmd? I know how to add commands and help text to...
3
by: Colin J. Williams | last post by:
Python advertises some basic service: C:\Python24>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> With...
7
by: Corepaul | last post by:
Missing Help Files When I enter "recordset" as the keyword and search the Visual Basic Help index, I get many topics of interest in the resulting list. But there isn't any information available...
5
by: Steve | last post by:
I have written a help file (chm) for a DLL and referenced it using Help.ShowHelp My expectation is that a developer using my DLL would be able to access this help file during his development time...
8
by: Mark | last post by:
I have loaded Visual Studio .net on my home computer and my laptop, but my home computer has an abbreviated help screen not 2% of the help on my laptop. All the settings look the same on both...
10
by: JonathanOrlev | last post by:
Hello everybody, I wrote this comment in another message of mine, but decided to post it again as a standalone message. I think that Microsoft's Office 2003 help system is horrible, probably...
1
by: trunxnirvana007 | last post by:
'UPGRADE_WARNING: Array has a new behavior. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' 'UPGRADE_WARNING: Couldn't resolve...
0
by: hitencontractor | last post by:
I am working on .NET Version 2003 making an SDI application that calls MS Excel 2003. I added a menu item called "MyApp Help" in the end of the menu bar to show Help-> About. The application...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
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,...
0
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...
0
Oralloy
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.