Showing posts with label queries. Show all posts
Showing posts with label queries. Show all posts

Wednesday, March 28, 2012

Need to access SQL Server 2000 tables

Hello,

I am trying to write a java program that will connect to a SQL Server DB, run some queries, pull some data and try to find some trends in the data.

The problem is that I have a copy of the Database, but I don't have SQL Server. I have been given a backup copy of the database though (SQL Server 2000). I know that in addition to the JDBC driver for SQL Server 2000 I will need something else to be able to access the DB. They have stopped selling SQL Server 2000, also the software tends to be a little expensive.

Is there anything else that I can use that will allow me the functionality of being able to run queries and pull data from the DB using JDBC? Will installing MSDE allow me to do that? Or is there someother software that will allow me to do that? Or do I have no other option except installing SQL Server 2000?

Any help is greatly appreciated.

ThanksHi there,

Will you only be accessing the database for the purposes of reporting (i.e. you won't be changing data and then merging these changes into a master database from which the backup was taken)?

What I would recommend is that you don't use MSDE but you use SQL Server 2005 Express Edition. You can download it here:

Download SQL Server 2005 Express

NB. The download could be quite hefty as you might need to download the .NET Framework 2.0, SQL Server 2005 Express Edition database engine and the Management Studio.

You are able to restore SQL Server 2000 database backups to SQL Server 2005 so what you would do is:

1) Install SQL Server 2005 Express & Management Studio Express (see previous link)

2) Use Management Studio Express to restore the SQL Server 2000 backup (you can do this by creating a new database and then restoring your backup over the top)

3) Download and install the JDBC driver for SQL Server 2005 here:
Download JDBC Driver

4) Write your Java program as required

Well, OK, you don't have to use the JDBC driver as you could also use the JDBC-ODBC bridge which already comes with Java but I'd recommend you use the JDBC driver.

Hope that helps a bit, but sorry if it doesn't

|||Thanks a lot NateV,

I will be using the DB for reporting purposes. I won't be chaning any data on the backend ( no inserts or updates, just selects). I am going to try using SQL Server Express 05 and let you know if it worked.

Thanks Again

Monday, March 26, 2012

Need suggestion on TSql Query with Joins

Hi All,

Please suggest me is there any performance/other differences between the below two queries.

-query1

select T1.name,T1.Number, T2.Dept, T2.Desig

From T1 Inner Join T2 on T1.EID = T2.EID

-query2

select T1.name,T1.Number, T2.Dept, T2.Desig

From T1 Inner Join (Select Dept, Desig From T2) As T2 on T1.EID = T2.EID

Thanks

Senthil

There is no performance difference for your quires.

Both are executed in same way..

Suppose, if your query2, subquery has any distinct or group by clause then the query1 may perform better than query2.

|||Thanks Sekaran!

Friday, March 23, 2012

Need SQL Performance Advice (Scenario Given)

Hey guys, having a bit of a urgency here. I need to make certain queries faster in our application, lemme give you a scoup. One of the queries i need to optimize or find a better way to do is the current scenario. We have jobs in our system, these jobs have applicants, some of them are direct applicants, some are matches (from searches), and some are applicants with resumes only.
Some of our clients have 100+ jobs, when they see the first page we list all the jobs with 6 counts next to them:

Job Title, Total Applicants, New Applicants, Total Matches, New Matches, Total Resumes, New Resumes

So we have 6 counts for each job, say you have 100+ jobs thats a lot of counts. Currently i'm performing a sub query for each of the counts since they represent different data points, the only thing that changes is the WHERE clause.

As you can see this can be very heavy and in some cases (100+ jobs) depending of number of applicants might take up to a minute to finish.

I would like to get some opinions from you guys on how to make this run faster, obviously caching cannot be considered since they employer must see the live data (counts)

Any help is greatly appreciated.indexes on the join columns?|||yes indexes are in place, i dont really thing that they are the problem,

i think the subqueries are killing it since one query needs to be run to get each of the count right? is there any other way to structure this thing?

thanks for your help|||depends

without seeing the subqueries, it's kinda difficult to tell what's wrong or whether an alternative structure is possible|||Without seeing your code, my first suggestion would be to "unwrap" the subqueries. Make a single pass through the data, doing a single join. Reimplement the counts as sums, and use CASE to provide the "smarts" to make it work.

As Rudy pointed out, without seeing what you are doing, we are pretty sorely limited in how we can help. This is kind of like calling someone on another continent and telling them "my stomach hurts" and asking them what you should do about it.

-PatP

Need some practice

Please point me to a web resource from where I can study:

1) writing complex queries such as those involving HAVING, mult-level
nested queries, GROUP BY, T-SQL functions

2) Joins - a lot of practice

3) Stored Procedures, transactions, cursors and triggers - I need some
heavy-duty practice

Where can I get some good practice of the above? Also, please recommend
a good SQL Server/T-SQL book in the light of the above requirement.Here's a good one for joins. I like the colors for the join tables:

http://www.tek-tips.com/faqs.cfm?fid=4785|||Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
working SQL programmers. And my house payment :)|||> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)

The book is of little use to working SQL programmers, a lot of the examples
aren't directly useable in SQL Server nor do they scale into the real world.

People are better off spending a couple of minutes searching GOOGLE for the
answers.

--
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials

"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1144801857.130733.158410@.i40g2000cwc.googlegr oups.com...
> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)

Need some practice

Please point me to a web resource from where I can study:
1) writing complex queries such as those involving HAVING, mult-level
nested queries, GROUP BY, T-SQL functions
2) Joins - a lot of practice
3) Stored Procedures, transactions, cursors and triggers - I need some
heavy-duty practice
Where can I get some good practice of the above? Also, please recommend
a good SQL Server/T-SQL book in the light of the above requirement.Some basic sites that have a couple examples...
http://www.w3schools.com/sql/sql_intro.asp
http://sqlzoo.net/
http://www.geocities.com/SiliconVal.../2207/sql1.html
If you want more comlicated examples, this forum may be the most useful.
You will have to sort through a lot of different posts that do not have what
you are looking for, but you will find dozens of solutions to various
problems that you can learn from.
"Water Cooler v2" <wtr_clr@.yahoo.com> wrote in message
news:1144682834.749751.324310@.i39g2000cwa.googlegroups.com...
> Please point me to a web resource from where I can study:
> 1) writing complex queries such as those involving HAVING, mult-level
> nested queries, GROUP BY, T-SQL functions
> 2) Joins - a lot of practice
> 3) Stored Procedures, transactions, cursors and triggers - I need some
> heavy-duty practice
>
> Where can I get some good practice of the above? Also, please recommend
> a good SQL Server/T-SQL book in the light of the above requirement.
>|||Here's a good one for joins. I like the colors for the join tables:
http://www.tek-tips.com/faqs.cfm?fid=4785|||Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
working SQL programmers. And my house payment :)|||> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)
The book is of little use to working SQL programmers, a lot of the examples
aren't directly useable in SQL Server nor do they scale into the real world.
People are better off spending a couple of minutes searching GOOGLE for the
answers.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1144801857.130733.158410@.i40g2000cwc.googlegroups.com...
> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)
>

Wednesday, March 21, 2012

Need some help with query

Hi Guys,

I'm working on a SQL problem and am a bit stuck. I'll have to apologize for I'm still very new to this and can't do a lot of complex queries yet. I've attached what I've done so far, thank you in advance for your help.

Given the following relation schemas:

EMPLOYEE(SSN, NAME, SEX, DNUMBER)
DEPARTMENT(DNUMBER, DNAME, DMGRSSN)
DLOCATION(DNUMBER, DLOCATION)
PROJECT(PNUMBER, PNAME, PLOCATION)
WORKSON(SSN, PNUMBER, HOURS)

Write the following queries in SQL:

1. List the name(s) of employee(s) who works(work) on every project located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c.PNUMBER = b. PNUMBER and b.PLOCATION= Houston

2. List the name(s) of employee(s) who only works(work) on every project located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c.PNUMBER=b.PNUMBER and b.PLOCATION in (Houston) and ?

3. List the name(s) of employee(s) who works(work) on every project except the one(s) located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c. PNUMBER=b.PNUMBER and b.PLOCATION not in (Houston)

4. List name(s) of employee(s) who works(work) on exactly all projects located in Houston.

?

Quote:

Originally Posted by alvinguy

Hi Guys,

I'm working on a SQL problem and am a bit stuck. I'll have to apologize for I'm still very new to this and can't do a lot of complex queries yet. I've attached what I've done so far, thank you in advance for your help.

Given the following relation schemas:

EMPLOYEE(SSN, NAME, SEX, DNUMBER)
DEPARTMENT(DNUMBER, DNAME, DMGRSSN)
DLOCATION(DNUMBER, DLOCATION)
PROJECT(PNUMBER, PNAME, PLOCATION)
WORKSON(SSN, PNUMBER, HOURS)

Write the following queries in SQL:

1. List the name(s) of employee(s) who works(work) on every project located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c.PNUMBER = b. PNUMBER and b.PLOCATION= Houston

2. List the name(s) of employee(s) who only works(work) on every project located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c.PNUMBER=b.PNUMBER and b.PLOCATION in (Houston) and ?

3. List the name(s) of employee(s) who works(work) on every project except the one(s) located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c. PNUMBER=b.PNUMBER and b.PLOCATION not in (Houston)

4. List name(s) of employee(s) who works(work) on exactly all projects located in Houston.

?


Try to use joins instead of alias names
sample:
3. List the name(s) of employee(s) who works(work) on every project except the one(s) located in Houston.

SELECT a.NAME from Project b
left join WORKSON c on C.Pnumber=b.Pnumber
left join EMPLOYEE a on a.SSN=c.SSN
WHERE b.PLOCATION !=Houston

2. List the name(s) of employee(s) who only works(work) on every project located in Houston.

select distinct Employee.Name from Project
left join Workson on Workson.PNumber=Project.PNumber
left join Employee on Employee.SSN=Workson.SSN
where Project.PLOcation='Houston'

4. List name(s) of employee(s) who works(work) on exactly all projects located in Houston.

Select Name from Employee where SSN=(Select SSN from
(Select SSN,count(SSN) as cnt from
(select distinct SSN,Workson.PNumber from Project
left join Workson on Workson.Pnumber= Project.PNumber
where Project.PLocation='Houston'
group by SSN,Workson.PNumber) as A
group by SSN) as B
where cnt=(select Count(Pnumber) from Project Where Plocation='Houston'))|||

Quote:

Originally Posted by alvinguy

Hi Guys,

I'm working on a SQL problem and am a bit stuck. I'll have to apologize for I'm still very new to this and can't do a lot of complex queries yet. I've attached what I've done so far, thank you in advance for your help.

Given the following relation schemas:

EMPLOYEE(SSN, NAME, SEX, DNUMBER)
DEPARTMENT(DNUMBER, DNAME, DMGRSSN)
DLOCATION(DNUMBER, DLOCATION)
PROJECT(PNUMBER, PNAME, PLOCATION)
WORKSON(SSN, PNUMBER, HOURS)

Write the following queries in SQL:

1. List the name(s) of employee(s) who works(work) on every project located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c.PNUMBER = b. PNUMBER and b.PLOCATION= Houston

2. List the name(s) of employee(s) who only works(work) on every project located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c.PNUMBER=b.PNUMBER and b.PLOCATION in (Houston) and ?

3. List the name(s) of employee(s) who works(work) on every project except the one(s) located in Houston.

SELECT a.NAME
FROM EMPLOYEE a, PROJECT b, WORKSON c
WHERE a.SSN = c.SSN and c. PNUMBER=b.PNUMBER and b.PLOCATION not in (Houston)

4. List name(s) of employee(s) who works(work) on exactly all projects located in Houston.

?


Hi
Different way for different queries exist.
if u still have problem in 3rd query u can use the following.

SELECT a.NAME
FROM
EMPLOYEE AS a, WORKSON AS b
WHERE a.SSN=b.SSN and b.PNUMBER IN
(SELECT PNUMBER
FROM PROJECT
WHERE PLOCATION NOT IN('HOUSTON'));

IF U STILL HAVE ANY PROBLEM IN ANY OTHER QUERY PLZ TELL I WILL TRY MY BEST TO SOLVE THAT ONE.sql

Monday, March 12, 2012

Need report for current heaviest queries

What tools can I use to get an immediate report of which queries are the
heavist on my sql server? Sometimes it can max for 30-40 seconds and I need
to troubleshoot where the bottleneck it.
All tips and links would be appreciated!
Thanks,
Moshe
You can use a server side trace or Profiler to capture
information on queries such as duration, cpu, reads, writes,
etc. You can use the tool or tracing in different ways but
I'm not sure what you mean by an immediate report - if you
need to see what's hardest on your server you'd need to
monitor this over some period of time. You can save the
trace results to a file and from there you can import them
to a table using fn_trace_gettable and do some analysis,
reporting, etc.
-Sue
On Mon, 6 Mar 2006 14:07:26 -0800, Moshe Rosenberg
<MosheRosenberg@.discussions.microsoft.com> wrote:

>What tools can I use to get an immediate report of which queries are the
>heavist on my sql server? Sometimes it can max for 30-40 seconds and I need
>to troubleshoot where the bottleneck it.
>All tips and links would be appreciated!
>Thanks,
>Moshe

Need report for current heaviest queries

What tools can I use to get an immediate report of which queries are the
heavist on my sql server? Sometimes it can max for 30-40 seconds and I need
to troubleshoot where the bottleneck it.
All tips and links would be appreciated!
Thanks,
MosheYou can use a server side trace or Profiler to capture
information on queries such as duration, cpu, reads, writes,
etc. You can use the tool or tracing in different ways but
I'm not sure what you mean by an immediate report - if you
need to see what's hardest on your server you'd need to
monitor this over some period of time. You can save the
trace results to a file and from there you can import them
to a table using fn_trace_gettable and do some analysis,
reporting, etc.
-Sue
On Mon, 6 Mar 2006 14:07:26 -0800, Moshe Rosenberg
<MosheRosenberg@.discussions.microsoft.com> wrote:

>What tools can I use to get an immediate report of which queries are the
>heavist on my sql server? Sometimes it can max for 30-40 seconds and I need
>to troubleshoot where the bottleneck it.
>All tips and links would be appreciated!
>Thanks,
>Moshe

Need report for current heaviest queries

What tools can I use to get an immediate report of which queries are the
heavist on my sql server? Sometimes it can max for 30-40 seconds and I need
to troubleshoot where the bottleneck it.
All tips and links would be appreciated!
Thanks,
MosheYou can use a server side trace or Profiler to capture
information on queries such as duration, cpu, reads, writes,
etc. You can use the tool or tracing in different ways but
I'm not sure what you mean by an immediate report - if you
need to see what's hardest on your server you'd need to
monitor this over some period of time. You can save the
trace results to a file and from there you can import them
to a table using fn_trace_gettable and do some analysis,
reporting, etc.
-Sue
On Mon, 6 Mar 2006 14:07:26 -0800, Moshe Rosenberg
<MosheRosenberg@.discussions.microsoft.com> wrote:
>What tools can I use to get an immediate report of which queries are the
>heavist on my sql server? Sometimes it can max for 30-40 seconds and I need
>to troubleshoot where the bottleneck it.
>All tips and links would be appreciated!
>Thanks,
>Moshe

Need query optimization help.

(SQL Server 2000, SP4)
Hello all!
I'm seeing a lot of I/O generated by one of our queries, and I think it's
how the query is constructed. Consider the following:
use [tempdb]
go
if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[
;Test]
create table [dbo].[Test]
(
[RowID] uniqueidentifier not NULL,
[Field1] int not NULL,
[Field2] int not NULL,
[Date] datetime not NULL,
primary key clustered ([RowID])
)
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor d
elay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor d
elay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor d
elay
'0:0:1'
insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor d
elay
'0:0:1'
insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor d
elay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor d
elay
'0:0:1'
insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor d
elay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor d
elay
'0:0:1'
select t.*
from [dbo].[Test] as t with (nolock)
select t.*
from [dbo].[Test] as t with (nolock)
inner join (
select [Field1] = t.[Field1],
[Field2] = t.[Field2],
[Date] = max(t.[Date])
from [dbo].[Test] as t with (nolock)
group by t.[Field1],
t.[Field2]
) as q on q.[Field1] = t.[Field1]
and q.[Field2] = t.[Field2]
and q.[Date] = t.[Date]
In essence, I'm trying to find the rows from Test that have the *maximum*
Date for a unique Field1/Field2 combination. This query is used in a VIEW,
and users of this VIEW typically JOIN on RowID.
I'm sure the "guts" of this VIEW can be refactored to be better, but I don't
know how to do it. Any suggestions would be *much* appreciated!
John PetersonWhat about (didnt try that but it should work)
Select * From Test
Inner Join
(
Select Field1,Field2,Max(Date)
From Test
Group by Field1,Field2
) SUbQuery
on
SUbQuery.Field1 = Test.FIeld1 AND
SUbQuery.Field2 = Test.FIeld2 AND
SUbQuery.Date = Test.Date
Its alsways interesting for performance issues to send the execution plan
with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
command and youll get the query execution plan in text displayes, which you
can copy & paste in the newsgroups.
HTH, Jens Suessmeyer.
"John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
> (SQL Server 2000, SP4)
> Hello all!
> I'm seeing a lot of I/O generated by one of our queries, and I think it's
> how the query is constructed. Consider the following:
>
> use [tempdb]
> go
> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].&#
91;Test]
> create table [dbo].[Test]
> (
> [RowID] uniqueidentifier not NULL,
> [Field1] int not NULL,
> [Field2] int not NULL,
> [Date] datetime not NULL,
> primary key clustered ([RowID])
> )
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
delay
> '0:0:1'
> select t.*
> from [dbo].[Test] as t with (nolock)
> select t.*
> from [dbo].[Test] as t with (nolock)
> inner join (
> select [Field1] = t.[Field1],
> [Field2] = t.[Field2],
> [Date] = max(t.[Date])
> from [dbo].[Test] as t with (nolock)
> group by t.[Field1],
> t.[Field2]
> ) as q on q.[Field1] = t.[Field1]
> and q.[Field2] = t.[Field2]
> and q.[Date] = t.[Date]
>
> In essence, I'm trying to find the rows from Test that have the *maximum*
> Date for a unique Field1/Field2 combination. This query is used in a
> VIEW, and users of this VIEW typically JOIN on RowID.
> I'm sure the "guts" of this VIEW can be refactored to be better, but I
> don't know how to do it. Any suggestions would be *much* appreciated!
> John Peterson
>|||Hello Jens!
I think your suggestion is exactly what I came up with (see original
post) -- I was hoping maybe there was an even better way to express this.
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
> What about (didnt try that but it should work)
> Select * From Test
> Inner Join
> (
> Select Field1,Field2,Max(Date)
> From Test
> Group by Field1,Field2
> ) SUbQuery
> on
> SUbQuery.Field1 = Test.FIeld1 AND
> SUbQuery.Field2 = Test.FIeld2 AND
> SUbQuery.Date = Test.Date
> Its alsways interesting for performance issues to send the execution plan
> with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
> command and youll get the query execution plan in text displayes, which
> you can copy & paste in the newsgroups.
> HTH, Jens Suessmeyer.
> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
> news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
>|||John,
There is another way to do this, but I can not asure that it will give
better performance. you have to compare both execution plan.
select
t1.*
from
[dbo].[Test] as t1 with (nolock)
where
t1.[Date] = (
select
max(t2.[Date])
from
[dbo].[Test] as t2 with (nolock)
where
t2.[Field1] = t1.[Field1]
and t2.[Field2] = t1.[Field2]
)
AMB
"John Peterson" wrote:

> Hello Jens!
> I think your suggestion is exactly what I came up with (see original
> post) -- I was hoping maybe there was an even better way to express this.
>
> "Jens Sü?meyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
in
> message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
>
>|||Sorry, but thats not exact the same, because you additionaly did a
correlated query
within your subselect and additionaly did and a join outside the query.
Bit the best thing to see the differences is to get the query plan for that
options.
HTH, Jens Suessmeyer.
"John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
news:uHWKtFPeFHA.1288@.tk2msftngp13.phx.gbl...
> Hello Jens!
> I think your suggestion is exactly what I came up with (see original
> post) -- I was hoping maybe there was an even better way to express this.
>
> "Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
> in message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
>|||Thanks Alejandro! I'll compare/contrast this technique. Typically, a
subselect within a field has performed more slowly for me -- but not every
case is the same. I'll do as you suggest and examine the Excecution Plans.
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:EA463D89-3CD7-474A-8DAD-6638C9B4066D@.microsoft.com...[vbcol=seagreen]
> John,
> There is another way to do this, but I can not asure that it will give
> better performance. you have to compare both execution plan.
> select
> t1.*
> from
> [dbo].[Test] as t1 with (nolock)
> where
> t1.[Date] = (
> select
> max(t2.[Date])
> from
> [dbo].[Test] as t2 with (nolock)
> where
> t2.[Field1] = t1.[Field1]
> and t2.[Field2] = t1.[Field2]
> )
>
> AMB
>
>
> "John Peterson" wrote:
>|||I don't mean to be obtuse, but I must be missing something. Your query and
my original query appear to be identical.
Here's what I had originally crafted:
select t.*
from [dbo].[Test] as t with (nolock)
inner join (
select [Field1] = t.[Field1],
[Field2] = t.[Field2],
[Date] = max(t.[Date])
from [dbo].[Test] as t with (nolock)
group by t.[Field1],
t.[Field2]
) as q on q.[Field1] = t.[Field1]
and q.[Field2] = t.[Field2]
and q.[Date] = t.[Date]
And here's what you suggested:
Select * From Test
Inner Join
(
Select Field1,Field2,Max(Date)
From Test
Group by Field1,Field2
) SUbQuery
on
SUbQuery.Field1 = Test.FIeld1 AND
SUbQuery.Field2 = Test.FIeld2 AND
SUbQuery.Date = Test.Date
Formatting aside, those seem *identical* to me. Or is there some subtle
difference that I don't perceive that might influence the performance?
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:%238a5LuPeFHA.2984@.TK2MSFTNGP15.phx.gbl...
> Sorry, but thats not exact the same, because you additionaly did a
> correlated query
> within your subselect and additionaly did and a join outside the query.
> Bit the best thing to see the differences is to get the query plan for
> that options.
> HTH, Jens Suessmeyer.
>
> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
> news:uHWKtFPeFHA.1288@.tk2msftngp13.phx.gbl...
>|||Hi John,
The query you posted should perform just fine, provided you add the
proper indexes. It would definitely be desirable to have an index on
Test(Field1,Field2) or even on Test(Field1,Field2,"Date").
HTH,
Gert-Jan
John Peterson wrote:
> (SQL Server 2000, SP4)
> Hello all!
> I'm seeing a lot of I/O generated by one of our queries, and I think it's
> how the query is constructed. Consider the following:
> use [tempdb]
> go
> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].&#
91;Test]
> create table [dbo].[Test]
> (
> [RowID] uniqueidentifier not NULL,
> [Field1] int not NULL,
> [Field2] int not NULL,
> [Date] datetime not NULL,
> primary key clustered ([RowID])
> )
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
delay
> '0:0:1'
> select t.*
> from [dbo].[Test] as t with (nolock)
> select t.*
> from [dbo].[Test] as t with (nolock)
> inner join (
> select [Field1] = t.[Field1],
> [Field2] = t.[Field2],
> [Date] = max(t.[Date])
> from [dbo].[Test] as t with (nolock)
> group by t.[Field1],
> t.[Field2]
> ) as q on q.[Field1] = t.[Field1]
> and q.[Field2] = t.[Field2]
> and q.[Date] = t.[Date]
> In essence, I'm trying to find the rows from Test that have the *maximum*
> Date for a unique Field1/Field2 combination. This query is used in a VIEW
,
> and users of this VIEW typically JOIN on RowID.
> I'm sure the "guts" of this VIEW can be refactored to be better, but I don
't
> know how to do it. Any suggestions would be *much* appreciated!
> John Peterson

Need query optimization help.

(SQL Server 2000, SP4)
Hello all!
I'm seeing a lot of I/O generated by one of our queries, and I think it's
how the query is constructed. Consider the following:
use [tempdb]
go
if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
create table [dbo].[Test]
(
[RowID] uniqueidentifier not NULL,
[Field1] int not NULL,
[Field2] int not NULL,
[Date] datetime not NULL,
primary key clustered ([RowID])
)
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
'0:0:1'
select t.*
from [dbo].[Test] as t with (nolock)
select t.*
from [dbo].[Test] as t with (nolock)
inner join (
select [Field1] = t.[Field1],
[Field2] = t.[Field2],
[Date] = max(t.[Date])
from [dbo].[Test] as t with (nolock)
group by t.[Field1],
t.[Field2]
) as q on q.[Field1] = t.[Field1]
and q.[Field2] = t.[Field2]
and q.[Date] = t.[Date]
In essence, I'm trying to find the rows from Test that have the *maximum*
Date for a unique Field1/Field2 combination. This query is used in a VIEW,
and users of this VIEW typically JOIN on RowID.
I'm sure the "guts" of this VIEW can be refactored to be better, but I don't
know how to do it. Any suggestions would be *much* appreciated!
John Peterson
What about (didnt try that but it should work)
Select * From Test
Inner Join
(
Select Field1,Field2,Max(Date)
From Test
Group by Field1,Field2
) SUbQuery
on
SUbQuery.Field1 = Test.FIeld1 AND
SUbQuery.Field2 = Test.FIeld2 AND
SUbQuery.Date = Test.Date
Its alsways interesting for performance issues to send the execution plan
with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
command and youll get the query execution plan in text displayes, which you
can copy & paste in the newsgroups.
HTH, Jens Suessmeyer.
"John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
> (SQL Server 2000, SP4)
> Hello all!
> I'm seeing a lot of I/O generated by one of our queries, and I think it's
> how the query is constructed. Consider the following:
>
> use [tempdb]
> go
> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
> create table [dbo].[Test]
> (
> [RowID] uniqueidentifier not NULL,
> [Field1] int not NULL,
> [Field2] int not NULL,
> [Date] datetime not NULL,
> primary key clustered ([RowID])
> )
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> select t.*
> from [dbo].[Test] as t with (nolock)
> select t.*
> from [dbo].[Test] as t with (nolock)
> inner join (
> select [Field1] = t.[Field1],
> [Field2] = t.[Field2],
> [Date] = max(t.[Date])
> from [dbo].[Test] as t with (nolock)
> group by t.[Field1],
> t.[Field2]
> ) as q on q.[Field1] = t.[Field1]
> and q.[Field2] = t.[Field2]
> and q.[Date] = t.[Date]
>
> In essence, I'm trying to find the rows from Test that have the *maximum*
> Date for a unique Field1/Field2 combination. This query is used in a
> VIEW, and users of this VIEW typically JOIN on RowID.
> I'm sure the "guts" of this VIEW can be refactored to be better, but I
> don't know how to do it. Any suggestions would be *much* appreciated!
> John Peterson
>
|||Hello Jens!
I think your suggestion is exactly what I came up with (see original
post) -- I was hoping maybe there was an even better way to express this.
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
> What about (didnt try that but it should work)
> Select * From Test
> Inner Join
> (
> Select Field1,Field2,Max(Date)
> From Test
> Group by Field1,Field2
> ) SUbQuery
> on
> SUbQuery.Field1 = Test.FIeld1 AND
> SUbQuery.Field2 = Test.FIeld2 AND
> SUbQuery.Date = Test.Date
> Its alsways interesting for performance issues to send the execution plan
> with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
> command and youll get the query execution plan in text displayes, which
> you can copy & paste in the newsgroups.
> HTH, Jens Suessmeyer.
> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
> news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
>
|||John,
There is another way to do this, but I can not asure that it will give
better performance. you have to compare both execution plan.
select
t1.*
from
[dbo].[Test] as t1 with (nolock)
where
t1.[Date] = (
select
max(t2.[Date])
from
[dbo].[Test] as t2 with (nolock)
where
t2.[Field1] = t1.[Field1]
and t2.[Field2] = t1.[Field2]
)
AMB
"John Peterson" wrote:

> Hello Jens!
> I think your suggestion is exactly what I came up with (see original
> post) -- I was hoping maybe there was an even better way to express this.
>
> "Jens Sü?meyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
> message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
>
>
|||Sorry, but thats not exact the same, because you additionaly did a
correlated query
within your subselect and additionaly did and a join outside the query.
Bit the best thing to see the differences is to get the query plan for that
options.
HTH, Jens Suessmeyer.
"John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
news:uHWKtFPeFHA.1288@.tk2msftngp13.phx.gbl...
> Hello Jens!
> I think your suggestion is exactly what I came up with (see original
> post) -- I was hoping maybe there was an even better way to express this.
>
> "Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
> in message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
>
|||Thanks Alejandro! I'll compare/contrast this technique. Typically, a
subselect within a field has performed more slowly for me -- but not every
case is the same. I'll do as you suggest and examine the Excecution Plans.
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:EA463D89-3CD7-474A-8DAD-6638C9B4066D@.microsoft.com...[vbcol=seagreen]
> John,
> There is another way to do this, but I can not asure that it will give
> better performance. you have to compare both execution plan.
> select
> t1.*
> from
> [dbo].[Test] as t1 with (nolock)
> where
> t1.[Date] = (
> select
> max(t2.[Date])
> from
> [dbo].[Test] as t2 with (nolock)
> where
> t2.[Field1] = t1.[Field1]
> and t2.[Field2] = t1.[Field2]
> )
>
> AMB
>
>
> "John Peterson" wrote:
|||I don't mean to be obtuse, but I must be missing something. Your query and
my original query appear to be identical.
Here's what I had originally crafted:
select t.*
from [dbo].[Test] as t with (nolock)
inner join (
select [Field1] = t.[Field1],
[Field2] = t.[Field2],
[Date] = max(t.[Date])
from [dbo].[Test] as t with (nolock)
group by t.[Field1],
t.[Field2]
) as q on q.[Field1] = t.[Field1]
and q.[Field2] = t.[Field2]
and q.[Date] = t.[Date]
And here's what you suggested:
Select * From Test
Inner Join
(
Select Field1,Field2,Max(Date)
From Test
Group by Field1,Field2
) SUbQuery
on
SUbQuery.Field1 = Test.FIeld1 AND
SUbQuery.Field2 = Test.FIeld2 AND
SUbQuery.Date = Test.Date
Formatting aside, those seem *identical* to me. Or is there some subtle
difference that I don't perceive that might influence the performance?
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:%238a5LuPeFHA.2984@.TK2MSFTNGP15.phx.gbl...
> Sorry, but thats not exact the same, because you additionaly did a
> correlated query
> within your subselect and additionaly did and a join outside the query.
> Bit the best thing to see the differences is to get the query plan for
> that options.
> HTH, Jens Suessmeyer.
>
> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
> news:uHWKtFPeFHA.1288@.tk2msftngp13.phx.gbl...
>
|||Hi John,
The query you posted should perform just fine, provided you add the
proper indexes. It would definitely be desirable to have an index on
Test(Field1,Field2) or even on Test(Field1,Field2,"Date").
HTH,
Gert-Jan
John Peterson wrote:
> (SQL Server 2000, SP4)
> Hello all!
> I'm seeing a lot of I/O generated by one of our queries, and I think it's
> how the query is constructed. Consider the following:
> use [tempdb]
> go
> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
> create table [dbo].[Test]
> (
> [RowID] uniqueidentifier not NULL,
> [Field1] int not NULL,
> [Field2] int not NULL,
> [Date] datetime not NULL,
> primary key clustered ([RowID])
> )
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> select t.*
> from [dbo].[Test] as t with (nolock)
> select t.*
> from [dbo].[Test] as t with (nolock)
> inner join (
> select [Field1] = t.[Field1],
> [Field2] = t.[Field2],
> [Date] = max(t.[Date])
> from [dbo].[Test] as t with (nolock)
> group by t.[Field1],
> t.[Field2]
> ) as q on q.[Field1] = t.[Field1]
> and q.[Field2] = t.[Field2]
> and q.[Date] = t.[Date]
> In essence, I'm trying to find the rows from Test that have the *maximum*
> Date for a unique Field1/Field2 combination. This query is used in a VIEW,
> and users of this VIEW typically JOIN on RowID.
> I'm sure the "guts" of this VIEW can be refactored to be better, but I don't
> know how to do it. Any suggestions would be *much* appreciated!
> John Peterson

Need query optimization help.

(SQL Server 2000, SP4)
Hello all!
I'm seeing a lot of I/O generated by one of our queries, and I think it's
how the query is constructed. Consider the following:
use [tempdb]
go
if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
create table [dbo].[Test]
(
[RowID] uniqueidentifier not NULL,
[Field1] int not NULL,
[Field2] int not NULL,
[Date] datetime not NULL,
primary key clustered ([RowID])
)
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
'0:0:1'
insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
'0:0:1'
select t.*
from [dbo].[Test] as t with (nolock)
select t.*
from [dbo].[Test] as t with (nolock)
inner join (
select [Field1] = t.[Field1],
[Field2] = t.[Field2],
[Date] = max(t.[Date])
from [dbo].[Test] as t with (nolock)
group by t.[Field1],
t.[Field2]
) as q on q.[Field1] = t.[Field1]
and q.[Field2] = t.[Field2]
and q.[Date] = t.[Date]
In essence, I'm trying to find the rows from Test that have the *maximum*
Date for a unique Field1/Field2 combination. This query is used in a VIEW,
and users of this VIEW typically JOIN on RowID.
I'm sure the "guts" of this VIEW can be refactored to be better, but I don't
know how to do it. Any suggestions would be *much* appreciated!
John PetersonWhat about (didn´t try that but it should work)
Select * From Test
Inner Join
(
Select Field1,Field2,Max(Date)
From Test
Group by Field1,Field2
) SUbQuery
on
SUbQuery.Field1 = Test.FIeld1 AND
SUbQuery.Field2 = Test.FIeld2 AND
SUbQuery.Date = Test.Date
Its alsways interesting for performance issues to send the execution plan
with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
command and you´ll get the query execution plan in text displayes, which you
can copy & paste in the newsgroups.
HTH, Jens Suessmeyer.
"John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
> (SQL Server 2000, SP4)
> Hello all!
> I'm seeing a lot of I/O generated by one of our queries, and I think it's
> how the query is constructed. Consider the following:
>
> use [tempdb]
> go
> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
> create table [dbo].[Test]
> (
> [RowID] uniqueidentifier not NULL,
> [Field1] int not NULL,
> [Field2] int not NULL,
> [Date] datetime not NULL,
> primary key clustered ([RowID])
> )
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> select t.*
> from [dbo].[Test] as t with (nolock)
> select t.*
> from [dbo].[Test] as t with (nolock)
> inner join (
> select [Field1] = t.[Field1],
> [Field2] = t.[Field2],
> [Date] = max(t.[Date])
> from [dbo].[Test] as t with (nolock)
> group by t.[Field1],
> t.[Field2]
> ) as q on q.[Field1] = t.[Field1]
> and q.[Field2] = t.[Field2]
> and q.[Date] = t.[Date]
>
> In essence, I'm trying to find the rows from Test that have the *maximum*
> Date for a unique Field1/Field2 combination. This query is used in a
> VIEW, and users of this VIEW typically JOIN on RowID.
> I'm sure the "guts" of this VIEW can be refactored to be better, but I
> don't know how to do it. Any suggestions would be *much* appreciated!
> John Peterson
>|||Hello Jens!
I think your suggestion is exactly what I came up with (see original
post) -- I was hoping maybe there was an even better way to express this.
"Jens Süßmeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
> What about (didn´t try that but it should work)
> Select * From Test
> Inner Join
> (
> Select Field1,Field2,Max(Date)
> From Test
> Group by Field1,Field2
> ) SUbQuery
> on
> SUbQuery.Field1 = Test.FIeld1 AND
> SUbQuery.Field2 = Test.FIeld2 AND
> SUbQuery.Date = Test.Date
> Its alsways interesting for performance issues to send the execution plan
> with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
> command and you´ll get the query execution plan in text displayes, which
> you can copy & paste in the newsgroups.
> HTH, Jens Suessmeyer.
> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
> news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
>> (SQL Server 2000, SP4)
>> Hello all!
>> I'm seeing a lot of I/O generated by one of our queries, and I think it's
>> how the query is constructed. Consider the following:
>>
>> use [tempdb]
>> go
>> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
>> create table [dbo].[Test]
>> (
>> [RowID] uniqueidentifier not NULL,
>> [Field1] int not NULL,
>> [Field2] int not NULL,
>> [Date] datetime not NULL,
>> primary key clustered ([RowID])
>> )
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
>> '0:0:1'
>> select t.*
>> from [dbo].[Test] as t with (nolock)
>> select t.*
>> from [dbo].[Test] as t with (nolock)
>> inner join (
>> select [Field1] = t.[Field1],
>> [Field2] = t.[Field2],
>> [Date] = max(t.[Date])
>> from [dbo].[Test] as t with (nolock)
>> group by t.[Field1],
>> t.[Field2]
>> ) as q on q.[Field1] = t.[Field1]
>> and q.[Field2] = t.[Field2]
>> and q.[Date] = t.[Date]
>>
>> In essence, I'm trying to find the rows from Test that have the *maximum*
>> Date for a unique Field1/Field2 combination. This query is used in a
>> VIEW, and users of this VIEW typically JOIN on RowID.
>> I'm sure the "guts" of this VIEW can be refactored to be better, but I
>> don't know how to do it. Any suggestions would be *much* appreciated!
>> John Peterson
>>
>|||John,
There is another way to do this, but I can not asure that it will give
better performance. you have to compare both execution plan.
select
t1.*
from
[dbo].[Test] as t1 with (nolock)
where
t1.[Date] = (
select
max(t2.[Date])
from
[dbo].[Test] as t2 with (nolock)
where
t2.[Field1] = t1.[Field1]
and t2.[Field2] = t1.[Field2]
)
AMB
"John Peterson" wrote:
> Hello Jens!
> I think your suggestion is exactly what I came up with (see original
> post) -- I was hoping maybe there was an even better way to express this.
>
> "Jens Sü�meyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
> message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
> > What about (didn´t try that but it should work)
> >
> > Select * From Test
> > Inner Join
> > (
> > Select Field1,Field2,Max(Date)
> > From Test
> > Group by Field1,Field2
> > ) SUbQuery
> > on
> > SUbQuery.Field1 = Test.FIeld1 AND
> > SUbQuery.Field2 = Test.FIeld2 AND
> > SUbQuery.Date = Test.Date
> >
> > Its alsways interesting for performance issues to send the execution plan
> > with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
> > command and you´ll get the query execution plan in text displayes, which
> > you can copy & paste in the newsgroups.
> >
> > HTH, Jens Suessmeyer.
> >
> > "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
> > news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
> >> (SQL Server 2000, SP4)
> >>
> >> Hello all!
> >>
> >> I'm seeing a lot of I/O generated by one of our queries, and I think it's
> >> how the query is constructed. Consider the following:
> >>
> >>
> >> use [tempdb]
> >> go
> >>
> >> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
> >> create table [dbo].[Test]
> >> (
> >> [RowID] uniqueidentifier not NULL,
> >> [Field1] int not NULL,
> >> [Field2] int not NULL,
> >> [Date] datetime not NULL,
> >> primary key clustered ([RowID])
> >> )
> >>
> >> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> >> '0:0:1'
> >> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
> >> '0:0:1'
> >> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
> >> '0:0:1'
> >> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> >> '0:0:1'
> >> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
> >> '0:0:1'
> >> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> >> '0:0:1'
> >> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> >> '0:0:1'
> >> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> >> '0:0:1'
> >>
> >> select t.*
> >> from [dbo].[Test] as t with (nolock)
> >>
> >> select t.*
> >> from [dbo].[Test] as t with (nolock)
> >> inner join (
> >> select [Field1] = t.[Field1],
> >> [Field2] = t.[Field2],
> >> [Date] = max(t.[Date])
> >> from [dbo].[Test] as t with (nolock)
> >> group by t.[Field1],
> >> t.[Field2]
> >> ) as q on q.[Field1] = t.[Field1]
> >> and q.[Field2] = t.[Field2]
> >> and q.[Date] = t.[Date]
> >>
> >>
> >> In essence, I'm trying to find the rows from Test that have the *maximum*
> >> Date for a unique Field1/Field2 combination. This query is used in a
> >> VIEW, and users of this VIEW typically JOIN on RowID.
> >>
> >> I'm sure the "guts" of this VIEW can be refactored to be better, but I
> >> don't know how to do it. Any suggestions would be *much* appreciated!
> >>
> >> John Peterson
> >>
> >>
> >
> >
>
>|||Sorry, but thats not exact the same, because you additionaly did a
correlated query
within your subselect and additionaly did and a join outside the query.
Bit the best thing to see the differences is to get the query plan for that
options.
HTH, Jens Suessmeyer.
"John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
news:uHWKtFPeFHA.1288@.tk2msftngp13.phx.gbl...
> Hello Jens!
> I think your suggestion is exactly what I came up with (see original
> post) -- I was hoping maybe there was an even better way to express this.
>
> "Jens Süßmeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
> in message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
>> What about (didn´t try that but it should work)
>> Select * From Test
>> Inner Join
>> (
>> Select Field1,Field2,Max(Date)
>> From Test
>> Group by Field1,Field2
>> ) SUbQuery
>> on
>> SUbQuery.Field1 = Test.FIeld1 AND
>> SUbQuery.Field2 = Test.FIeld2 AND
>> SUbQuery.Date = Test.Date
>> Its alsways interesting for performance issues to send the execution plan
>> with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing the
>> command and you´ll get the query execution plan in text displayes, which
>> you can copy & paste in the newsgroups.
>> HTH, Jens Suessmeyer.
>> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
>> news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
>> (SQL Server 2000, SP4)
>> Hello all!
>> I'm seeing a lot of I/O generated by one of our queries, and I think
>> it's how the query is constructed. Consider the following:
>>
>> use [tempdb]
>> go
>> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
>> create table [dbo].[Test]
>> (
>> [RowID] uniqueidentifier not NULL,
>> [Field1] int not NULL,
>> [Field2] int not NULL,
>> [Date] datetime not NULL,
>> primary key clustered ([RowID])
>> )
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
>> '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
>> '0:0:1'
>> select t.*
>> from [dbo].[Test] as t with (nolock)
>> select t.*
>> from [dbo].[Test] as t with (nolock)
>> inner join (
>> select [Field1] = t.[Field1],
>> [Field2] = t.[Field2],
>> [Date] = max(t.[Date])
>> from [dbo].[Test] as t with (nolock)
>> group by t.[Field1],
>> t.[Field2]
>> ) as q on q.[Field1] = t.[Field1]
>> and q.[Field2] = t.[Field2]
>> and q.[Date] = t.[Date]
>>
>> In essence, I'm trying to find the rows from Test that have the
>> *maximum* Date for a unique Field1/Field2 combination. This query is
>> used in a VIEW, and users of this VIEW typically JOIN on RowID.
>> I'm sure the "guts" of this VIEW can be refactored to be better, but I
>> don't know how to do it. Any suggestions would be *much* appreciated!
>> John Peterson
>>
>>
>|||Thanks Alejandro! I'll compare/contrast this technique. Typically, a
subselect within a field has performed more slowly for me -- but not every
case is the same. I'll do as you suggest and examine the Excecution Plans.
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> wrote in message
news:EA463D89-3CD7-474A-8DAD-6638C9B4066D@.microsoft.com...
> John,
> There is another way to do this, but I can not asure that it will give
> better performance. you have to compare both execution plan.
> select
> t1.*
> from
> [dbo].[Test] as t1 with (nolock)
> where
> t1.[Date] = (
> select
> max(t2.[Date])
> from
> [dbo].[Test] as t2 with (nolock)
> where
> t2.[Field1] = t1.[Field1]
> and t2.[Field2] = t1.[Field2]
> )
>
> AMB
>
>
> "John Peterson" wrote:
>> Hello Jens!
>> I think your suggestion is exactly what I came up with (see original
>> post) -- I was hoping maybe there was an even better way to express this.
>>
>> "Jens Süßmeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
>> in
>> message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
>> > What about (didn´t try that but it should work)
>> >
>> > Select * From Test
>> > Inner Join
>> > (
>> > Select Field1,Field2,Max(Date)
>> > From Test
>> > Group by Field1,Field2
>> > ) SUbQuery
>> > on
>> > SUbQuery.Field1 = Test.FIeld1 AND
>> > SUbQuery.Field2 = Test.FIeld2 AND
>> > SUbQuery.Date = Test.Date
>> >
>> > Its alsways interesting for performance issues to send the execution
>> > plan
>> > with the post, use the SET SHOWPLAN_TEXT ON Statement before issuing
>> > the
>> > command and you´ll get the query execution plan in text displayes,
>> > which
>> > you can copy & paste in the newsgroups.
>> >
>> > HTH, Jens Suessmeyer.
>> >
>> > "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
>> > news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
>> >> (SQL Server 2000, SP4)
>> >>
>> >> Hello all!
>> >>
>> >> I'm seeing a lot of I/O generated by one of our queries, and I think
>> >> it's
>> >> how the query is constructed. Consider the following:
>> >>
>> >>
>> >> use [tempdb]
>> >> go
>> >>
>> >> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
>> >> create table [dbo].[Test]
>> >> (
>> >> [RowID] uniqueidentifier not NULL,
>> >> [Field1] int not NULL,
>> >> [Field2] int not NULL,
>> >> [Date] datetime not NULL,
>> >> primary key clustered ([RowID])
>> >> )
>> >>
>> >> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
>> >> delay
>> >> '0:0:1'
>> >>
>> >> select t.*
>> >> from [dbo].[Test] as t with (nolock)
>> >>
>> >> select t.*
>> >> from [dbo].[Test] as t with (nolock)
>> >> inner join (
>> >> select [Field1] = t.[Field1],
>> >> [Field2] = t.[Field2],
>> >> [Date] = max(t.[Date])
>> >> from [dbo].[Test] as t with (nolock)
>> >> group by t.[Field1],
>> >> t.[Field2]
>> >> ) as q on q.[Field1] = t.[Field1]
>> >> and q.[Field2] = t.[Field2]
>> >> and q.[Date] = t.[Date]
>> >>
>> >>
>> >> In essence, I'm trying to find the rows from Test that have the
>> >> *maximum*
>> >> Date for a unique Field1/Field2 combination. This query is used in a
>> >> VIEW, and users of this VIEW typically JOIN on RowID.
>> >>
>> >> I'm sure the "guts" of this VIEW can be refactored to be better, but I
>> >> don't know how to do it. Any suggestions would be *much* appreciated!
>> >>
>> >> John Peterson
>> >>
>> >>
>> >
>> >
>>|||I don't mean to be obtuse, but I must be missing something. Your query and
my original query appear to be identical.
Here's what I had originally crafted:
select t.*
from [dbo].[Test] as t with (nolock)
inner join (
select [Field1] = t.[Field1],
[Field2] = t.[Field2],
[Date] = max(t.[Date])
from [dbo].[Test] as t with (nolock)
group by t.[Field1],
t.[Field2]
) as q on q.[Field1] = t.[Field1]
and q.[Field2] = t.[Field2]
and q.[Date] = t.[Date]
And here's what you suggested:
Select * From Test
Inner Join
(
Select Field1,Field2,Max(Date)
From Test
Group by Field1,Field2
) SUbQuery
on
SUbQuery.Field1 = Test.FIeld1 AND
SUbQuery.Field2 = Test.FIeld2 AND
SUbQuery.Date = Test.Date
Formatting aside, those seem *identical* to me. Or is there some subtle
difference that I don't perceive that might influence the performance?
"Jens Süßmeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:%238a5LuPeFHA.2984@.TK2MSFTNGP15.phx.gbl...
> Sorry, but thats not exact the same, because you additionaly did a
> correlated query
> within your subselect and additionaly did and a join outside the query.
> Bit the best thing to see the differences is to get the query plan for
> that options.
> HTH, Jens Suessmeyer.
>
> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
> news:uHWKtFPeFHA.1288@.tk2msftngp13.phx.gbl...
>> Hello Jens!
>> I think your suggestion is exactly what I came up with (see original
>> post) -- I was hoping maybe there was an even better way to express this.
>>
>> "Jens Süßmeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
>> in message news:uCi7hBPeFHA.3880@.tk2msftngp13.phx.gbl...
>> What about (didn´t try that but it should work)
>> Select * From Test
>> Inner Join
>> (
>> Select Field1,Field2,Max(Date)
>> From Test
>> Group by Field1,Field2
>> ) SUbQuery
>> on
>> SUbQuery.Field1 = Test.FIeld1 AND
>> SUbQuery.Field2 = Test.FIeld2 AND
>> SUbQuery.Date = Test.Date
>> Its alsways interesting for performance issues to send the execution
>> plan with the post, use the SET SHOWPLAN_TEXT ON Statement before
>> issuing the command and you´ll get the query execution plan in text
>> displayes, which you can copy & paste in the newsgroups.
>> HTH, Jens Suessmeyer.
>> "John Peterson" <j0hnp@.comcast.net> schrieb im Newsbeitrag
>> news:eM0id1OeFHA.3620@.TK2MSFTNGP09.phx.gbl...
>> (SQL Server 2000, SP4)
>> Hello all!
>> I'm seeing a lot of I/O generated by one of our queries, and I think
>> it's how the query is constructed. Consider the following:
>>
>> use [tempdb]
>> go
>> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
>> create table [dbo].[Test]
>> (
>> [RowID] uniqueidentifier not NULL,
>> [Field1] int not NULL,
>> [Field2] int not NULL,
>> [Date] datetime not NULL,
>> primary key clustered ([RowID])
>> )
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
>> delay '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor
>> delay '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor
>> delay '0:0:1'
>> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
>> delay '0:0:1'
>> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor
>> delay '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
>> delay '0:0:1'
>> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor
>> delay '0:0:1'
>> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor
>> delay '0:0:1'
>> select t.*
>> from [dbo].[Test] as t with (nolock)
>> select t.*
>> from [dbo].[Test] as t with (nolock)
>> inner join (
>> select [Field1] = t.[Field1],
>> [Field2] = t.[Field2],
>> [Date] = max(t.[Date])
>> from [dbo].[Test] as t with (nolock)
>> group by t.[Field1],
>> t.[Field2]
>> ) as q on q.[Field1] = t.[Field1]
>> and q.[Field2] = t.[Field2]
>> and q.[Date] = t.[Date]
>>
>> In essence, I'm trying to find the rows from Test that have the
>> *maximum* Date for a unique Field1/Field2 combination. This query is
>> used in a VIEW, and users of this VIEW typically JOIN on RowID.
>> I'm sure the "guts" of this VIEW can be refactored to be better, but I
>> don't know how to do it. Any suggestions would be *much* appreciated!
>> John Peterson
>>
>>
>>
>|||Hi John,
The query you posted should perform just fine, provided you add the
proper indexes. It would definitely be desirable to have an index on
Test(Field1,Field2) or even on Test(Field1,Field2,"Date").
HTH,
Gert-Jan
John Peterson wrote:
> (SQL Server 2000, SP4)
> Hello all!
> I'm seeing a lot of I/O generated by one of our queries, and I think it's
> how the query is constructed. Consider the following:
> use [tempdb]
> go
> if (object_id('[dbo].[Test]') is not NULL) drop table [dbo].[Test]
> create table [dbo].[Test]
> (
> [RowID] uniqueidentifier not NULL,
> [Field1] int not NULL,
> [Field2] int not NULL,
> [Date] datetime not NULL,
> primary key clustered ([RowID])
> )
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 2, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 3, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 3, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 2, 1, getdate()) waitfor delay
> '0:0:1'
> insert into [dbo].[Test] values (newid(), 1, 1, getdate()) waitfor delay
> '0:0:1'
> select t.*
> from [dbo].[Test] as t with (nolock)
> select t.*
> from [dbo].[Test] as t with (nolock)
> inner join (
> select [Field1] = t.[Field1],
> [Field2] = t.[Field2],
> [Date] = max(t.[Date])
> from [dbo].[Test] as t with (nolock)
> group by t.[Field1],
> t.[Field2]
> ) as q on q.[Field1] = t.[Field1]
> and q.[Field2] = t.[Field2]
> and q.[Date] = t.[Date]
> In essence, I'm trying to find the rows from Test that have the *maximum*
> Date for a unique Field1/Field2 combination. This query is used in a VIEW,
> and users of this VIEW typically JOIN on RowID.
> I'm sure the "guts" of this VIEW can be refactored to be better, but I don't
> know how to do it. Any suggestions would be *much* appreciated!
> John Peterson

Need Query Help

I have the following queries which probably violates all sorts of rules.
I'm doing year over year changes and can't seem to get the entire calucation
done in one query. So I'm pulling data from one query (SQL2) and using it
in another query (SQL1). You'll see real numbers being used in SQL1 (ie
(totalmem - 30152)). The 30152 is coming from the other query.
I would rather have access to all the data in a single query. My real issue
is that from period to period health plans come and go in our data file
because they cease operations in a State and then reenter the market a year
or two later... Most health plans are constant in the data. A few come and
go. I might have 5 records in 2Q03 data and 6 in 2Q02 data. This causes
SQL1 to break because the rs2 data does not exisit if there is more data in
SQL1 than SQL2.
Data format:
MCO HMO MeciareMem MedicaidMem CommMem TotalMem
If I could get the data returned like this:
MCO HMO MedicareMem2Q03 MedicareMem2Q02, MedicaidMem2Q03,
MedicareMem2Q02... I would be in great shape
My data file looks like this:
Period MCO HMO MeciareMem MedicaidMem CommMem TotalMem
2Q02 Aetna Aetna Health of CT 0 0 37947 37947
2Q03 Aetna Aetna Health of CT 0 0 41110 41110
except that I have 11,000 rows of data.
I'd love some help on this one. A sample data set is below.
***
SQL2= "Select MCO, HMO, medicaremem, medicaidmem, commmem, totalmem from
sheet1$ where period = '" & varPeriod4 & "' AND " & strStateSQL1 & " order
by " & varsort & " " & varorder
renders like this:
SQL2 = Select MCO, HMO, medicaremem, medicaidmem, commmem, totalmem from
sheet1$ where period = '3Q03' AND (domicile LIKE '%ct%' OR domicile LIKE
'%ma%' OR domicile LIKE '%nh%' OR domicile LIKE '%me%' OR domicile LIKE
'%ri%' OR domicile LIKE '%vt%' OR domicile LIKE '%ny%' OR domicile LIKE
'%nj%' OR domicile LIKE '%pa%') order by hmo asc
***
SQL1= "Select MCO, HMO, medicaremem, (medicaremem - " & rs2("medicaremem") &
") as medicarememchange, medicaidmem, commmem, totalmem, (totalmem - " &
rs2("totalmem") & ") as totalmemchange from sheet1$ where totalmem <> '' and
period = '" & varPeriod & "' AND " & strStateSQL1 & " order by " & varsort &
" " & varorder
renders like this:
SQL1 = Select MCO, HMO, medicaremem, (medicaremem - 0) as medicarememchange,
medicaidmem, commmem, totalmem, (totalmem - 30152) as totalmemchange from
sheet1$ where totalmem <> '' and period = '3Q04' AND (domicile LIKE '%ct%'
OR domicile LIKE '%ma%' OR domicile LIKE '%nh%' OR domicile LIKE '%me%' OR
domicile LIKE '%ri%' OR domicile LIKE '%vt%' OR domicile LIKE '%ny%' OR
domicile LIKE '%nj%' OR domicile LIKE '%pa%') order by hmo ascHi
Posting DDL and example data is the best way to help people answer your
questions, see http://www.aspfaq.com/etiquett_e.asp?id=5006
This may give you some indication of what you require assuming primary the
key is MCO, HMO, medicaremem
Select a.MCO, a.HMO, a.medicaremem, a.medicaidmem-b.medicaidmem, a.commmem,
b.commmem, a.totalmem-b.totalmem
from sheet1$ a
JOIN sheet1$ b ON a.MCO = b.MCO AND a.HMO = b.HMO AND a.medicaremem =
b.medicaremem
where a.period = '3Q03'
and b.period = '3Q04'
If there is not always a record in '3Q04' then try:
Select a.MCO, a.HMO, a.medicaremem, a.medicaidmem-ISNULL(b.medicaidmem,0),
a.commmem, b.commmem, a.totalmem - ISNULL(b.totalmem,0)
from sheet1$ a
LEFT JOIN sheet1$ b ON a.MCO = b.MCO AND a.HMO = b.HMO AND a.medicaremem =
b.medicaremem
where a.period = '3Q03'
and b.period = '3Q04'
John
"William" wrote:

> I have the following queries which probably violates all sorts of rules.
> I'm doing year over year changes and can't seem to get the entire calucati
on
> done in one query. So I'm pulling data from one query (SQL2) and using it
> in another query (SQL1). You'll see real numbers being used in SQL1 (ie
> (totalmem - 30152)). The 30152 is coming from the other query.
> I would rather have access to all the data in a single query. My real iss
ue
> is that from period to period health plans come and go in our data file
> because they cease operations in a State and then reenter the market a yea
r
> or two later... Most health plans are constant in the data. A few come a
nd
> go. I might have 5 records in 2Q03 data and 6 in 2Q02 data. This causes
> SQL1 to break because the rs2 data does not exisit if there is more data i
n
> SQL1 than SQL2.
> Data format:
> MCO HMO MeciareMem MedicaidMem CommMem TotalMem
>
> If I could get the data returned like this:
> MCO HMO MedicareMem2Q03 MedicareMem2Q02, MedicaidMem2Q03,
> MedicareMem2Q02... I would be in great shape
> My data file looks like this:
> Period MCO HMO MeciareMem MedicaidMem CommMem TotalMem
> 2Q02 Aetna Aetna Health of CT 0 0 37947 37947
> 2Q03 Aetna Aetna Health of CT 0 0 41110 41110
> except that I have 11,000 rows of data.
>
> I'd love some help on this one. A sample data set is below.
> ***
> SQL2= "Select MCO, HMO, medicaremem, medicaidmem, commmem, totalmem from
> sheet1$ where period = '" & varPeriod4 & "' AND " & strStateSQL1 & " order
> by " & varsort & " " & varorder
> renders like this:
> SQL2 = Select MCO, HMO, medicaremem, medicaidmem, commmem, totalmem from
> sheet1$ where period = '3Q03' AND (domicile LIKE '%ct%' OR domicile LIKE
> '%ma%' OR domicile LIKE '%nh%' OR domicile LIKE '%me%' OR domicile LIKE
> '%ri%' OR domicile LIKE '%vt%' OR domicile LIKE '%ny%' OR domicile LIKE
> '%nj%' OR domicile LIKE '%pa%') order by hmo asc
> ***
> SQL1= "Select MCO, HMO, medicaremem, (medicaremem - " & rs2("medicaremem")
&
> ") as medicarememchange, medicaidmem, commmem, totalmem, (totalmem - " &
> rs2("totalmem") & ") as totalmemchange from sheet1$ where totalmem <> '' a
nd
> period = '" & varPeriod & "' AND " & strStateSQL1 & " order by " & varsort
&
> " " & varorder
> renders like this:
> SQL1 = Select MCO, HMO, medicaremem, (medicaremem - 0) as medicarememchang
e,
> medicaidmem, commmem, totalmem, (totalmem - 30152) as totalmemchange from
> sheet1$ where totalmem <> '' and period = '3Q04' AND (domicile LIKE '%ct%'
> OR domicile LIKE '%ma%' OR domicile LIKE '%nh%' OR domicile LIKE '%me%' OR
> domicile LIKE '%ri%' OR domicile LIKE '%vt%' OR domicile LIKE '%ny%' OR
> domicile LIKE '%nj%' OR domicile LIKE '%pa%') order by hmo asc
>
>
>|||I'd build a table of the periods, then do a LEFT OUTER JOIN on it to
the membership table. This will give you NULLs for the periods that
the particular company was not in the State.
If you really must have things on one row, then you can use CASE
expressions inside aggregates.
I also wonder why you use things like "(domicile LIKE '%pa%')" instead
of scrubbing the data to assure that you have CHAR(2) valid state
codes.

Friday, March 9, 2012

Need one Query to obtain results I can only get with two queries

I'm trying to devise a query for use on SQL Server 2000 that will do
what was previously done with one query in MS Access. The MS Access
query was like this:

SELECT Count(*) as [Opened],
Abs(Sum([Status] Like 'Cancel*')) As [Cancelled]
FROM Detail_Dir_LocV
Where (Detail_Dir_LocV.DateOpened > '2004-8-01') and
Status not like 'Deleted'
Group By Year(DateOpened), Month(DateOpened)
Order By Year(DateOpened), Month(DateOpened)

Here were I'm at with SQL Server, TSQL

Select Right(Convert(Char (11), Min(DateOpened), 106), 8) as [Month
Opened],
Count(Status) as [Opened]
FROM Detail_Dir_LocV
Where (Detail_Dir_LocV.DateOpened > '2004-8-01') and
Status not like 'Deleted'
Group By Year(DateOpened), Month(DateOpened) Order By
Year(DateOpened), Month(DateOpened)

Which yields

MonthOpened
======================
Aug 2004503
Sep 2004752
Oct 2004828
Nov 2004658
Dec 2004533
Jan 2005736
Feb 2005707
Mar 2005797
Apr 2005412

And

Select Right(Convert(Char (11), Min(DateOpened), 106), 8) as [Month
Opened],
Count(Status) as [Cancelled]
FROM Detail_Dir_LocV
Where (Detail_Dir_LocV.DateOpened > '2004-8-01') and
Status like 'Cancelled%'
Group By Year(DateOpened), Month(DateOpened) Order By
Year(DateOpened), Month(DateOpened)

Which yields;

MonthCancelled
=========================
Aug 200478
Sep 2004105
Oct 2004121
Nov 2004106
Dec 200475
Jan 200582
Feb 200571
Mar 200594
Apr 200533

What is desired is

MonthOpenedCancelled
============================
Aug 200450378
Sep 2004752105
Oct 2004828121
Nov 2004658106
Dec 200453375
Jan 200573682
Feb 200570771
Mar 200579794
Apr 200541233

Any assistance would be appreciated.

Cheers;

BillI think that you need something like this:

Select Right(Convert(Char (11), Min(DateOpened), 106), 8) as [Month
Opened],
Count(Status) as [Opened],
Sum(CASE WHEN [Status] Like 'Cancel%' THEN 1 ELSE 0 END) as
[Cancelled]
FROM Detail_Dir_LocV
Where (Detail_Dir_LocV.DateOpened > '2004-8-01') and Status not like
'Deleted'
Group By Year(DateOpened), Month(DateOpened)
Order By Year(DateOpened), Month(DateOpened)

Razvan

PS. It would have been useful if you would have provided the DDL (in
form of "CREATE TABLE..." statements) and some sample data (in form of
"INSERT INTO ... VALUES ..." statements).|||"Razvan Socol" <rsocol@.gmail.com> wrote in message news:<1113473001.684266.112120@.o13g2000cwo.googlegroups. com>...
> I think that you need something like this:
> Select Right(Convert(Char (11), Min(DateOpened), 106), 8) as [Month
> Opened],
> Count(Status) as [Opened],
> Sum(CASE WHEN [Status] Like 'Cancel%' THEN 1 ELSE 0 END) as
> [Cancelled]
> FROM Detail_Dir_LocV
> Where (Detail_Dir_LocV.DateOpened > '2004-8-01') and Status not like
> 'Deleted'
> Group By Year(DateOpened), Month(DateOpened)
> Order By Year(DateOpened), Month(DateOpened)
> Razvan
> PS. It would have been useful if you would have provided the DDL (in
> form of "CREATE TABLE..." statements) and some sample data (in form of
> "INSERT INTO ... VALUES ..." statements).

Razvan;

Thank you for your assistance. It solved my problem.

Is the purpose of your request for a Create Table and Insert samples
so that you might build the table and populate it locally to test your
proposed solution? I think I know how to get the Create statement
since in fact the query is accessing a view and I can just grab it's
properties. The main table that the view is built upon was built
interactively. The table is also populated via an ASP html form so
building a set of insert into would be a manual process. Is there
anyway to have SQL Server build a sample for your intended purpose
based upon the existing data in the table or view?

Any way, you solved my problem and I appreciate your time.

Thank you.

Cheers;

Bill|||Hi Bill,

Yes, that is the purpose: to enable us to test the solution easily, but
also to make us sure that we properly understood the scenario, to make
all of those who respond use the same column names.

For generating insert scripts from the existing data, see:
http://vyaskn.tripod.com/code.htm#inserts
http://www.databasejournal.com/scri...cle.php/1493101

For in-depth considerations about DDL and sample data, see:
http://www.aspfaq.com/etiquette.asp?id=5006

Razvan

Saturday, February 25, 2012

Need Help, fast

I have a SP which is having an odd problem. There is an int which I am
using to to return several different queries in the SP. The first
query gets the value of the int based on a date, @.minsess. @.minsess is
then used in multiple queries in the SP. For some reason if I replace
@.minsess with a value say 656 then query plan changes and the entire sp
executes in seconds, with @.minsess each query takes much longer
resulting in the SP taking more than a minute to execute.
A dumbed down version of this would be like this.
Select @.minsess = min(sessionid) from table1 where FileDate >=
CONVERT(varchar(10), getdate() - 3, 112)
Select * FRom table2 where sessionid >= @.minsess
Select * FRom table2 where sessionid >= 656
In this example @.minsess would equal 656. Both are INTs, why in the
world would the first table2 hit take multiple times longer to return
than the second?For a parameter to a stored procedure, the optimizer picks up the value for
when the execution plan
is created ("first execution") and put into cache. This is the value the opt
imize base its execution
plan on.
For a constant, then the optimize know the value.
For a variable, the optimizer doesn't know the value and have to guess the s
electivity (number of
rows that matches).
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"Paul Moore" <ptmoore@.gmail.com> wrote in message
news:1108047830.104598.326620@.o13g2000cwo.googlegroups.com...
>I have a SP which is having an odd problem. There is an int which I am
> using to to return several different queries in the SP. The first
> query gets the value of the int based on a date, @.minsess. @.minsess is
> then used in multiple queries in the SP. For some reason if I replace
> @.minsess with a value say 656 then query plan changes and the entire sp
> executes in seconds, with @.minsess each query takes much longer
> resulting in the SP taking more than a minute to execute.
> A dumbed down version of this would be like this.
> Select @.minsess = min(sessionid) from table1 where FileDate >=
> CONVERT(varchar(10), getdate() - 3, 112)
> Select * FRom table2 where sessionid >= @.minsess
>
> Select * FRom table2 where sessionid >= 656
> In this example @.minsess would equal 656. Both are INTs, why in the
> world would the first table2 hit take multiple times longer to return
> than the second?
>|||You get this problem because you use a variable in a WHERE clause. Because
the Query Optimizer doesn't know at compile time what the value of the
variable will be, it decides on a query plan based on an estimate of the
number of rows that will be returned. For a >= comparison it assumes 30% of
the rows will be returned IIRC.
If you change your code to:
Select * FRom table2 where sessionid >= (Select min(sessionid) from table1
where FileDate >=
CONVERT(varchar(10), getdate() - 3, 112))
the Query Optimizer will come up with a faster execution plan.
Jacco Schalkwijk
SQL Server MVP
"Paul Moore" <ptmoore@.gmail.com> wrote in message
news:1108047830.104598.326620@.o13g2000cwo.googlegroups.com...
>I have a SP which is having an odd problem. There is an int which I am
> using to to return several different queries in the SP. The first
> query gets the value of the int based on a date, @.minsess. @.minsess is
> then used in multiple queries in the SP. For some reason if I replace
> @.minsess with a value say 656 then query plan changes and the entire sp
> executes in seconds, with @.minsess each query takes much longer
> resulting in the SP taking more than a minute to execute.
> A dumbed down version of this would be like this.
> Select @.minsess = min(sessionid) from table1 where FileDate >=
> CONVERT(varchar(10), getdate() - 3, 112)
> Select * FRom table2 where sessionid >= @.minsess
>
> Select * FRom table2 where sessionid >= 656
> In this example @.minsess would equal 656. Both are INTs, why in the
> world would the first table2 hit take multiple times longer to return
> than the second?
>|||Thanks

Monday, February 20, 2012

Need help with UNION and SUM

Hi!

I am trying to join to different queries into one table ( I accomplished this)

Next I need to ADD or SUM the results of 2 rows to form a single row.

As you can see in the query below, I run 2 separate queries and use ' ' as a place holder for the UNION to work. I get duplicate rows, one with a value and the other with a '0'. I want to have a single row.

Any help is greatly appreciated!

(SELECT
v_gs_supportedpackages.ProdID0 as 'Product Name',
v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 as 'Site',
Count(ProdID0) as '# copies installed',
'' as '# legitimate copies installed'

FROM
v_R_System SYS,
v_GS_Workstation_Status HWSCAN,
v_gs_SupportedPackages
inner join
v_RA_System_SMSInstalledSites on v_RA_System_SMSInstalledSites.ResourceID = v_gs_SupportedPackages.ResourceID

WHERE
SYS.ResourceId = HWSCAN.ResourceId
AND
SYS.ResourceId = v_gs_SupportedPackages.ResourceId
AND
v_gs_supportedpackages.ProdID0 = substring('MS Security Patch MS04-030,031,032,034,037,038',1,60)

GROUP BY

v_gs_supportedpackages.ProdID0,
v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 )

UNION

(SELECT
v_gs_supportedpackages.ProdID0 as 'Product Name',
v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 as 'Site',
'' as '# copies installed',
Count(ProdID0) as '# legitimate copies installed'

FROM
v_R_System SYS,
v_GS_Workstation_Status HWSCAN,
v_gs_SupportedPackages
inner join
v_RA_System_SMSInstalledSites on v_RA_System_SMSInstalledSites.ResourceID = v_gs_SupportedPackages.ResourceID

WHERE
SYS.ResourceId = HWSCAN.ResourceId
AND
SYS.ResourceId = v_gs_SupportedPackages.ResourceId
AND
v_gs_supportedpackages.ProdID0 = substring('MS Security Patch MS04-030,031,032,034,037,038',1,60)
AND
DateDiff(Day,HWSCAN.LastHWScan,GetDate()) <= '20'

GROUP BY

v_gs_supportedpackages.ProdID0,
v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 )Change your null string place holder to a zero and use a table variable to return only 1 row for each instance of ColA and ColB. For example

DECLARE @.myTable table
(
ColA varchar(50), CoB varchar(50), ColC int, ColD int
)

INSERT INTO @.myTable
(ColA, ColB, ColC, ColD)

SELECT ColA, ColB, SUM(ColC), 0
FROM TableA

UNION ALL

SELECT ColA, ColB, 0, Sum(ColD)
FROM TableB
GROUP BY ColA, ColB

ORDER BY 1, 2

SELECT ColA, ColB, SUM(ColC) AS ColC, SUM(ColD) AS ColD
FROM @.myTable
GROUP BY ColA, ColB
ORDER BY 1, 2
GO|||First, fix your queries to eliminate joining tables in your WHERE clauses.
Second, you don't (and shouldn't) enclose numeric values in quotes.
Third, you don't need UNION here. You need a full outer join:

SELECT COPIESINSTALLED.ProdID0 as 'Product Name', COPIESINSTALLED.SMS_Installed_Sites0 as 'Site', COPIESINSTALLED.TOTAL as '# copies installed', LEGITCOPIESINSTALLED.TOTAL as '# legitimate copies installed'
FROM
(SELECT v_gs_supportedpackages.ProdID0, v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 , Count(ProdID0) TOTAL
FROM v_R_System SYS,
INNER JOIN v_GS_Workstation_Status HWSCAN ON SYS.ResourceId = HWSCAN.ResourceId
INNER JOIN v_gs_SupportedPackages ON SYS.ResourceId = v_gs_SupportedPackages.ResourceId
INNER JOIN v_RA_System_SMSInstalledSites ON v_RA_System_SMSInstalledSites.ResourceID = v_gs_SupportedPackages.ResourceID
WHERE v_gs_supportedpackages.ProdID0 = substring('MS Security Patch MS04-030,031,032,034,037,038',1,60)
GROUP BY v_gs_supportedpackages.ProdID0, v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 ) COPIESINSTALLED
FULL OUTER JOIN
(SELECT v_gs_supportedpackages.ProdID0, v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 , Count(ProdID0) TOTAL
FROM v_R_System SYS,
INNER JOIN v_GS_Workstation_Status HWSCAN ON SYS.ResourceId = HWSCAN.ResourceId
INNER JOIN v_gs_SupportedPackages ON SYS.ResourceId = v_gs_SupportedPackages.ResourceId
INNER JOIN v_RA_System_SMSInstalledSites ON v_RA_System_SMSInstalledSites.ResourceID = v_gs_SupportedPackages.ResourceID
WHERE v_gs_supportedpackages.ProdID0 = substring('MS Security Patch MS04-030,031,032,034,037,038',1,60)
AND DateDiff(Day,HWSCAN.LastHWScan,GetDate()) <= 20
GROUP BY v_gs_supportedpackages.ProdID0, v_RA_System_SMSInstalledSites.SMS_Installed_Sites0 ) LEGITCOPIESINSTALLED
ON COPIESINSTALLED.ProdID0 = LEGITCOPIESINSTALLED.ProdID0
AND COPIESINSTALLED.SMS_Installed_Sites0 = LEGITCOPIESINSTALLED.SMS_Installed_Sites0

Finally, you could probably do the whole thing in a single SELECT with a CASE statement in the result set, but I'm not clear enough on your task to create the SQL for you.

...and one other thing. What is "substring('MS Security Patch MS04-030,031,032,034,037,038',1,60)" supposed to be doing for you?|||Many thanks to you. I knew you guys would knock this out.

Thanks again.

Semper Fi,

JP|||Blindman,

Thanks again for your help. In regards to:

Finally, you could probably do the whole thing in a single SELECT with a CASE statement in the result set, but I'm not clear enough on your task to create the SQL for you.

...and one other thing. What is "substring('MS Security Patch MS04-030,031,032,034,037,038',1,60)" supposed to be doing for you?
__________________

The substring was the only way I could pump in a variable with commas. On our web reports this value is dynamic and due to the naming conventions of our admins, some put commas in the title to separate the different versions of a package.

If you know a better way to capture commas and not have SQL try to evaluate it as an expression, please let me know!

Many thanks again,

JP