473,698 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_typ e
='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_A mount / Totals.total_Am ount) 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 2230
select date,
user,
sum(case when transaction_typ e ='debit' then amount else 0 end)
/
sum(amount) as perc_Debit
from mytable
group by date, user

Dec 18 '06 #2
is*********@hot mail.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_typ e 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******@hotmai l.com wrote:
select date,
user,
sum(case when transaction_typ e ='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******@hotmai l.com wrote:
select date,
user,
sum(case when transaction_typ e ='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******@hotmai l.com wrote:
select date,
user,
sum(case when transaction_typ e ='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_typ e || amount

MarkC gave me this:-
----
select date,
user,
sum(case when transaction_typ e ='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_typ e,
sum(
case
when transaction_typ e ='debit' then amount else
when transaction_typ e ='credit' then amount else
when transaction_typ e ='...' 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_typ e,
sum(
case
when transaction_typ e
IN (SELECT DISTINCT transactionType ID FROM Transaction_Lis t) 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_typ es 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******@hotmai l.com wrote:
>
select date,
user,
sum(case when transaction_typ e ='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*********@ho tmail.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_typ e || amount

MarkC gave me this:-
----
select date,
user,
sum(case when transaction_typ e ='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_typ e,
100 * SUM(amount) / SUM(amount) OVER (PARTITION BY date, user)
FROM mytable
GROUP BY date, user, transaction_typ e

On SQL 2000 you could maybe do:

SELECT a.date, a.user, a.transaction_t ype, 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_t ype, 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****@sommarsk og.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
6546
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 Workshop program: hcw.exe that's included with Visual Basic. This exact same file compiled perfectly with no notes, warnings or errors prior to reformatting my system. Prior to the reformatting, I copied the help.rtf file onto a CD and checked the box to...
9
4401
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 the microsoft HTML workshop utility, lets call it c:\path\help.chm. My question is how do you launch it from the GUI? What logic do I put behind the "help" button, in other words. I thought it would be os.spawnv(os.P_DETACH,...
4
3350
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 cmd.Cmd but I would also like to get the man-page-like help for classes and functions. Does anyone know how to do that? Thanks. Sarir
3
3357
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 numarray, help gives unhelpful responses:
7
5375
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 from clicking on many of the available topics (mostly methods but some properties are also unavailable). This same problem occurs with many, if not most, keywords. Is there any way I can activate these "missing" help topics? HELP!
5
3266
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 using "F1" help within the VB IDE. Is this expectation achievable In trying to test my help file in the IDE, I have a solution with 2 projects: the DLL and a tester. VB does not look for my help file; instead, it looks for path to my source code...
8
3226
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 including search the internet for help, but the help is worthless. Any ideas?
10
3359
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 the worst I ever seen. I almost cannot find anything I need, including things I
1
6127
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 default property of object Label. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' Label = New Object(){Box1, Box2, Box3, Box4, Box5, Box6, Box7, Box8, Box9, Box10, Box11,...
0
2883
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 calls MS Excel, so the scenario is that I am supposed to see the Excel Menu bar, FILE EDIT VIEW INSERT ... HELP. I am able to see the menu bar, but in case of Help, I see the Help of Excel and help of my application, both as a submenu of help. ...
0
8675
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, 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...
0
9029
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6521
isladogs
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...
0
5860
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();...
0
4370
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...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3050
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
2
2331
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2002
bsmnconsultancy
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...

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.