473,748 Members | 10,058 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Complex query (compare records in same table / join a 2nd table)

19 New Member
Question for all you SQL gurus out there. I have a (seemingly) complex query to write, and since
I'm just learning SQL server, am not sure how to go about it.

Tables:
t_trans
t_account

All tables are bound by an SSN column ("SSN").

t_trans has the bulk of the data I need, and includes the following data:
ssn, trans_date, trans_amount, trans_code
111-11-1111, 8/9/1999, $350.00, 10
111-11-1111, 12/31/1999, $25.00, 30

t_account has the following data:
ssn, close_date
111-11-1111, 8/20/1999

I need a query to pull records from t_trans using the following criteria:

1. Show all t_trans records that are trans_code 30, ONLY if the 30 occurs after a 10,
2. Trans code 30 must include positive dollars,
3. Trans code 30 trans_date must be greater than the close_date from t_account

I'm having trouble doing this since criteria 1 above is comparing records in the same table. In other words, if there's a single SSN with four t_trans entries, one 10 and three 30's, only the 30's will show, and only if those 30's have positive dollars, and only if those 30's have trans_dates that occur after the account close date.

I'm so confuzzled :(
Jan 3 '08 #1
5 3413
camel
55 New Member
Going to have a stab at this off top of head, but no warranties implied !

The main problem is the "must be a 10 before the 30 issue". I would get round that basically as below, by putting all the records of possible interest in a temp table with an auto generated Row ID. You can then use this Row ID to identify the records that meet the "10 followed by 30 rule" as below.

So, put your t_trans records in a temp table. Note I have just written "etc", you need to define all the columns of interest in temp table and ins statement

CREATE TABLE #Transactions (RowID int IDENTITY(1,1), SSN etc)
INSERT #Transactions(S SN etc)
SELECT SSN etc
FROM t_trans -- Probably want to limit rows added by trans_date

Now you should find something like the following picks out records you want

SELECT T *
FROM #Transactions T
JOIN ( SELECT RowID, SSN
FROM #Transactions
WHERE trans_code = 10) AS D
ON T.SSN = D.SSN
AND (T.RowID - 1) = D.RowID -- This is the key SARG to handle the rule
JOIN t_account A
ON T.SSN = A.SSN
WHERE T.trans_Code = 30
AND T.trans_date > A.close_date
AND T.trans_amount > 0
Jan 3 '08 #2
binky
19 New Member
The records I have to sort through in t_trans total over 15 million. I need to sorth through ALL those records to find the trans_code 10 and 30's, and those alone total over 6 million.

I'm hesitant to use a temp table for that since I'm not sure how much resources it will use.
Jan 3 '08 #3
binky
19 New Member
Well I was able to whittle it down to about 36,000 records to review, and it seems to be working. Thanks for your help :)
Jan 3 '08 #4
camel
55 New Member
You are right, its not an option to use a temp table with this many records. Is it possible to add an identity column to the main table itself ? Without a RowID style column or a timestamp on each row I don't know any way you can use a check on value of previous record within a set based statement in the way your requirement implies is needed (and as I have illustrated). If not you have to use a cursor based approach that really will annihilate performance.

Perhaps you could mediate the performance hit by working through several subsets of rows, be that by vertically partitioning the main table or using queries targeted by trans_date. Resource wise you are going to have serious issues going after so many rows in memory in a non-set based fashion

I really wonder why you have so many active records to process ? To carry out a report of this nature on so many records sounds more like a data warehouse scenario where of course you can optimise by building a cube to suit the kind of question you need to ask. Does not strike me you would want this overhead on a production server supporting running applications at the same time....
Jan 3 '08 #5
camel
55 New Member
Missed your previous post reporting some success whilst responding your reply worrying over number of records ! Glad the original reply was helpful and you know have some more ideas for approaching the problem in the future perhaps.
Jan 3 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1944
by: Tom Cunningham | last post by:
OK, say you're trying to find all the non-exact duplicates in a table, and especially do it with a single query, so that the check can be part of a user interface. Then naturally you're going to have a slow query, because it has to compare every row with every other row. You ought to be able to cut out exactly half of the records in the second table, by just saying:
0
1610
by: Dave | last post by:
Hi all, I have a problem with a query. (well, I actually have a few problems...) Here is my query. select FOCUS.SiteName, FOCUS.URL, OTWAdCars.* , REGION.SiteName as RegionSite, REGION.URL as RegionUrl from OTWSite as FOCUS right join OTWSite as REGION
9
3136
by: netpurpose | last post by:
I need to extract data from this table to find the lowest prices of each product as of today. The product will be listed/grouped by the name only, discarding the product code - I use SUBSTRING(ProductName, 1, CHARINDEX('(', ProductName)-2). I can get this result, but I had to use several views (totally inefficient). I think this can be done in one efficient/fast query, but I can't think of one. In the case that one query is not...
6
8164
by: Sven Pran | last post by:
Probably the answer is there just in front of me only awaiting me to discover it, but: 1: I want to build a query that returns all records in one table for which there is no successful "join" in another table but I have not found what the field criteria should look like? 2: And if/when I succeed I should further like to build a new record (with
4
1542
by: bhargav.desai | last post by:
Hello Gurus, I need help! I have two table, tblCurrent and tblPrevious. What I want to join the tables, and create a new table that have matching records from both the tables, plus this new table also includes records from tblcurrent that were are not in the tblprevious and also records from tblprevious that are not in tblcurrent! How can I accomplish this in one query? or Can I?
9
2860
by: MLH | last post by:
I have a table (tblCorrespondence) holding records with fields like , , , , , , , etc... About a dozen 's are defined and I often use queries to extract records of a given . That's pretty easy. But, recently, I wanted to list all "15" letters, a few of the above mentioned fields and one additional field: of nother letter "00" in the same row. That's the tough part.
2
2395
by: Fendi Baba | last post by:
I created a person table with various fields such as Suffix, Salutation, etc, Some of these fields may not be mandatory for example suffix. In the actual table itself, I only have a field for suffix ID where 1=Phd, 2= MD. To display all of these to the user, I created a form with an underlying query. The problem I am encountering is this, when we have an empty field, for example where ID="", the query returns nothing. How do i work around...
9
2051
by: jardar.maatje | last post by:
I am logging scientific data. For this a normal relationship database is not idéal but I am going to try it. I have basically three tables like: datarecord: * idx - integer * time - datetime * type - integer
5
3530
by: Wired Hosting News | last post by:
I tried to be breif and give a scenario so as not to be overlooked because it was soooo long. Let me give you real world. I am a manufacturer of goods and produce 11 items that are distributed to 1800 stores of a national home improvement chain store. Every week I electronicaly receive an excel spreadsheet "inventory report" with 19,800 rows or records, which I import into my tblSalesData table. The table now has 10 weeks of data or...
0
8823
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,...
0
9363
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
9312
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9238
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6793
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
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3300
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
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
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.