Monday, March 19, 2012
How to reverse a reverse order by?
using the statement
SELECT TOP 10 * FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
I get the last 10 rows in the Import table as expected, but how to I reverse
these last 10 rows?
MortenUse an outer query which has an ORDER BY in the other direction.
SELECT ...
FROM
(
SELECT TOP 10 ... FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
) AS i
ORDER BY rowID ASC
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Morten Wennevik" <Morten.Wennevik@.email.adr> wrote in message
news:op.sz2pzfp2g1d8xu@.tr023.bouvet.no...
> Hi,
> using the statement
> SELECT TOP 10 * FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
> I get the last 10 rows in the Import table as expected, but how to I rever
se these last 10 rows?
> Morten|||Hi Morten,
hope I undertstand you right to reorder the queried rows before.
SELECT
* FROM
(
SELECT TOP 10 * FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
) SubQuery
Order by RowID
So you want the hightest 10 Rows, but those in an ascending order,
right ?
HTH, Jens Suessmeyer.|||Well, I tried this before, but I get an error near the keyword 'ORDER'
SELECT * FROM
(
SELECT TOP 10 * FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
)
ORDER BY RowID ASC
Morten
On Fri, 11 Nov 2005 12:31:40 +0100, Tibor Karaszi <tibor_please.no.email_kar
aszi@.hotmail.nomail.com> wrote:
> Use an outer query which has an ORDER BY in the other direction.
> SELECT ...
> FROM
> (
> SELECT TOP 10 ... FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
> ) AS i
> ORDER BY rowID ASC|||It accepts the query when I add AS i after (), but it still does not ascend
the RowIDs
On Fri, 11 Nov 2005 12:38:16 +0100, Morten Wennevik <Morten.Wennevik@.email.a
dr> wrote:
> Well, I tried this before, but I get an error near the keyword 'ORDER'
> SELECT * FROM
> (
> SELECT TOP 10 * FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
> )
> ORDER BY RowID ASC
> Morten
>
> On Fri, 11 Nov 2005 12:31:40 +0100, Tibor Karaszi <tibor_please.no.email_k
araszi@.hotmail.nomail.com> wrote:
>
>|||Yes, given RowIDs from 1-499 I want 490-499
On Fri, 11 Nov 2005 12:37:11 +0100, Jens <Jens@.sqlserver2005.de> wrote:
> Hi Morten,
> hope I undertstand you right to reorder the queried rows before.
> SELECT
> * FROM
> (
> SELECT TOP 10 * FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
> ) SubQuery
> Order by RowID
> So you want the hightest 10 Rows, but those in an ascending order,
> right ?
> HTH, Jens Suessmeyer.
>|||You need to name the derived (inner) table, see the AS clause after the clos
ing bracket.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Morten Wennevik" <Morten.Wennevik@.email.adr> wrote in message
news:op.sz2ql2d7g1d8xu@.tr023.bouvet.no...
> Well, I tried this before, but I get an error near the keyword 'ORDER'
> SELECT * FROM
> (
> SELECT TOP 10 * FROM Import WHERE RowID >= 1 ORDER BY RowID DESC
> )
> ORDER BY RowID ASC
> Morten
>
> On Fri, 11 Nov 2005 12:31:40 +0100, Tibor Karaszi
> <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote:
>
>|||Using your suggestion the RowIDs still got from 499-490, which is the opposi
te of what I want
On Fri, 11 Nov 2005 12:41:41 +0100, Morten Wennevik <Morten.Wennevik@.email.a
dr> wrote:
> Yes, given RowIDs from 1-499 I want 490-499
>
> On Fri, 11 Nov 2005 12:37:11 +0100, Jens <Jens@.sqlserver2005.de> wrote:
>
>|||Ok, I'm baffled, selecting * ignores the last reverse ordering, but selectin
g just RowID will give me 490-499
?
On Fri, 11 Nov 2005 12:47:07 +0100, Morten Wennevik <Morten.Wennevik@.email.a
dr> wrote:
> Using your suggestion the RowIDs still got from 499-490, which is the oppo
site of what I want
> On Fri, 11 Nov 2005 12:41:41 +0100, Morten Wennevik <Morten.Wennevik@.email
.adr> wrote:
>
>
How to return the first row of each group of rows
I have a group of rows that grouped by host and user. I want to return the first row of each group of hosts. I have struggled with this all day and need some help. With this T-SQL I have built the table:
USE Test
GO
IF OBJECT_ID(N'[dbo].Sample') IS NOT NULL
DROP TABLE [dbo].Sample
GO
-- Create the Sample table
CREATE TABLE [dbo].Sample(
ID [int] IDENTITY NOT NULL,
Host [varchar](128) NOT NULL,
Username [varchar](128) NOT NULL,
Seconds [int] NOT NULL)
GO
SET NOCOUNT ON
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C001','Smith',120012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C001','Jone',100012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C001','Doe',90012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C001','Cole',80012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C001','Lee',70012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C002','Lee',8012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C002','Cole',5012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C002','Smith',4012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C003','Doe',90012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C003','Lee',80012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C003','Cole',7012);
INSERT INTO [dbo].Sample(Host,Username,Seconds) VALUES('C003','Smith',60012);
SET NOCOUNT OFF
I want to write a select statement that will return the first row of each host group:
C001 Smith 120012
C002 Lee 8012
C003 Doe 90012
Thanks for pointing me in the right direction.
Ken
Give a look to the ROW_NUMBER() function in books online; partition by host and order by seconds.|||Try:
select
a.*
from
dbo.Sample as a
where
not exists(
select
*
from
dbo.Sample as b
where
b.Host = a.Host
and b.[ID] < a.[ID]
)
go
-- 2005
;with cte
as
(
select
Host, Username, Seconds,
row_number() over(partition by Host order by [ID]) as rn
from
dbo.Sample
)
select
*
from
cte
where
rn = 1
go
AMB
|||Also,
select
a.*
from
dbo.Sample as a
where
a.[ID] = (
select
min(b.[ID])
from
dbo.Sample as b
where
b.Host = a.Host
)
go
AMB
Monday, March 12, 2012
How to return specific Row in sql server
Suppose I have 100 rows in my table, I want to retrieve say row no 5(I just want any thing on row no 5), I don't want to use identity column. Is there any other way by which I can retrieve specified row.
Thanks,
Sajidin relational databases, rows do not have a position -- there is no "5th row in the table" because the rows are not stored in sequence
the only way to get a specific row is to select it based on the value of one or more of its columns
if you sort the rows of the table into a specific sequence based on the values of one or more columns, then yes, you can get the 5th row
so, tell me what columns you want to sort the table on, and i'll show you how to get the 5th row in that sequence
rudy
http://r937.com/|||Originally posted by r937
in relational databases, rows do not have a position -- there is no "5th row in the table" because the rows are not stored in sequence
the only way to get a specific row is to select it based on the value of one or more of its columns
if you sort the rows of the table into a specific sequence based on the values of one or more columns, then yes, you can get the 5th row
so, tell me what columns you want to sort the table on, and i'll show you how to get the 5th row in that sequence
rudy
http://r937.com/
Thanks for answering my question.
Say suppose I have Name column and i want the 5th record on name column.
Thanks
Sajid|||Hi
U are asking how to select a row without having to specify anything unique about that row other than it's Ordinal position within the table.
Are U sure thats what U want
Are U Saying you want to select a row based on it's position within a table?
Ooops r937 U posted whilst I was Posting - I'll Post anyway
GW|||Originally posted by GWilliy
Hi
U are asking how to select a row without having to specify anything unique about that row other than it's Ordinal position within the table.
Are U sure thats what U want
Are U Saying you want to select a row based on it's position within a table?
Ooops r937 U posted whilst I was Posting - I'll Post anyway
GW
Yes I need the same.|||select top 1
from (
select top 5
Name
from yourtable
order
by Name
)
order
by Name desc
rudy|||Originally posted by r937
select top 1
from (
select top 5
Name
from yourtable
order
by Name
)
order
by Name desc
rudy
Thanks, It works.
If suppose i want to retrieve all columns, then do I need to specific each column.|||U could actualy do a sraight select into a cursor & then go straight to the Row
DECLARE @.a VarChar(20),@.b,@.c
DECLARE myCursor CURSOR SCROLL
FOR
SELECT a,b,c FROM myTable
OPEN myCursor
FETCH ABSOLUTE 5 INTO @.a,@.b,@.c
BEGIN
PRINT @.a
PRINT @.b
PRINT @.c
END
CLOSE myCursor
DEALLOCATE myCursor
example Code to give U an Idea - There are many options available when declaring Cursors etc.
May be more suitable for whatever Sajidrep is Doing
GW
How to return only the first row....
ThanksIn Oracle you would add
AND ROWNUM = 1
to the WHERE clause
-- rajXesh|||Thanks rajXesh!|||Is there a similar command for SQL Server?|||Originally posted by acg_ray
Is there a similar command for SQL Server?
SELECT TOP 1 * FROM [table]|||Thx Joel. That did it.
how to return only last select from stored procedure
I am using first and second select just for calculating number of rows
(@.@.ROWCOUNT), and last one is the final select that I need. But I get all
three selects
TomislawTomislaw,
If the first two are only for calculating the number of rows, then use
select @.numrows = count(*)
from ...
instead of doing the select query and referencing @.@.rowcount.
If you do a select query in a stored procedure, it will be returned as a
result set.
Rob|||it is not so simple
my select is:
SELECT Date1, Date2, Neto, Provision
FROM TERMIN
WHERE (ID = @.ID)
AND (Date1>= @.Date1 AND DatumDo <= @.Date2)
GROUP BY Date1, Date2, Neto, Provision
HAVING (MAX(BedsNo) >= @.BedsNo)
i get 2 rows
with count i get number 3
"Rob Farley" <RobFarley@.discussions.microsoft.com> wrote in message
news:E655A96C-643E-40F1-B045-D6F3DC713737@.microsoft.com...
> Tomislaw,
> If the first two are only for calculating the number of rows, then use
> select @.numrows = count(*)
> from ...
> instead of doing the select query and referencing @.@.rowcount.
> If you do a select query in a stored procedure, it will be returned as a
> result set.
> Rob
>|||Hi
Try this
create proc myproc
as
set nocount on
declare @.row int
declare @.t table (col int)
insert into @.t select orderid from orders
select @.row=@.@.rowcount
select * from orders
go
exec myproc
"TomislaW" <tomislav147@.hotmail.com> wrote in message
news:OwLMrsjSFHA.248@.TK2MSFTNGP15.phx.gbl...
> it is not so simple
> my select is:
> SELECT Date1, Date2, Neto, Provision
> FROM TERMIN
> WHERE (ID = @.ID)
> AND (Date1>= @.Date1 AND DatumDo <= @.Date2)
> GROUP BY Date1, Date2, Neto, Provision
> HAVING (MAX(BedsNo) >= @.BedsNo)
> i get 2 rows
> with count i get number 3
> "Rob Farley" <RobFarley@.discussions.microsoft.com> wrote in message
> news:E655A96C-643E-40F1-B045-D6F3DC713737@.microsoft.com...
>|||What ar you doing with the data returned from the first two selects? Why
are you even executing them if you don;t want the results passed back to the
client?
Either you want to use the data as a parameter value in the last Select, or
to decide whether or not to even run the last Select. Either way, The Outpu
t
of a Select statement in a Stored Proc is either returned to the client or
not returned, depending on whether the output values are being assigned to
T-SQL Variables or not. If even one output value is NOT being assigned t oa
T-SQL Variable, then the Output will be returned t othe CLient.
Select @.VarA = <expresssionA>, @.Varb = <ExpressionB>, <ExpressionC>, etc.
From ...
If ALL The output values are being assigned to T-SQL Variables, then the
result set will NOT be sent back to the client.
Select @.VarA = <ExpresssionA>,
@.Varb = <ExpressionB>,
@.VarC = <ExpressionC>
From ...
In the latter case, you have to be careful that the Select only generates
one row, because if it generates more than one, then the T-SQL Variables wil
l
be populated with the values in the Last Row of the resultset, which, withou
t
an Order By, may not be absolutely determinisitic,
"TomislaW" wrote:
> I have 3 selects in my stored procedure
> I am using first and second select just for calculating number of rows
> (@.@.ROWCOUNT), and last one is the final select that I need. But I get all
> three selects
>
> Tomislaw
>
>
>|||There should be no reason why you can't get the same result with COUNT as
with @.@.ROWCOUNT:
SELECT COUNT(*)
FROM
(SELECT NULL
FROM termin
WHERE id = @.id
AND date1 >= @.date1
AND datumdo <= @.date2
GROUP BY date1, date2, neto, provision
HAVING MAX(bedsno) >= @.bedsno)T(x)
If you still have a problem then please post DDL as well as your query so
that we can test it out.
David Portas
SQL Server MVP
--|||The issue with count(*) in your original context, Tomislaw, is that the
"having" filter is applied after the aggregates are calculated. Therefore,
you could get a different solution. But using count(*) is still the right
way, you just need to nest it as in David's example.
He puts 'select null', because there's no point in returning a whole bunch
of rows in a subquery where you're only interested in how many rows there ar
e.
You should find that David's example works veryw ell.
Rob|||"Rob Farley" <RobFarley@.discussions.microsoft.com> wrote in message
news:ED19C5E3-A554-4976-B0E0-4C9631A95C78@.microsoft.com...
> The issue with count(*) in your original context, Tomislaw, is that the
> "having" filter is applied after the aggregates are calculated. Therefore,
> you could get a different solution. But using count(*) is still the right
> way, you just need to nest it as in David's example.
> He puts 'select null', because there's no point in returning a whole bunch
> of rows in a subquery where you're only interested in how many rows there
> are.
> You should find that David's example works veryw ell.
> Rob
Thanks to you and David
TomislaW
How to return 'error' if no rows are found?
I am stuck with this one...
I have a rather simple table with ZIP-codes and a responsible branch-office. When I enter a zip-code, I recieve the branch-city, just as designed. But, I need the text 'error' returned if the zip-code is not valid. I don't know about the USA, but in Austria, EU, there are about 2300 valid 4-number zip-codes, and 6700 unused codes.
There is an application which accesses the SQL 2000 server by ODBC, and that application needs a value returned. This application sends a SQL query to the server, and interprets the return value.
Example:
1100 Wien
1200 Wien
2345 Linz
When queried for '1200', 'Wien' should return (this works of course), but when '1234' is queried, 'error' should return...
Can someone help me, or point me in th right direction?
SELECT COALESCE((SELECT DISTINCT City FROM Person.Address
WHERE PostalCode = 'MyPostalCode') , 'ERROR')
|||Thanks! that was the clue! Now I can use"SELECT COALESCE ( ( SELECT Route FROM qry_PLZ_Route WHERE plz = 1100 ) , -1 ) AS Route" (plz is german abbr for zipcode) in the application, which is manageable.
Thanks for your help!
Friday, March 9, 2012
How to return a range of rows?
rows? For example:
-- tblContact
-- (
-- SSN char(9),
-- FirstName varchar(50),
-- LastName varchar(50)
-- )
-- This table contains 500 rows.
Select * from tblContact -- Return only rows 5 through 10
Thanks"Briniken" <briniken@.yahoo.com> wrote in message
news:68dae6d3.0311012131.6f9faf26@.posting.google.c om...
> How can a SQL statement be written to return a specified range of
> rows? For example:
> -- tblContact
> -- (
> -- SSN char(9),
> -- FirstName varchar(50),
> -- LastName varchar(50)
> -- )
> -- This table contains 500 rows.
> Select * from tblContact -- Return only rows 5 through 10
> Thanks
Data in tables doesn't have any order, so you have to decide how to say
which are the 'first' 10 rows. Assuming that you want rows 5 to 10 when
ordered by LastName, then this is one possible solution:
select top 5 * from
(
select top 10 *
from tblContact
order by LastName asc) dt
order by LastName desc
Alternatively, you can look at the first example in this KB article:
http://support.microsoft.com/defaul...kb;en-us;186133
If you add "having count(*) between 5 and 10" to the query, you should also
get the results you want.
Simon|||Hi
There is not equivalent of a row number in SQL Server, therefore you need to
be able to order the values, but something like
SELECT TOP 5 SSN. FirstName, LastName FROM
( SELECT TOP 10 SSN. FirstName, LastName FROM tblContact ORDER BY SSN ASC )
A
ORDER BY SSN DESC
Will give you the rows, but not in order!
Also check out the solution in the following thread
http://groups.google.com/groups?hl=...Newsposts%2BTOP
John
"Briniken" <briniken@.yahoo.com> wrote in message
news:68dae6d3.0311012131.6f9faf26@.posting.google.c om...
> How can a SQL statement be written to return a specified range of
> rows? For example:
> -- tblContact
> -- (
> -- SSN char(9),
> -- FirstName varchar(50),
> -- LastName varchar(50)
> -- )
> -- This table contains 500 rows.
> Select * from tblContact -- Return only rows 5 through 10
> Thanks
How to return a range of rows in sql server
John Bell posted a reply on 2003-11-02 04:11:02 PST, that gave me an
idea how to achieve paging in sql server without row number
functionality. Thank you John. The following works for me, not very
eficient though:
SELECT * FROM
( SELECT top 5 * FROM
( SELECT top 10 * FROM
( SELECT top 10 *
FROM dft_document
ORDER BY documentkey ASC
) a
ORDER BY documentkey DESC
) b
) d
ORDER BY documentKey ASC
The innermost SELECT gives 10 rows out of which last 5 needed.
regardsSeveral alternative methods described here:
www.aspfaq.com/2120
--
David Portas
SQL Server MVP
--|||"Alex Ravvin" <alexravv@.hotmail.com> wrote in message
news:f497c8a4.0401291050.175bcef0@.posting.google.c om...
> Hello,
> John Bell posted a reply on 2003-11-02 04:11:02 PST, that gave me an
> idea how to achieve paging in sql server without row number
> functionality. Thank you John. The following works for me, not very
> eficient though:
> SELECT * FROM
> ( SELECT top 5 * FROM
> ( SELECT top 10 * FROM
> ( SELECT top 10 *
> FROM dft_document
> ORDER BY documentkey ASC
> ) a
> ORDER BY documentkey DESC
> ) b
> ) d
> ORDER BY documentKey ASC
> The innermost SELECT gives 10 rows out of which last 5 needed.
> regards
You can simplify this to
SELECT *
FROM (SELECT TOP 5 *
FROM (SELECT TOP 10 *
FROM dft_document
ORDER BY documentkey ASC) AS T10
ORDER BY documentkey DESC) AS T5
ORDER BY documentkey ASC
Regards,
jag
How To Return A "Range Of Rows"?
How does one return a range of rows.
I know that "Top 5" will return rows 0 - 5
but, how do I get 6 - 10?
thanks"pbd22" <dushkin@.gmail.comwrote in message
news:1176393322.377665.40770@.y5g2000hsa.googlegrou ps.com...
Quote:
Originally Posted by
Hi.
>
How does one return a range of rows.
I know that "Top 5" will return rows 0 - 5
but, how do I get 6 - 10?
Depends partly on which version of SQL Server you're using.
2000 or 2005?
2000, you need something like
select top 5 orderid from dbo.orders where orderid in
(select top 10 orderid from dbo.orders order by orderid) order by orderid
desc
for 2005 something like:
with OrdersCTE as
(
select row_number() over (order by orderid) as rownum, *
from dbo.orders
)
select * from OrdersCTE where rownum between 5 and 10
(obviously don't use * in your actual production code)
Quote:
Originally Posted by
>
thanks
>
--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||On Apr 12, 8:55 am, "pbd22" <dush...@.gmail.comwrote:
Quote:
Originally Posted by
Hi.
>
How does one return a range of rows.
I know that "Top 5" will return rows 0 - 5
but, how do I get 6 - 10?
>
thanks
Hi.
I am following up my own message with more detailed info.
If some """kind""" soul could tell me how to isolate a range
of rows for each of the following conditions I would really
(**really**)
apprecaite it. The SQL is dynamically generated based on user
requirements. The resulting statements vary wildly but, the below
three
look more-or-less like the rest of them:
I REALLY appreciate your help. Thanks!
----------------------------------
EXAMPLE ONE (ORDERBY CASE STATEMENT):
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate from
( select distinct postalAddress from Profiles union select distinct
name from ProfilesPictures union select distinct postaladdress from
ChangeSettings union select distinct postaladdress from LastSignIn )
drv Left Join Profiles tab1 on (drv.postalAddress =
tab1.postalAddress) Left Join ProfilesPictures tab2 on
(drv.postalAddress = tab2.name) Left Join LastSignIn tab4 on
(drv.postalAddress = tab4.postaladdress) Left Join ChangeSettings tab3
on (drv.postalAddress = tab3.postaladdress) where tab1.sex='men' and
tab1.bdayyear between '0' and '1988' and tab2.photodefault = 1 or
tab2.nophoto = 1 order by CASE WHEN userID=67 THEN 1 WHEN userID=103
THEN 2 WHEN userID=102 THEN 3 WHEN userID=81 THEN 4 WHEN userID=94
THEN 5 WHEN userID=87 THEN 6 WHEN userID=104 THEN 7 WHEN userID=82
THEN 8 WHEN userID=54 THEN 9 WHEN userID=64 THEN 10 WHEN userID=63
THEN 11 WHEN userID=6 THEN 12 WHEN userID=58 THEN 13 WHEN userID=100
THEN 14 WHEN userID=96 THEN 15 WHEN userID=70 THEN 16 WHEN userID=98
THEN 17 WHEN userID=69 THEN 18 WHEN userID=92 THEN 19 WHEN userID=93
THEN 20 WHEN userID=68 THEN 21 WHEN userID=65 THEN 22 WHEN userID=86
THEN 23 WHEN userID=91 THEN 24 WHEN userID=80 THEN 25 WHEN userID=76
THEN 26 WHEN userID=73 THEN 27 WHEN userID=72 THEN 28 WHEN userID=74
THEN 29 WHEN userID=83 THEN 30 WHEN userID=84 THEN 31 WHEN userID=88
THEN 32 WHEN userID=75 THEN 33 WHEN userID=77 THEN 34 WHEN userID=78
THEN 35 WHEN userID=79 THEN 36 WHEN userID=61 THEN 37 WHEN userID=101
THEN 38 WHEN userID=97 THEN 39 WHEN userID=99 THEN 40 WHEN userID=95
THEN 41 WHEN userID=71 THEN 42 WHEN userID=85 THEN 43 WHEN userID=62
THEN 44 END ;
EXAMPLE TWO (ORDERBY "SOME COLUMN"... COULD BE DATE, TIME, NUMBER,
ETC. THIS IS ALWAYS ASCENDING):
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate ,
tab4.online from ( select distinct postalAddress from Profiles union
select distinct name from ProfilesPictures union select distinct
postaladdress from ChangeSettings union select distinct postaladdress
from LastSignIn ) drv Left Join Profiles tab1 on (drv.postalAddress =
tab1.postalAddress) Left Join ProfilesPictures tab2 on
(drv.postalAddress = tab2.name) Left Join LastSignIn tab4 on
(drv.postalAddress = tab4.postaladdress) Left Join ChangeSettings tab3
on (drv.postalAddress = tab3.postaladdress) where tab1.bdayyear
between '0' and '1988' and tab2.photodefault = 1 or tab2.nophoto = 1
order by tab1.registerDate ;
EXAMPLE THREE (ORDERBY LAST TIME LOGGED IN - ALWAYS DESCENDING):
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate ,
tab4.online from ( select distinct postalAddress from Profiles union
select distinct name from ProfilesPictures union select distinct
postaladdress from ChangeSettings union select distinct postaladdress
from LastSignIn ) drv Left Join Profiles tab1 on (drv.postalAddress =
tab1.postalAddress) Left Join ProfilesPictures tab2 on
(drv.postalAddress = tab2.name) Left Join LastSignIn tab4 on
(drv.postalAddress = tab4.postaladdress) Left Join ChangeSettings tab3
on (drv.postalAddress = tab3.postaladdress) where tab1.bdayyear
between '0' and '1989' and tab2.photodefault = 1 and not tab2.nophoto
= 1 order by tab4.signindate DESC ;|||On 12 Apr 2007 11:46:57 -0700, pbd22 wrote:
Quote:
Originally Posted by
>I am following up my own message with more detailed info.
>If some """kind""" soul could tell me how to isolate a range
>of rows for each of the following conditions I would really
>(**really**)
>apprecaite it.
Hi pbd22,
Some kind sould has even written a whole web page full of methods to
achieve this. The first part of the page focuses on ASP techniques, but
the second part covers DB techniques for paging.
http://databases.aspfaq.com/databas...-recordset.html
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||On Apr 12, 11:46 am, "pbd22" <dush...@.gmail.comwrote:
Quote:
Originally Posted by
On Apr 12, 8:55 am, "pbd22" <dush...@.gmail.comwrote:
>
Quote:
Originally Posted by
Hi.
>
Quote:
Originally Posted by
How does one return a range of rows.
I know that "Top 5" will return rows 0 - 5
but, how do I get 6 - 10?
>
Quote:
Originally Posted by
thanks
>
Hi.
>
I am following up my own message with more detailed info.
If some """kind""" soul could tell me how to isolate a range
of rows for each of the following conditions I would really
(**really**)
apprecaite it. The SQL is dynamically generated based on user
requirements. The resulting statements vary wildly but, the below
three
look more-or-less like the rest of them:
>
I REALLY appreciate your help. Thanks!
>
----------------------------------
>
EXAMPLE ONE (ORDERBY CASE STATEMENT):
>
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate from
( select distinct postalAddress from Profiles union select distinct
name from ProfilesPictures union select distinct postaladdress from
ChangeSettings union select distinct postaladdress from LastSignIn )
drv Left Join Profiles tab1 on (drv.postalAddress =
tab1.postalAddress) Left Join ProfilesPictures tab2 on
(drv.postalAddress = tab2.name) Left Join LastSignIn tab4 on
(drv.postalAddress = tab4.postaladdress) Left Join ChangeSettings tab3
on (drv.postalAddress = tab3.postaladdress) where tab1.sex='men' and
tab1.bdayyear between '0' and '1988' and tab2.photodefault = 1 or
tab2.nophoto = 1 order by CASE WHEN userID=67 THEN 1 WHEN userID=103
THEN 2 WHEN userID=102 THEN 3 WHEN userID=81 THEN 4 WHEN userID=94
THEN 5 WHEN userID=87 THEN 6 WHEN userID=104 THEN 7 WHEN userID=82
THEN 8 WHEN userID=54 THEN 9 WHEN userID=64 THEN 10 WHEN userID=63
THEN 11 WHEN userID=6 THEN 12 WHEN userID=58 THEN 13 WHEN userID=100
THEN 14 WHEN userID=96 THEN 15 WHEN userID=70 THEN 16 WHEN userID=98
THEN 17 WHEN userID=69 THEN 18 WHEN userID=92 THEN 19 WHEN userID=93
THEN 20 WHEN userID=68 THEN 21 WHEN userID=65 THEN 22 WHEN userID=86
THEN 23 WHEN userID=91 THEN 24 WHEN userID=80 THEN 25 WHEN userID=76
THEN 26 WHEN userID=73 THEN 27 WHEN userID=72 THEN 28 WHEN userID=74
THEN 29 WHEN userID=83 THEN 30 WHEN userID=84 THEN 31 WHEN userID=88
THEN 32 WHEN userID=75 THEN 33 WHEN userID=77 THEN 34 WHEN userID=78
THEN 35 WHEN userID=79 THEN 36 WHEN userID=61 THEN 37 WHEN userID=101
THEN 38 WHEN userID=97 THEN 39 WHEN userID=99 THEN 40 WHEN userID=95
THEN 41 WHEN userID=71 THEN 42 WHEN userID=85 THEN 43 WHEN userID=62
THEN 44 END ;
>
EXAMPLE TWO (ORDERBY "SOME COLUMN"... COULD BE DATE, TIME, NUMBER,
ETC. THIS IS ALWAYS ASCENDING):
>
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate ,
tab4.online from ( select distinct postalAddress from Profiles union
select distinct name from ProfilesPictures union select distinct
postaladdress from ChangeSettings union select distinct postaladdress
from LastSignIn ) drv Left Join Profiles tab1 on (drv.postalAddress =
tab1.postalAddress) Left Join ProfilesPictures tab2 on
(drv.postalAddress = tab2.name) Left Join LastSignIn tab4 on
(drv.postalAddress = tab4.postaladdress) Left Join ChangeSettings tab3
on (drv.postalAddress = tab3.postaladdress) where tab1.bdayyear
between '0' and '1988' and tab2.photodefault = 1 or tab2.nophoto = 1
order by tab1.registerDate ;
>
EXAMPLE THREE (ORDERBY LAST TIME LOGGED IN - ALWAYS DESCENDING):
>
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate ,
tab4.online from ( select distinct postalAddress from Profiles union
select distinct name from ProfilesPictures union select distinct
postaladdress from ChangeSettings union select distinct postaladdress
from LastSignIn ) drv Left Join Profiles tab1 on (drv.postalAddress =
tab1.postalAddress) Left Join ProfilesPictures tab2 on
(drv.postalAddress = tab2.name) Left Join LastSignIn tab4 on
(drv.postalAddress = tab4.postaladdress) Left Join ChangeSettings tab3
on (drv.postalAddress = tab3.postaladdress) where tab1.bdayyear
between '0' and '1989' and tab2.photodefault = 1 and not tab2.nophoto
= 1 order by tab4.signindate DESC ;
Thanks Greg!
I "am" using 2005 and the solution looks much easier than the 2000
alternatives.
I am not sure why, but the second message I posted in this thread was
right after the first but it appeared after your response. Regardless,
as you can see my queries are somewhat complicated and I am not quite
sure how to apply your 2005 solution (OrdersCTE) to them. I am
wondering if you could use one of my queries to demonstrate how it
works (I hope I am not being too demanding)?
It would help me get my mind wrapped around things.
Thanks kindly for your time.
Peter|||pbd22 (dushkin@.gmail.com) writes:
Quote:
Originally Posted by
I "am" using 2005 and the solution looks much easier than the 2000
alternatives.
I am not sure why, but the second message I posted in this thread was
right after the first but it appeared after your response. Regardless,
as you can see my queries are somewhat complicated and I am not quite
sure how to apply your 2005 solution (OrdersCTE) to them. I am
wondering if you could use one of my queries to demonstrate how it
works (I hope I am not being too demanding)?
It would help me get my mind wrapped around things.
WITH CTE (
SELECT <yourselectlistgoeshere>,
rownum = row_number() over( ORDER BY <yourorderbylisthere>)
FROM <yourfrom+joinshere>
WHERE <anywhereclauseyoumayhav>
)
SELECT <yourselectlisthereagain, nowwithoutaliases>
FROM CTE
WHERE rownum BETWEEN @.first AND @.last
ORDER BY rownum
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||On Apr 12, 1:38 pm, Hugo Kornelis
<h...@.perFact.REMOVETHIS.info.INVALIDwrote:
Quote:
Originally Posted by
On 12 Apr 2007 11:46:57 -0700, pbd22 wrote:
>
Quote:
Originally Posted by
I am following up my own message with more detailed info.
If some """kind""" soul could tell me how to isolate a range
of rows for each of the following conditions I would really
(**really**)
apprecaite it.
>
Hi pbd22,
>
Some kind sould has even written a whole web page full of methods to
achieve this. The first part of the page focuses on ASP techniques, but
the second part covers DB techniques for paging.
>
http://databases.aspfaq.com/databas...ough-a-recordse...
>
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog:http://sqlblog.com/blogs/hugo_kornelis
Thanks Hugo (horay for kind souls).
I will go through this in detail after I get home. But, for now,
I am wondering if it is more cost-effective to do the paging logic
on the client or the server? I have already written all my paging
logic
in javascript (basically, what that link provides, but in javascript).
Do
I save on performance by moving the paging away from the server
or do you think it matters?
Thanks again.|||"pbd22" <dushkin@.gmail.comwrote in message
news:1176412970.235762.124510@.n76g2000hsh.googlegr oups.com...
Quote:
Originally Posted by
>
Thanks Hugo (horay for kind souls).
I will go through this in detail after I get home. But, for now,
I am wondering if it is more cost-effective to do the paging logic
on the client or the server? I have already written all my paging
logic
in javascript (basically, what that link provides, but in javascript).
Do
I save on performance by moving the paging away from the server
or do you think it matters?
Depends, how many rows are you returning to the client?
You generally want to return as little data to the client as necessary. Of
course "necessary" changes for every application.
Quote:
Originally Posted by
>
Thanks again.
>
--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||pbd22 wrote:
Quote:
Originally Posted by
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate from
Why the hell doesn't anyone format their queries for readability?
Quote:
Originally Posted by
order by CASE WHEN userID=67 THEN 1 WHEN userID=103
THEN 2 WHEN userID=102 THEN 3 WHEN userID=81 THEN 4 WHEN userID=94
THEN 5 WHEN userID=87 THEN 6 WHEN userID=104 THEN 7 WHEN userID=82
THEN 8 WHEN userID=54 THEN 9 WHEN userID=64 THEN 10 WHEN userID=63
THEN 11 WHEN userID=6 THEN 12 WHEN userID=58 THEN 13 WHEN userID=100
This should be driven by a Users table. Do you really want to mess
around with altering the query every time a user is added/removed?|||pbd22 (dushkin@.gmail.com) writes:
Quote:
Originally Posted by
I will go through this in detail after I get home. But, for now,
I am wondering if it is more cost-effective to do the paging logic
on the client or the server? I have already written all my paging
logic in javascript (basically, what that link provides, but in
javascript). Do I save on performance by moving the paging away from the
server or do you think it matters?
Disclaimer: I have no personal experience of writing web apps, so take this
as a grain of salt.
If you can be sure that the search can never return more than, say, 1000
rows (and this can be acieved by using TOP), reading all rows in one go,
and then page from the web server is likely to be better, since else
there would be an access to the database each time the user presses next.
But if the search could hit tens of thousands of rows, you need to have
some sort of batching mechanism, because if 100 users do that at the same
time, your web server will choke.
And you should not send all rows at once to the browser, unless the user
requests to see all rows. If the browser is on a slow connection, that
can be painful.
Finally: don't forget to give the user the option to see at least 100 items
at once. I hate sites where I only get a spoonful at a time.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||On Apr 12, 6:50 pm, Ed Murphy <emurph...@.socal.rr.comwrote:
Quote:
Originally Posted by
pbd22 wrote:
Quote:
Originally Posted by
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate from
>
Why the hell doesn't anyone format their queries for readability?
>
Quote:
Originally Posted by
order by CASE WHEN userID=67 THEN 1 WHEN userID=103
THEN 2 WHEN userID=102 THEN 3 WHEN userID=81 THEN 4 WHEN userID=94
THEN 5 WHEN userID=87 THEN 6 WHEN userID=104 THEN 7 WHEN userID=82
THEN 8 WHEN userID=54 THEN 9 WHEN userID=64 THEN 10 WHEN userID=63
THEN 11 WHEN userID=6 THEN 12 WHEN userID=58 THEN 13 WHEN userID=100
>
This should be driven by a Users table. Do you really want to mess
around with altering the query every time a user is added/removed?
good point Ed. I didn't think of that. I'll obviously have to do that
- yet
another thing on the "to-do list". thanks...|||On Apr 13, 4:18 pm, "pbd22" <dush...@.gmail.comwrote:
Quote:
Originally Posted by
On Apr 12, 6:50 pm, Ed Murphy <emurph...@.socal.rr.comwrote:
>
>
>
Quote:
Originally Posted by
pbd22 wrote:
Quote:
Originally Posted by
select coalesce (tab1.postalAddress, tab2.name, tab3.postaladdress,
tab4.postaladdress) id , tab1.bdayday , tab1.bdaymonth ,
tab1.bdayyear , tab1.sex , tab1.zipCode , tab1.siteId , tab1.userID ,
tab2.photolocation , tab2.photoname , tab2.photodefault ,
tab2.nophoto , tab3.headline , tab3.aboutme , tab4.signindate from
>
Quote:
Originally Posted by
Why the hell doesn't anyone format their queries for readability?
>
Quote:
Originally Posted by
Quote:
Originally Posted by
order by CASE WHEN userID=67 THEN 1 WHEN userID=103
THEN 2 WHEN userID=102 THEN 3 WHEN userID=81 THEN 4 WHEN userID=94
THEN 5 WHEN userID=87 THEN 6 WHEN userID=104 THEN 7 WHEN userID=82
THEN 8 WHEN userID=54 THEN 9 WHEN userID=64 THEN 10 WHEN userID=63
THEN 11 WHEN userID=6 THEN 12 WHEN userID=58 THEN 13 WHEN userID=100
>
Quote:
Originally Posted by
This should be driven by a Users table. Do you really want to mess
around with altering the query every time a user is added/removed?
>
good point Ed. I didn't think of that. I'll obviously have to do that
- yet
another thing on the "to-do list". thanks...
Hi All.
So, I have taken all of your advice and turned my code into a stored
procedure that has a dynamic ORDER BY clause for user deletions.
This is turning into a bit of a beast and I am getting well out of my
comfort zone.
I have taken Hugo's advice and moved paging from the client to the
server (or, at least, tried to). I have based my sproc on the RowCount
code in the link he provided. I have also taken Ed's advice and made
my ORDER BY clause table-based for the CASE logic.
I have pasted the code below (sorry if i offend anybody about
formatting.
I am not sure how to format code here... suggestions?). When I use
Query Analyzer and step through the code in "debug" mode, the compiler
jumps to the following line:
---------
SET ROWCOUNT 0
---------
and throws this error:
----------------------------
CurrentPage TotalPages TotalRows
---- ---- ----
0 0 0
Server: Msg 507, Level 16, State 2, Procedure sp_SearchRowCount, Line
60
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid argument for
SET ROWCOUNT. Must be a non-null non-negative integer.
@.RETURN_VALUE = -6
----------------------------
Could somebody tell me what about the logic in my code is causing this
failure (I know that the value is null and that that is causing the
error). I have a feeling it might have to do with the following lines
of code that I have commented out in the WHERE clause (but, I am not
sure what it is doing or how to add the logic to my own code):
-- ArtistName + '~' + Title
-- >= @.aname + '~' + @.title
Other feedback appreciated also. I really appreciate your help!
Thanks.
----------------------------
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER PROCEDURE [dbo].[sp_SearchRowCount]
@.pagenum INT = 1,
@.perpage INT = 10
AS
BEGIN
SET NOCOUNT ON
DECLARE
@.ubound INT,
@.lbound INT,
@.pages INT,
@.rows INT
SELECT
@.rows = COUNT(*),
@.pages = COUNT(*) / @.perpage
FROM
(select distinct emailAddress
from Customers with(nolock) union select distinct user_name
from Photos with(nolock) union select distinct email_address
from Edit with(nolock) union select distinct email_address
from Searches with(nolock) union select distinct email_address
from Precedence with(nolock) union select distinct
email_address
from LoginDate with(nolock)) drv
Left Join Customers tab1 on (drv.emailAddress =
tab1.emailAddress)
Inner Join Precedence tab5 on tab5.UserID=tab1.UserID
Left Join Photos tab2 on (drv.emailAddress = tab2.user_name)
Left Join LoginDate tab4 on (drv.emailAddress =
tab4.email_address)
Left Join Edit tab3 on (drv.emailAddress = tab3.email_address)
Left Join Searches tab6 on (drv.emailAddress =
tab6.email_address)
IF @.rows % @.perpage != 0 SET @.pages = @.pages + 1
IF @.pagenum < 1 SET @.pagenum = 1
IF @.pagenum @.pages SET @.pagenum = @.pages
SET @.ubound = @.perpage * @.pagenum
SET @.lbound = @.ubound - (@.perpage - 1)
SELECT
CurrentPage = @.pagenum,
TotalPages = @.pages,
TotalRows = @.rows
-- this method determines the string values
-- for the first desired row, then sets the
-- rowcount to get it, plus the next n rows
DECLARE
@.gender VARCHAR(50),
@.country VARCHAR(50),
@.orderby INTEGER,
@.low VARCHAR(50),
@.high VARCHAR(50),
@.photo VARCHAR(50),
@.sort INTEGER
SET ROWCOUNT @.lbound
SELECT
@.gender = saved_sex,
@.country = saved_country,
@.orderby = saved_orderby,
@.low = saved_fage,
@.high = saved_tage,
@.sort = saved_sort,
@.photo = saved_photo_string
FROM
(select distinct emailAddress
from Customers with(nolock) union select distinct user_name
from Photos with(nolock) union select distinct email_address
from Edit with(nolock) union select distinct email_address
from Searches with(nolock) union select distinct email_address
from Precedence with(nolock) union select distinct
email_address
from LoginDate with(nolock)) drv
Left Join Customers tab1 on (drv.emailAddress =
tab1.emailAddress)
Inner Join Precedence tab5 on tab5.UserID=tab1.UserID
Left Join Photos tab2 on (drv.emailAddress = tab2.user_name)
Left Join LoginDate tab4 on (drv.emailAddress =
tab4.email_address)
Left Join Edit tab3 on (drv.emailAddress = tab3.email_address)
Left Join Searches tab6 on (drv.emailAddress =
tab6.email_address)
ORDER BY CASE @.sort
WHEN 1 THEN tab1.registerDate
WHEN 2 THEN tab3.edit_date
WHEN 3 THEN tab4.login_date
WHEN 4 THEN tab5.up_order
END DESC
SET ROWCOUNT @.perPage
SELECT COALESCE
(
tab1.emailAddress,
tab2.user_name,
tab3.email_address,
tab4.email_address,
tab5.email_address,
tab6.email_address
)
id ,
tab1.bday_day ,
tab1.bday_month ,
tab1.bday_year ,
tab1.gender ,
tab1.zipCode ,
tab1.siteId ,
tab1.userID ,
tab2.photo_location ,
tab2.photo_name ,
tab2.photo_default ,
tab2.no_photo ,
tab3.headline ,
tab3.about_me ,
tab4.login_date ,
tab4.login_isonline,
tab5.up_order,
tab6.saved_orderby,
tab6.saved_sort,
tab6.saved_fage,
tab6.saved_tage
FROM
(select distinct emailAddress
from Customers with(nolock) union select distinct user_name
from Photos with(nolock) union select distinct email_address
from Edit with(nolock) union select distinct email_address
from Searches with(nolock) union select distinct email_address
from Precedence with(nolock) union select distinct
email_address
from LoginDate with(nolock)) drv
Left Join Customers tab1 on (drv.emailAddress =
tab1.emailAddress)
Inner Join Precedence tab5 on tab5.UserID=tab1.UserID
Left Join Photos tab2 on (drv.emailAddress = tab2.user_name)
Left Join LoginDate tab4 on (drv.emailAddress =
tab4.email_address)
Left Join Edit tab3 on (drv.emailAddress = tab3.email_address)
Left Join Searches tab6 on (drv.emailAddress =
tab6.email_address)
WHERE
tab1.gender = @.gender
AND tab1.country = @.country
AND tab1.bday_year BETWEEN @.low AND @.high
AND tab2.photo_default = 1 + @.photo
-- ArtistName + '~' + Title
-- >= @.aname + '~' + @.title
ORDER BY CASE @.sort
WHEN 1 THEN tab1.registerDate
WHEN 2 THEN tab3.edit_date
WHEN 3 THEN tab4.login_date
WHEN 4 THEN tab5.up_order
END DESC
SET ROWCOUNT 0
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO|||On 18 Apr 2007 06:12:44 -0700, pbd22 wrote:
Quote:
Originally Posted by
>I have pasted the code below (sorry if i offend anybody about
>formatting.
>I am not sure how to format code here... suggestions?). When I use
>Query Analyzer and step through the code in "debug" mode, the compiler
>jumps to the following line:
>
>---------
>SET ROWCOUNT 0
>---------
>
>and throws this error:
>
>----------------------------
>
>CurrentPage TotalPages TotalRows
>---- ---- ----
>0 0 0
>
>Server: Msg 507, Level 16, State 2, Procedure sp_SearchRowCount, Line
>60
>[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid argument for
>SET ROWCOUNT. Must be a non-null non-negative integer.
>
>@.RETURN_VALUE = -6
>----------------------------
>
>Could somebody tell me what about the logic in my code is causing this
>failure (I know that the value is null and that that is causing the
>error). I have a feeling it might have to do with the following lines
>of code that I have commented out in the WHERE clause (but, I am not
>sure what it is doing or how to add the logic to my own code):
Hi pbd22,
Since those commented lines are *AFTER* the place where the error occurs
(the debugger jumps to the incorrect line; the only line that can cause
this error is either this one:
Quote:
Originally Posted by
SET ROWCOUNT @.lbound
or this one:
Quote:
Originally Posted by
SET ROWCOUNT @.perPage
I assume that it's the first, and that it's cause by some unexpected
things going on in the calculations neede to compute @.lbound.
You already have added a great statement to aid in debugging; I'm gonna
ask you to add a bit more to it - so please change this:
Quote:
Originally Posted by
SELECT
>
CurrentPage = @.pagenum,
TotalPages = @.pages,
TotalRows = @.rows
to this:
SELECT
CurrentPage = @.pagenum,
PageSize = @.perpage,
TotalPages = @.pages,
TotalRows = @.rows,
UpperBoundary = @.ubound,
LowerBoundary = @.lbound
And then rerun the query and post back the results. We'll then have to
take it from there.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||On Apr 18, 8:08 am, Hugo Kornelis
<h...@.perFact.REMOVETHIS.info.INVALIDwrote:
Quote:
Originally Posted by
On 18 Apr 2007 06:12:44 -0700, pbd22 wrote:
>
>
>
Quote:
Originally Posted by
I have pasted the code below (sorry if i offend anybody about
formatting.
I am not sure how to format code here... suggestions?). When I use
Query Analyzer and step through the code in "debug" mode, the compiler
jumps to the following line:
>
Quote:
Originally Posted by
---------
SET ROWCOUNT 0
---------
>
Quote:
Originally Posted by
and throws this error:
>
Quote:
Originally Posted by
----------------------------
>
Quote:
Originally Posted by
CurrentPage TotalPages TotalRows
---- ---- ----
0 0 0
>
Quote:
Originally Posted by
Server: Msg 507, Level 16, State 2, Procedure sp_SearchRowCount, Line
60
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid argument for
SET ROWCOUNT. Must be a non-null non-negative integer.
>
Quote:
Originally Posted by
@.RETURN_VALUE = -6
----------------------------
>
Quote:
Originally Posted by
Could somebody tell me what about the logic in my code is causing this
failure (I know that the value is null and that that is causing the
error). I have a feeling it might have to do with the following lines
of code that I have commented out in the WHERE clause (but, I am not
sure what it is doing or how to add the logic to my own code):
>
Hi pbd22,
>
Since those commented lines are *AFTER* the place where the error occurs
(the debugger jumps to the incorrect line; the only line that can cause
this error is either this one:
>
Quote:
Originally Posted by
SET ROWCOUNT @.lbound
>
or this one:
>
Quote:
Originally Posted by
SET ROWCOUNT @.perPage
>
I assume that it's the first, and that it's cause by some unexpected
things going on in the calculations neede to compute @.lbound.
>
You already have added a great statement to aid in debugging; I'm gonna
ask you to add a bit more to it - so please change this:
>
Quote:
Originally Posted by
SELECT
>
Quote:
Originally Posted by
CurrentPage = @.pagenum,
TotalPages = @.pages,
TotalRows = @.rows
>
to this:
>
SELECT
>
CurrentPage = @.pagenum,
PageSize = @.perpage,
TotalPages = @.pages,
TotalRows = @.rows,
UpperBoundary = @.ubound,
LowerBoundary = @.lbound
>
And then rerun the query and post back the results. We'll then have to
take it from there.
>
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog:http://sqlblog.com/blogs/hugo_kornelis
Hi Hugo,
Thanks for your reply. I have made the changes you suggested and got
the following output:
CurrentPage PageSize TotalPages TotalRows UpperBoundary
LowerBoundary
----...... ---- ..... ---- ....
---- ......... ---- ......----
0 ...... 10 ........ 0 ....
0 ......... 0 ...... -9
Server: Msg 507, Level 16, State 2, Procedure sp_PeopleSearch, Line 63
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid argument for
SET ROWCOUNT. Must be a non-null non-negative integer.|||On 18 Apr 2007 09:10:16 -0700, pbd22 wrote:
(snip)
Quote:
Originally Posted by
>Thanks for your reply. I have made the changes you suggested and got
>the following output:
>
>CurrentPage PageSize TotalPages TotalRows UpperBoundary
>LowerBoundary
>----...... ---- ..... ---- ....
>---- ......... ---- ......----
>0 ...... 10 ........ 0 ....
>0 ......... 0 ...... -9
>
>
>
>Server: Msg 507, Level 16, State 2, Procedure sp_PeopleSearch, Line 63
>[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid argument for
>SET ROWCOUNT. Must be a non-null non-negative integer.
Hi pbd22,
Thanks. This makes a lot clear.
Obviously, there are no rows returned by your query. Or to be more
precies - by the first copy of your query. You will have noted that you
have multiple copies of the same query in the procedure; the first copy
uses "SELECT @.rows = COUNT(*), @.pages = COUNT(*) / @.perpage" to find the
total number of rows in the query. Since @.rows is only set here, and it
is shown to be 0 in the results above, the query obviously returns no
rows. That means that either the query you want to run in a paged mode
does in fact not return any rows, or that you made a mistake when making
the extra copies of this query.
After this row-counting, some calculations are done:
(1) IF @.rows % @.perpage != 0 SET @.pages = @.pages + 1
(2) IF @.pagenum < 1 SET @.pagenum = 1
(3) IF @.pagenum @.pages SET @.pagenum = @.pages
(4) SET @.ubound = @.perpage * @.pagenum
(5) SET @.lbound = @.ubound - (@.perpage - 1)
Line 1: The value of @.perpage is rounded down in the query; this line
corrects that to rounding up. I'd have done that a little differently,
but that's mostly a matter of taste, and it works.
Line 2: In case someone passed a page number of zero or less to the
procedure, set it to 1. This is to prevent erroneous results.
Line 3: Another sanity check - if the page number passed to the proc
exceeds the actual number of pages, set it to the highest actual page
number. In this case, with 0 rows, this sets the page number to 0;
exactly the value that line 2 attempts to prevent!! This is the source
of the error you received.
Lines 4 and 5: Based on the page number, calculate the number of the
first and the last row to display. For page number 1, these numbers
would have been 1 and 10. For page number 0, the calculation yields -9
and 0. As a result, the proc later tries to set a negative ROWCOUNT.
I _think_ that you can easily fix this by swapping lines 2 and 3. I have
not checked every bit of the proc, but I suggest that you simply try it
and see what happens. If this results in (different) problems, you'll
have to explicitly add code to handle the possibility of an empty result
set.
I have already sent a mail to the author of the aspfaq article I refered
you to earlier, asking him to correct this page.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||On Apr 18, 11:23 am, Hugo Kornelis
<h...@.perFact.REMOVETHIS.info.INVALIDwrote:
Quote:
Originally Posted by
On 18 Apr 2007 09:10:16 -0700, pbd22 wrote:
>
(snip)
>
Quote:
Originally Posted by
Thanks for your reply. I have made the changes you suggested and got
the following output:
>
Quote:
Originally Posted by
CurrentPage PageSize TotalPages TotalRows UpperBoundary
LowerBoundary
----...... ---- ..... ---- ....
---- ......... ---- ......----
0 ...... 10 ........ 0 ....
0 ......... 0 ...... -9
>
Quote:
Originally Posted by
Server: Msg 507, Level 16, State 2, Procedure sp_PeopleSearch, Line 63
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid argument for
SET ROWCOUNT. Must be a non-null non-negative integer.
>
Hi pbd22,
>
Thanks. This makes a lot clear.
>
Obviously, there are no rows returned by your query. Or to be more
precies - by the first copy of your query. You will have noted that you
have multiple copies of the same query in the procedure; the first copy
uses "SELECT @.rows = COUNT(*), @.pages = COUNT(*) / @.perpage" to find the
total number of rows in the query. Since @.rows is only set here, and it
is shown to be 0 in the results above, the query obviously returns no
rows. That means that either the query you want to run in a paged mode
does in fact not return any rows, or that you made a mistake when making
the extra copies of this query.
>
After this row-counting, some calculations are done:
>
(1) IF @.rows % @.perpage != 0 SET @.pages = @.pages + 1
(2) IF @.pagenum < 1 SET @.pagenum = 1
(3) IF @.pagenum @.pages SET @.pagenum = @.pages
>
(4) SET @.ubound = @.perpage * @.pagenum
(5) SET @.lbound = @.ubound - (@.perpage - 1)
>
Line 1: The value of @.perpage is rounded down in the query; this line
corrects that to rounding up. I'd have done that a little differently,
but that's mostly a matter of taste, and it works.
>
Line 2: In case someone passed a page number of zero or less to the
procedure, set it to 1. This is to prevent erroneous results.
>
Line 3: Another sanity check - if the page number passed to the proc
exceeds the actual number of pages, set it to the highest actual page
number. In this case, with 0 rows, this sets the page number to 0;
exactly the value that line 2 attempts to prevent!! This is the source
of the error you received.
>
Lines 4 and 5: Based on the page number, calculate the number of the
first and the last row to display. For page number 1, these numbers
would have been 1 and 10. For page number 0, the calculation yields -9
and 0. As a result, the proc later tries to set a negative ROWCOUNT.
>
I _think_ that you can easily fix this by swapping lines 2 and 3. I have
not checked every bit of the proc, but I suggest that you simply try it
and see what happens. If this results in (different) problems, you'll
have to explicitly add code to handle the possibility of an empty result
set.
>
I have already sent a mail to the author of the aspfaq article I refered
you to earlier, asking him to correct this page.
>
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog:http://sqlblog.com/blogs/hugo_kornelis
Hugo -
Good catch! I never would have found that. That was spot on - I am
sure
the author of the article will appreciate the correction. So, I got
these results
with the adjustment (the formatting is sloppy but the lines at the
bottom are supposed to be under each column title from the query's
results):
CurrentPage PageSize TotalPages TotalRows UpperBoundary
LowerBoundary
---- ---- ---- ---- ----
----
1 10 0 0 10 1
id
bday_day
bday_month
bday_year
gender
zipCode
siteId userID
photo_location
photo_name photo_default
no_photo headline
about_me
login_date login_isonline
up_order saved_orderby
saved_sort
saved_fage
saved_tage
----------------
----------------
----------------
----------------
----------------
----------------
---------------- ----
------------------------------
---------------- ----
--- ----------------
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------- -----
---- ----
----------------
----------------
----------------
@.RETURN_VALUE = 0
MY final question is - why don't I get any data returned with the
query? Shouldn't I be seeing results with the column headers? Or, is
this just to show that the query works in debug mode? Sorry - still
trying to learn my way around stored procedures.
Thanks again for your help.
Peter|||On 18 Apr 2007 11:57:53 -0700, pbd22 wrote:
(snip)
Quote:
Originally Posted by
>MY final question is - why don't I get any data returned with the
>query? Shouldn't I be seeing results with the column headers? Or, is
>this just to show that the query works in debug mode? Sorry - still
>trying to learn my way around stored procedures.
Hi Peter,
You're probably going to hate me for this, but my best guess is that
your tables simply don't contain any data that matches the criteria in
the trigger. I already hinted at this in my previous reply (though I
left a back door open for the possibilty that one of the queries
contained a copy/paste error).
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||Ah, yes. You were right Hugo. It was a problem with my select
statement.
Thanks again for your help, MUCH appreciated!
Cheers.
Peter
Hugo Kornelis wote:
Quote:
Originally Posted by
On 18 Apr 2007 11:57:53 -0700, pbd22 wrote:
>
(snip)
Quote:
Originally Posted by
MY final question is - why don't I get any data returned with the
query? Shouldn't I be seeing results with the column headers? Or, is
this just to show that the query works in debug mode? Sorry - still
trying to learn my way around stored procedures.
>
Hi Peter,
>
You're probably going to hate me for this, but my best guess is that
your tables simply don't contain any data that matches the criteria in
the trigger. I already hinted at this in my previous reply (though I
left a back door open for the possibilty that one of the queries
contained a copy/paste error).
>
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis
How to return 0 instead of null when using a sum function?
Hi,
I basically do not want to return a null value as a result of using a sum function (using sum against 0 rows).
Is there a common way to avoid this?
Thanx
Interesting you should ask. I was looking at the same problemyesterday. My results are displayed in a DataGrid and thankfully itdoesn't barf on the NULL values. It displays -1 instead. Of coursethat's still not desirable as the correct answer for SUM(nothing)should be 0 IMO.Let's hope someone has a suggestion.
|||You could use the ISNULL function to calculate a 0 whenever the SUM contains a NULL:
SELECT ISNULL(SUM(myColumn,0)) FROM myTable WHERE 0=1
|||
Or, as a slight variation, use ISNULL to replace the result of the SUM for instances where no rows result in an answer of NULL:
SELECT ISNULL(SUM(myColumn),0) FROM myTable WHERE 0 = 1
(Note the different parenthesis placement: tmorton's will replace any NULL value with zero BEFORE aggregation; mine will replace theentire result with 0 AFTER aggregation in the event of a NULL sum).
|||
pjmcb wrote:
Or, as a slight variation, use ISNULL to replace the result of the SUM for instances where no rows result in an answer of NULL:
SELECT ISNULL(SUM(myColumn),0) FROM myTable WHERE 0 = 1
(Note the different parenthesis placement: tmorton's will replace anyNULL value with zero BEFORE aggregation; mine will replace the entireresult with 0 AFTER aggregation in the event of a NULL sum).
Thank you for catching my typo pjmcb! What I actually posted is not even syntactically correct. :-)
I should have copied-and-pasted from Query Analyzer instead of retyping.
|||I didn't think you could do that, but I was too lazy to open up QA to test it out...
Wednesday, March 7, 2012
How to Retrieve the Rows where particular Column Data equals NULL
Hi all,
I have a datatable Employee which is containg columns Emp_ID, Emp_Name, Manager_ID
I want to retrieve all the rows whose Manager_ID=NULL
I wirte the query select * from Employee where Manager_ID=NULL
but it is not working. How to do this. Please help me.
with regards
Ravinder Reddy.K
You have to use IS operator on NULL..
select * from Employee where Manager_ID is NULL
remember,
NULL = NULL => always False
NULL IS NULL = > True
|||
>NULL = NULL => always False
Not always... this is dependent on the setting of ANSI_NULLS. Try the following as an example:
SET ANSI_NULLS ON
GO
SELECT CASE WHEN NULL = NULL THEN 'YES'
ELSE 'NO'
END
GO
--Result: 'No'
SET ANSI_NULLS OFF
GO
SELECT CASE WHEN NULL = NULL THEN 'YES'
ELSE 'NO'
END
GO
--Result: 'Yes'
Chris
|||How to retrieve rows with no Duplicate in this case?
subquery returns 1 row, which is fine. But the query itself returns 2 rows
because the TransactionDate has two same date. I want the quesry to return
only one row if it has the same ProductID.
TransactionID is the primary key, which determines the
uniqueness of rows. Qty is not important in the query, but we only need to
have it in the select. We query based on ProductID,StoreID and the date. We
want to get each row based on ProductID, and StoreID which have the
MaX(TransactionDate). Each row returned must have only one ProductID and
StoreID.
For example,
TransactionID ProductID StoreID QTY Date
1 Prd1 2 4
1/2/2005 9:32AM
2 Prd1 2 8
1/2/2005 9:32AM
3 Prd5 2 9
3/2/2005 9:33AM
4 Prd5 4 9
4/2/2005 9:33AM
If we want to get all the products which are in StoreID 2 within the date
that fall below 3/2/2005 10:00AM it must returne the following rows:
TransactionID ProductID StoreID QTY Date
2 Prd1 2 8
1/2/2005 9:32AM
3 Prd5 2 9
3/2/2005 9:33AM
Why? Because we want the last entered record for the ProductID in the
StoreID Within the date. If we see the subquery, this is right which return
s
the right record, but the main query returnes the other record as well, that
is TransactionID #1.
But when we join it with the main query we get wrong results, that is we get
TransactionID #1,2,3. We only want TransactionID #2, #3.
Note:
We cannot use Top 1 in the subquery, because we want to query for many
products which only returns one record for each ProductID. For example, if
there are ProductID 1,2,3,and 4 it must check for all the products if the
query does not specify the ProductID as a limit. It may even want to get all
products from all
stores within specified date. But it must only get 1 Same ProductID for ever
y
StoreID as the previouse example says.
The subquery below works fine, but I think the problem is in the outer query
.
Here is the query:
SELECT DISTINCT IT.ProductID, IT.StoreID,IT.Quantity, Products.ProductName
FROM [Inventory Transactions] IT
LEFT OUTER JOIN Products Products ON Products.ProductID=IT.ProductID
INNER JOIN (
SELECT Products.ProductID,StoreID,MAX(TransactionDate) MaxDate
FROM [Inventory Transactions] IT LEFT OUTER JOIN Products Products
ON Products.ProductID=IT.ProductID WHERE TransactionDate<='03/02/2005
10:02:26'
AND StoreID IN(2) GROUP BY
Products.ProductID,StoreID) AS X
ON IT.ProductID=X.ProductID AND IT.StoreID=X.StoreID AND
IT.TransactionDate=X.MaxDate
ORDER BY Products.ProductName
MikeDon't have time for a full explanation, but try adding
HAVING TransactionDate = MAX(TransactionDate)
after the GROUP BY clause in your subquery. This should force it to return
only the row for the most recent sale.
"Mike9900" wrote:
> I need to get rows without dupicate ProductID. In the below query, the
> subquery returns 1 row, which is fine. But the query itself returns 2 rows
> because the TransactionDate has two same date. I want the quesry to retur
n
> only one row if it has the same ProductID.
> TransactionID is the primary key, which determines the
> uniqueness of rows. Qty is not important in the query, but we only need to
> have it in the select. We query based on ProductID,StoreID and the date.
We
> want to get each row based on ProductID, and StoreID which have the
> MaX(TransactionDate). Each row returned must have only one ProductID and
> StoreID.
> For example,
> TransactionID ProductID StoreID QTY Date
> 1 Prd1 2 4
> 1/2/2005 9:32AM
> 2 Prd1 2 8
> 1/2/2005 9:32AM
> 3 Prd5 2 9
> 3/2/2005 9:33AM
> 4 Prd5 4 9
> 4/2/2005 9:33AM
> If we want to get all the products which are in StoreID 2 within the date
> that fall below 3/2/2005 10:00AM it must returne the following rows:
> TransactionID ProductID StoreID QTY Date
> 2 Prd1 2 8
> 1/2/2005 9:32AM
> 3 Prd5 2 9
> 3/2/2005 9:33AM
> Why? Because we want the last entered record for the ProductID in the
> StoreID Within the date. If we see the subquery, this is right which retu
rns
> the right record, but the main query returnes the other record as well, th
at
> is TransactionID #1.
>
> But when we join it with the main query we get wrong results, that is we g
et
> TransactionID #1,2,3. We only want TransactionID #2, #3.
> Note:
> We cannot use Top 1 in the subquery, because we want to query for many
> products which only returns one record for each ProductID. For example, i
f
> there are ProductID 1,2,3,and 4 it must check for all the products if the
> query does not specify the ProductID as a limit. It may even want to get a
ll
> products from all
> stores within specified date. But it must only get 1 Same ProductID for ev
ery
> StoreID as the previouse example says.
>
> The subquery below works fine, but I think the problem is in the outer que
ry.
> Here is the query:
> SELECT DISTINCT IT.ProductID, IT.StoreID,IT.Quantity, Products.ProductName
> FROM [Inventory Transactions] IT
> LEFT OUTER JOIN Products Products ON Products.ProductID=IT.ProductID
> INNER JOIN (
> SELECT Products.ProductID,StoreID,MAX(TransactionDate) MaxDate
> FROM [Inventory Transactions] IT LEFT OUTER JOIN Products Products
> ON Products.ProductID=IT.ProductID WHERE TransactionDate<='03/02/2005
> 10:02:26'
> AND StoreID IN(2) GROUP BY
> Products.ProductID,StoreID) AS X
> ON IT.ProductID=X.ProductID AND IT.StoreID=X.StoreID AND
> IT.TransactionDate=X.MaxDate
> ORDER BY Products.ProductName
> --
> Mike|||Forget my earlier post. Could you post DDL for all tables involved in the
query, and sample data?
"Mike9900" wrote:
> I need to get rows without dupicate ProductID. In the below query, the
> subquery returns 1 row, which is fine. But the query itself returns 2 rows
> because the TransactionDate has two same date. I want the quesry to retur
n
> only one row if it has the same ProductID.
> TransactionID is the primary key, which determines the
> uniqueness of rows. Qty is not important in the query, but we only need to
> have it in the select. We query based on ProductID,StoreID and the date.
We
> want to get each row based on ProductID, and StoreID which have the
> MaX(TransactionDate). Each row returned must have only one ProductID and
> StoreID.
> For example,
> TransactionID ProductID StoreID QTY Date
> 1 Prd1 2 4
> 1/2/2005 9:32AM
> 2 Prd1 2 8
> 1/2/2005 9:32AM
> 3 Prd5 2 9
> 3/2/2005 9:33AM
> 4 Prd5 4 9
> 4/2/2005 9:33AM
> If we want to get all the products which are in StoreID 2 within the date
> that fall below 3/2/2005 10:00AM it must returne the following rows:
> TransactionID ProductID StoreID QTY Date
> 2 Prd1 2 8
> 1/2/2005 9:32AM
> 3 Prd5 2 9
> 3/2/2005 9:33AM
> Why? Because we want the last entered record for the ProductID in the
> StoreID Within the date. If we see the subquery, this is right which retu
rns
> the right record, but the main query returnes the other record as well, th
at
> is TransactionID #1.
>
> But when we join it with the main query we get wrong results, that is we g
et
> TransactionID #1,2,3. We only want TransactionID #2, #3.
> Note:
> We cannot use Top 1 in the subquery, because we want to query for many
> products which only returns one record for each ProductID. For example, i
f
> there are ProductID 1,2,3,and 4 it must check for all the products if the
> query does not specify the ProductID as a limit. It may even want to get a
ll
> products from all
> stores within specified date. But it must only get 1 Same ProductID for ev
ery
> StoreID as the previouse example says.
>
> The subquery below works fine, but I think the problem is in the outer que
ry.
> Here is the query:
> SELECT DISTINCT IT.ProductID, IT.StoreID,IT.Quantity, Products.ProductName
> FROM [Inventory Transactions] IT
> LEFT OUTER JOIN Products Products ON Products.ProductID=IT.ProductID
> INNER JOIN (
> SELECT Products.ProductID,StoreID,MAX(TransactionDate) MaxDate
> FROM [Inventory Transactions] IT LEFT OUTER JOIN Products Products
> ON Products.ProductID=IT.ProductID WHERE TransactionDate<='03/02/2005
> 10:02:26'
> AND StoreID IN(2) GROUP BY
> Products.ProductID,StoreID) AS X
> ON IT.ProductID=X.ProductID AND IT.StoreID=X.StoreID AND
> IT.TransactionDate=X.MaxDate
> ORDER BY Products.ProductName
> --
> Mike|||Hi
Your problem is that the MaxDate is not unique for each ProductID AND
StoreID combination in [Inventory Transactions] (the accuracy of a datetime
value is one three-hundredth of a second). If TransactionID is guaranteed to
be ascending over time then you could use this instead of the date.
e.g (untested)
SELECT IT.ProductID, IT.StoreID, IT.Quantity, P.ProductName
FROM [Inventory Transactions] IT
LEFT JOIN Products P ON P.ProductID=IT.ProductID
JOIN (
SELECT Q.ProductID, T.StoreID, MAX(T.TransactionID) AS MaxTID
FROM [Inventory Transactions] T
LEFT JOIN Products Q ON Q.ProductID=T.ProductID
WHERE T.TransactionDate<='03/02/2005 10:02:26'
AND StoreID IN(2)
GROUP BY Q.ProductID,T.StoreID) AS X
ON IT.ProductID=X.ProductID AND IT.StoreID=X.StoreID AND
IT.TransactionID=X.MaxTID
ORDER BY P.ProductName
You may want to check out http://www.aspfaq.com/etiquette.asp?id=5006 on how
to post DDL and example data that can be usable.
John
"Mike9900" <Mike9900@.discussions.microsoft.com> wrote in message
news:E7A4AC26-DF6E-4740-9440-ECD9894CCE03@.microsoft.com...
> I need to get rows without dupicate ProductID. In the below query, the
> subquery returns 1 row, which is fine. But the query itself returns 2 rows
> because the TransactionDate has two same date. I want the quesry to
> return
> only one row if it has the same ProductID.
> TransactionID is the primary key, which determines the
> uniqueness of rows. Qty is not important in the query, but we only need to
> have it in the select. We query based on ProductID,StoreID and the date.
> We
> want to get each row based on ProductID, and StoreID which have the
> MaX(TransactionDate). Each row returned must have only one ProductID and
> StoreID.
> For example,
> TransactionID ProductID StoreID QTY Date
> 1 Prd1 2 4
> 1/2/2005 9:32AM
> 2 Prd1 2 8
> 1/2/2005 9:32AM
> 3 Prd5 2 9
> 3/2/2005 9:33AM
> 4 Prd5 4 9
> 4/2/2005 9:33AM
> If we want to get all the products which are in StoreID 2 within the date
> that fall below 3/2/2005 10:00AM it must returne the following rows:
> TransactionID ProductID StoreID QTY Date
> 2 Prd1 2 8
> 1/2/2005 9:32AM
> 3 Prd5 2 9
> 3/2/2005 9:33AM
> Why? Because we want the last entered record for the ProductID in the
> StoreID Within the date. If we see the subquery, this is right which
> returns
> the right record, but the main query returnes the other record as well,
> that
> is TransactionID #1.
>
> But when we join it with the main query we get wrong results, that is we
> get
> TransactionID #1,2,3. We only want TransactionID #2, #3.
> Note:
> We cannot use Top 1 in the subquery, because we want to query for many
> products which only returns one record for each ProductID. For example,
> if
> there are ProductID 1,2,3,and 4 it must check for all the products if the
> query does not specify the ProductID as a limit. It may even want to get
> all
> products from all
> stores within specified date. But it must only get 1 Same ProductID for
> every
> StoreID as the previouse example says.
>
> The subquery below works fine, but I think the problem is in the outer
> query.
> Here is the query:
> SELECT DISTINCT IT.ProductID, IT.StoreID,IT.Quantity, Products.ProductName
> FROM [Inventory Transactions] IT
> LEFT OUTER JOIN Products Products ON Products.ProductID=IT.ProductID
> INNER JOIN (
> SELECT Products.ProductID,StoreID,MAX(TransactionDate) MaxDate
> FROM [Inventory Transactions] IT LEFT OUTER JOIN Products Products
> ON Products.ProductID=IT.ProductID WHERE TransactionDate<='03/02/2005
> 10:02:26'
> AND StoreID IN(2) GROUP BY
> Products.ProductID,StoreID) AS X
> ON IT.ProductID=X.ProductID AND IT.StoreID=X.StoreID AND
> IT.TransactionDate=X.MaxDate
> ORDER BY Products.ProductName
> --
> Mike|||Thanks for the answer.
TransactionID is the primary key that is incremented by the system. It is
gurantedd I think, don't you?
--
Mike
"John Bell" wrote:
> Hi
> Your problem is that the MaxDate is not unique for each ProductID AND
> StoreID combination in [Inventory Transactions] (the accuracy of a datetim
e
> value is one three-hundredth of a second). If TransactionID is guaranteed
to
> be ascending over time then you could use this instead of the date.
> e.g (untested)
> SELECT IT.ProductID, IT.StoreID, IT.Quantity, P.ProductName
> FROM [Inventory Transactions] IT
> LEFT JOIN Products P ON P.ProductID=IT.ProductID
> JOIN (
> SELECT Q.ProductID, T.StoreID, MAX(T.TransactionID) AS MaxTID
> FROM [Inventory Transactions] T
> LEFT JOIN Products Q ON Q.ProductID=T.ProductID
> WHERE T.TransactionDate<='03/02/2005 10:02:26'
> AND StoreID IN(2)
> GROUP BY Q.ProductID,T.StoreID) AS X
> ON IT.ProductID=X.ProductID AND IT.StoreID=X.StoreID AND
> IT.TransactionID=X.MaxTID
> ORDER BY P.ProductName
> You may want to check out http://www.aspfaq.com/etiquette.asp?id=5006 on h
ow
> to post DDL and example data that can be usable.
> John
> "Mike9900" <Mike9900@.discussions.microsoft.com> wrote in message
> news:E7A4AC26-DF6E-4740-9440-ECD9894CCE03@.microsoft.com...
>
>|||The other tables are Store with StoreID as primary key, Products with
ProductID as the primary key. These two keys are references in this table.
--
Mike
"Mark Williams" wrote:
> Forget my earlier post. Could you post DDL for all tables involved in the
> query, and sample data?
> "Mike9900" wrote:
>|||Thanks for the help.
We want it based on TransactionDate not the TransactionID. There could have
been a transaction that had lower date but the TransactionID is the highest.
This occurs, for example, when the user wants to post a transaction for
previous month today. If the user post the previouse month transaction today
,
TransactionID is Max but the TransactionDate is not Max.
We want a combination of both Max(TransactionDate) and Max(TransactionID) to
be true, but here we see that the TransactionDate could not be unique and
TransactionID is not correct by itself.
--
Mike
"John Bell" wrote:
> Hi
> Your problem is that the MaxDate is not unique for each ProductID AND
> StoreID combination in [Inventory Transactions] (the accuracy of a datetim
e
> value is one three-hundredth of a second). If TransactionID is guaranteed
to
> be ascending over time then you could use this instead of the date.
> e.g (untested)
> SELECT IT.ProductID, IT.StoreID, IT.Quantity, P.ProductName
> FROM [Inventory Transactions] IT
> LEFT JOIN Products P ON P.ProductID=IT.ProductID
> JOIN (
> SELECT Q.ProductID, T.StoreID, MAX(T.TransactionID) AS MaxTID
> FROM [Inventory Transactions] T
> LEFT JOIN Products Q ON Q.ProductID=T.ProductID
> WHERE T.TransactionDate<='03/02/2005 10:02:26'
> AND StoreID IN(2)
> GROUP BY Q.ProductID,T.StoreID) AS X
> ON IT.ProductID=X.ProductID AND IT.StoreID=X.StoreID AND
> IT.TransactionID=X.MaxTID
> ORDER BY P.ProductName
> You may want to check out http://www.aspfaq.com/etiquette.asp?id=5006 on h
ow
> to post DDL and example data that can be usable.
> John
> "Mike9900" <Mike9900@.discussions.microsoft.com> wrote in message
> news:E7A4AC26-DF6E-4740-9440-ECD9894CCE03@.microsoft.com...
>
>|||Hi
This tends to imply that you transaction date is a confusing name! If these
can be back dates then you will potentially get different results each time
you run the query and it will not be historically static. If you don't have
sufficient auditing of the changes to your data it may be hard to prove why
you get different results.
Try something like:
SELECT IT.ProductID, IT.StoreID, IT.Quantity, P.ProductName
FROM [Inventory Transactions] IT
JOIN Products P ON P.ProductID=IT.ProductID
JOIN (
SELECT X.ProductID, X.StoreID, MAX(I.TransactionID) AS MAXTID
FROM [Inventory Transactions] I
JOIN (
SELECT Q.ProductID, T.StoreID, MAX(T.TransactionDate) AS MaxDate
FROM [Inventory Transactions] T
LEFT JOIN Products Q ON Q.ProductID=T.ProductID
WHERE T.TransactionDate<='03/02/2005 10:02:26'
AND StoreID IN(2)
GROUP BY Q.ProductID,T.StoreID) AS X ON I.ProductID=X.ProductID AND
I.StoreID=X.StoreID AND I.TransactionDate=X.MaxDate
) Y ON IT.ProductID=Y.ProductID AND IT.StoreID=Y.StoreID AND
IT.TransactionID=Y.MAXTID
ORDER BY P.ProductName
John
"Mike9900" <Mike9900@.discussions.microsoft.com> wrote in message
news:4149F671-75A3-4A82-95BD-841CF2FC55C4@.microsoft.com...
> Thanks for the help.
> We want it based on TransactionDate not the TransactionID. There could
> have
> been a transaction that had lower date but the TransactionID is the
> highest.
> This occurs, for example, when the user wants to post a transaction for
> previous month today. If the user post the previouse month transaction
> today,
> TransactionID is Max but the TransactionDate is not Max.
> We want a combination of both Max(TransactionDate) and Max(TransactionID)
> to
> be true, but here we see that the TransactionDate could not be unique and
> TransactionID is not correct by itself.
> --
> Mike
>
> "John Bell" wrote:
>|||Thank you John, it is working.
--
Mike
"John Bell" wrote:
> Hi
> This tends to imply that you transaction date is a confusing name! If thes
e
> can be back dates then you will potentially get different results each tim
e
> you run the query and it will not be historically static. If you don't hav
e
> sufficient auditing of the changes to your data it may be hard to prove wh
y
> you get different results.
> Try something like:
> SELECT IT.ProductID, IT.StoreID, IT.Quantity, P.ProductName
> FROM [Inventory Transactions] IT
> JOIN Products P ON P.ProductID=IT.ProductID
> JOIN (
> SELECT X.ProductID, X.StoreID, MAX(I.TransactionID) AS MAXTID
> FROM [Inventory Transactions] I
> JOIN (
> SELECT Q.ProductID, T.StoreID, MAX(T.TransactionDate) AS MaxDate
> FROM [Inventory Transactions] T
> LEFT JOIN Products Q ON Q.ProductID=T.ProductID
> WHERE T.TransactionDate<='03/02/2005 10:02:26'
> AND StoreID IN(2)
> GROUP BY Q.ProductID,T.StoreID) AS X ON I.ProductID=X.ProductID AND
> I.StoreID=X.StoreID AND I.TransactionDate=X.MaxDate
> ) Y ON IT.ProductID=Y.ProductID AND IT.StoreID=Y.StoreID AND
> IT.TransactionID=Y.MAXTID
> ORDER BY P.ProductName
> John
>
> "Mike9900" <Mike9900@.discussions.microsoft.com> wrote in message
> news:4149F671-75A3-4A82-95BD-841CF2FC55C4@.microsoft.com...
>
>|||Create a view that captures the max date
Create view VwMaxDate as
select ProductID, Max(Date) as MaxDate
group by ProductID
Then, you can join your table to the view and get the results you are
s
Select a.TransactionID, a.ProductID, a.StoreID, a.QTY, a.Date
from TableA a join VwMaxDate on a.ProductId = b.ProductId and a.Date =
b.MaxDate