Showing posts with label order. Show all posts
Showing posts with label order. Show all posts

Friday, March 30, 2012

please help me fix this SQL query

SELECT * FROM

(SELECT row_number() OVER (ORDER BY custname) as resultNum,

t_enduser.id,substring(t_enduser.custcode,1,3), custname,city1,state1,

t_enduser.createdby,t_enduser.createdtime as ct, t_details.serialnumber,

t_details.package,startdate,endDate,endProduct

from t_enduser,t_master,t_details

where t_enduser.id=t_master.custcode

and t_master.t_ref=t_details.t_ref

and lOWER(package)<>'pdahardwareonly'

and lOWER(endproduct)<>'accessories' and status='valid'

and t_details.t_ref in

(SELECT rh.t_ref FROM t_details rh,

(SELECT max(endDate) as maxdate, serialNumber FROM t_details

where lOWER(package)<>'pdahardwareonly' and

lOWER(endproduct)<>'accessories' and status='valid'

GROUP BY serialNumber

)maxresults

WHERE rh.serialNumber = maxresults.serialNumber AND

rh.endDate= maxresults.maxdate

)

)as numberResults where resultNum '1' and '10'

It's difficult to say what's wrong seeing without seeing error messages or sample data.

One thing that stands out, however, is the WHERE clause:

where resultNum '1' and '10'

Should this be:

where resultNum IN('1', '10')

or if resultNum is of a numerical datatype:

where resultNum IN(1, 10)

?

Chris

|||

The first line says

Select * from

but there is nothing in the from clause.

There is a lot more wrong with this query.

|||

The query will be perfectly valid once the final WHERE clause has been sorted out.

Chris

|||

Firstly, I hope the code is better formatted on your end. I know it is pretty ugly to past directly into the forums, so consider pasting to text first. I would consider reformatting for our value if you post such amounts of code as youi have a very messy query. I have highlighted a few things that seem troublesome, but nothing overly horrible.

You are going to have to give more information...

SELECT *
--alias all names. We can't help you if you won't give all information.
FROM (SELECT row_number() OVER (ORDER BY custname) as resultNum,
t_enduser.id,
substring(t_enduser.custcode, 1, 3),
custname, city1, state1, t_enduser.createdby,
t_enduser.createdtime as ct,
t_details.serialnumber, t_details.package,
startdate, endDate, endProduct
from t_enduser
,t_master --is this table_master, or does t_ have other meaning. Master is a weak name
--master, what?

,t_details
--learn about the JOIN criteria instead of using the comma based cartesion product style join
--syntax, it is easier to follow, and certainly to debug

where t_enduser.id = t_master.custcode --Customers are also endusers? This seems odd
and t_master.t_ref = t_details.t_ref --t_ref? Is this the pkey of one of your tables? Or all?
--Why lower? Is your database case sensitive? If so, then use a constraint to make sure
--package and products forllow the rules.

and LOWER(package) <> 'pdahardwareonly'
and LOWER(endproduct) <> 'accessories'
and status = 'valid'
and t_details.t_ref in (
SELECT rh.t_ref
FROM t_details rh
,(SELECT max(endDate) as maxdate,
serialNumber
FROM t_details
WHERE LOWER(package) <> 'pdahardwareonly'
and LOWER(endproduct) <> 'accessories'
and status = 'valid'
GROUP BY serialNumber) maxresults
WHERE rh.serialNumber = maxresults.serialNumber
AND rh.endDate = maxresults.maxdate))
as numberResults
where resultNum between 1 and 10 --this is the code that needed fixed

--also you can redo the in clause using the rowNumber function to make it a little easier...
select getRows.tref
from (SELECT rh.t_ref, row_number() over (partition by serialNumber order by endDate) as rowNum
FROM t_details
WHERE LOWER(package) <> 'pdahardwareonly'
and LOWER(endproduct) <> 'accessories'
and status = 'valid') as getRows
where getRows.rowNum = 1

|||

Louis thanks for you tips. As what you suggested “between” is the problem. Basically
I want to combine three tables and those three tables cross-reference each other.
My task requirement in such I need to pull the transactions in one
stretch customer details and his last product purchased that is by expiry date.

1. Find the product and its expiry date (maximum end date is the exp date)
2. Get the customer details for that reference
3. Pagination
4. Get row number for each records

Customer Details TABLE NAMES (T_ENDUSER)
Transaction TABLE NAMES (T_MASTER,T_DETAILS)

After I made the correction, The following query can work for me. But as what you suggested my join criteria,
I feel like dump. Can u please tune up for me?

SELECT * FROM (
SELECT row_number() OVER (ORDER BY custname) as RESULTNUM,
T_ENDUSER.id,T_MASTER.t_ref
from T_ENDUSER,T_MASTER,T_DETAILS
where T_ENDUSER.id=T_MASTER.custcode
and T_MASTER.t_ref=T_DETAILS.t_ref
and lOWER(package)<>'pdahardwareonly'
and lOWER(endproduct)<>'accessories'
and status='valid'
and T_DETAILS.t_ref in
(SELECT rh.t_ref FROM T_DETAILS rh,
(SELECT max(endDate) as maxdate, serialNumber FROM T_DETAILS where lOWER(package)<>'pdahardwareonly'
and lOWER(endproduct)<>'accessories'
and status='valid' GROUP BY serialNumber
) as EXPDATE
WHERE rh.serialNumber = EXPDATE.serialNumber
AND rh.endDate= EXPDATE.maxdate)
)as NUMRESULTS where RESULTNUM between '1' and '20'

|||

I was just suggesting that you use the new style joins instead:

SELECT *
FROM (SELECT row_number() OVER (ORDER BY custname) as RESULTNUM,
T_ENDUSER.id, T_MASTER.t_ref
from T_ENDUSER
JOIN T_MASTER
on T_ENDUSER.id = T_MASTER.custcode
JOIN T_DETAILS
on T_MASTER.t_ref = T_DETAILS.t_ref

where lOWER(package) <> 'pdahardwareonly'
and lOWER(endproduct) <> 'accessories'
and status = 'valid'
and T_DETAILS.t_ref in (
SELECT rh.t_ref
FROM T_DETAILS rh
join (SELECT max(endDate) as maxdate,
serialNumber
FROM T_DETAILS
where lOWER(package) <> 'pdahardwareonly'
and lOWER(endproduct) <> 'accessories'
and status = 'valid'
GROUP BY serialNumber) as EXPDATE
ON rh.serialNumber = EXPDATE.serialNumber
AND rh.endDate = EXPDATE.maxdate
))
as NUMRESULTS
where RESULTNUM between 1 and 20 --Also, these should be numbers, not characters

The version you did will work just fine, but this is a lot easier to follow, and is far better for outer joins...

Monday, March 26, 2012

Please help - setting order of select in a self-referencing table

Hello,
I have a table of product categories that looks like this (air code, so
could be some typos, but it's basically right)...
create table producttypes (
ptype int not null identity(1,1) primary key,
typename varchar(50) not null default '',
ParentCat int references producttypes(ptype)
)
This allows categories to contain subcategories and so on.
In order to allow me to see the hierarchy, I am using the following
code, modified from some found in "Inside SQL Server 7.0" by Kalen
Delaney.
-- SQL starts
declare @.level int, @.current int
create table #stack (depthlevel int, ptype int)
create table #orgchart (seqno int identity, orglevel int not null, ptype int
not null)
set rowcount 1
select @.level=1, @.current=ptype from producttypes where ptype=parentcat
set rowcount 0
insert into #stack (depthlevel, ptype) values (@.level, @.current)
while (@.level>0)
begin
if exists (select * from #stack where depthlevel=@.level)
begin
set rowcount 1
select @.current=ptype from #stack where depthlevel=@.level
set rowcount 0
insert into #orgchart (orglevel, ptype) select @.level, @.current
delete from #stack where depthlevel=@.level and ptype=@.current
insert into #stack select @.level+1, ptype from producttypes where parentcat=
@.current and parentcat<>ptype
if @.@.ROWCOUNT > 0 select @.level=@.level+1
end
else
select @.level=@.level-1
end
select o.orglevel, e.ptype, e.parentcat, e.typename from #orgchart as o
join producttypes as e on e.ptype=o.ptype order by o.seqno
drop table #stack, #orgchart
-- SQL ends
This produces a set of results that gives me all the categories. I can
use the orglevel field to tell what level I'm at, so if it changes, I
can see if I've gone up or down the hierarchy.
Now, the problem is that I can't work out how to set the order of
categories. For example, if the above SQL produces...
1 16 16 Products
2 17 16 Outdoor Toys
3 1 17 Trampolines
3 2 17 Slides
3 3 17 Swings
3 4 17 Accessories
3 5 17 Climbing Frames
3 7 17 Bicycles
you can see that the categories on level 3 are not in any obvious order.
I would like to have them in alphabetical order.
Any ideas how I would modify the above SQL to do this? TIA
Alan Silver
(anything added below this line is nothing to do with me)Try
select o.orglevel, e.ptype, e.parentcat, e.typename from #orgchart as o
join producttypes as e on e.ptype=o.ptype order by o.seqno, e.typename
The results should be sorted first by the orglevel, and results within the
same orglevel will be sorted alphabetically. The syntax reads like "order
results first by o.seqno, then by e.typename"
"Alan Silver" wrote:

> Hello,
> I have a table of product categories that looks like this (air code, so
> could be some typos, but it's basically right)...
> create table producttypes (
> ptype int not null identity(1,1) primary key,
> typename varchar(50) not null default '',
> ParentCat int references producttypes(ptype)
> )
> This allows categories to contain subcategories and so on.
> In order to allow me to see the hierarchy, I am using the following
> code, modified from some found in "Inside SQL Server 7.0" by Kalen
> Delaney.
> -- SQL starts
> declare @.level int, @.current int
> create table #stack (depthlevel int, ptype int)
> create table #orgchart (seqno int identity, orglevel int not null, ptype i
nt not null)
> set rowcount 1
> select @.level=1, @.current=ptype from producttypes where ptype=parentcat
> set rowcount 0
> insert into #stack (depthlevel, ptype) values (@.level, @.current)
> while (@.level>0)
> begin
> if exists (select * from #stack where depthlevel=@.level)
> begin
> set rowcount 1
> select @.current=ptype from #stack where depthlevel=@.level
> set rowcount 0
> insert into #orgchart (orglevel, ptype) select @.level, @.current
> delete from #stack where depthlevel=@.level and ptype=@.current
> insert into #stack select @.level+1, ptype from producttypes where par
entcat=@.current and parentcat<>ptype
> if @.@.ROWCOUNT > 0 select @.level=@.level+1
> end
> else
> select @.level=@.level-1
> end
> select o.orglevel, e.ptype, e.parentcat, e.typename from #orgchart as o
> join producttypes as e on e.ptype=o.ptype order by o.seqno
> drop table #stack, #orgchart
> -- SQL ends
>
> This produces a set of results that gives me all the categories. I can
> use the orglevel field to tell what level I'm at, so if it changes, I
> can see if I've gone up or down the hierarchy.
> Now, the problem is that I can't work out how to set the order of
> categories. For example, if the above SQL produces...
> 1 16 16 Products
> 2 17 16 Outdoor Toys
> 3 1 17 Trampolines
> 3 2 17 Slides
> 3 3 17 Swings
> 3 4 17 Accessories
> 3 5 17 Climbing Frames
> 3 7 17 Bicycles
> you can see that the categories on level 3 are not in any obvious order.
> I would like to have them in alphabetical order.
> Any ideas how I would modify the above SQL to do this? TIA
> --
> Alan Silver
> (anything added below this line is nothing to do with me)
>|||>Try
>select o.orglevel, e.ptype, e.parentcat, e.typename from #orgchart as o
>join producttypes as e on e.ptype=o.ptype order by o.seqno, e.typename
>The results should be sorted first by the orglevel, and results within the
>same orglevel will be sorted alphabetically. The syntax reads like "order
>results first by o.seqno, then by e.typename"
Mark,
Thanks for the reply, but if you look carefully, it's not that simple.
Your suggestion will list all level 2 categories together, followed by
all level 3 and so on. This will not give the correct hierarchy as there
may be several level 2 categories each with subcategories (ie level 3).
If this isn't clear, look at the longer category listing shown later on.
This is a more complete list than the abbreviated one I showed before.
Note that the ordering is done on seqno, which is the order in which the
categories were put into the orgchart table. The ordering is not done on
the level at all.
I think I need to modify the way the categories are pulled out of the
producttypes table when they are inserted into the stack table. Trouble
is, I can't see how to control the ordering as they are being pulled one
at a time.
Thanks for the reply. Any further help would be appreciated.
Longer category listing follows...
level typename
1 Products
2 Outdoor Toys
3 Trampolines
3 Slides
3 Swings
3 Accessories
3 Climbing Frames
3 Bicycles
2 Indoor Toys
3 Snooker Tables
3 Boy's Toys
4 Hard Puzzles
3 Girl's Toys
4 Easy Puzzles
3 Board Games
3 Pets
4 Ferrets
4 Dogs
4 Cats
>"Alan Silver" wrote:
>
Alan Silver
(anything added below this line is nothing to do with me)sql

Please Help

I am trying to pull the last 30 records in a table. I'm trying to write a
dynamic stored procedure in order to do this. I am joining a couple tables
and the table i need to get the 30 records out of is the second table. I
can't seem to get it to work with my code. Below is the code that I am using
to try to do this, I have declared the variables earlier in this procedure:
(Select Distinct LotID, @.LowNum = max(LotID)-30, @.HighNum = max(LotID)
From dbo.schedulegovcom
Where LotID<=@.HighNum
and >=@.LowNum
Group by LotID) pTry:
SELECT TOP 30
[field list]
FROM
dbo.schedulegovcom
ORDER BY
LotID DESC
Mike
"A.B." <AB@.discussions.microsoft.com> wrote in message
news:F449DAD0-7B92-4E1A-9676-1604C2D79D3A@.microsoft.com...
>I am trying to pull the last 30 records in a table. I'm trying to write a
> dynamic stored procedure in order to do this. I am joining a couple tables
> and the table i need to get the 30 records out of is the second table. I
> can't seem to get it to work with my code. Below is the code that I am
> using
> to try to do this, I have declared the variables earlier in this
> procedure:
> (Select Distinct LotID, @.LowNum = max(LotID)-30, @.HighNum = max(LotID)
> From dbo.schedulegovcom
> Where LotID<=@.HighNum
> and >=@.LowNum
> Group by LotID) p|||You can not mix resultset with assigning value to a variable in the same
select statement.
-- wrong
select @.i = orderid, customerid from dbo.orders
AMB
"A.B." wrote:

> I am trying to pull the last 30 records in a table. I'm trying to write a
> dynamic stored procedure in order to do this. I am joining a couple tables
> and the table i need to get the 30 records out of is the second table. I
> can't seem to get it to work with my code. Below is the code that I am usi
ng
> to try to do this, I have declared the variables earlier in this procedure
:
> (Select Distinct LotID, @.LowNum = max(LotID)-30, @.HighNum = max(LotID)
> From dbo.schedulegovcom
> Where LotID<=@.HighNum
> and >=@.LowNum
> Group by LotID) p|||Thanks that worked
"Mike Jansen" wrote:

> Try:
> SELECT TOP 30
> [field list]
> FROM
> dbo.schedulegovcom
> ORDER BY
> LotID DESC
> Mike
> "A.B." <AB@.discussions.microsoft.com> wrote in message
> news:F449DAD0-7B92-4E1A-9676-1604C2D79D3A@.microsoft.com...
>
>

Monday, March 12, 2012

Placement of Null in result set - sort order

Hi All,
This is a really crappy question that I found a responce to ages ago, but cannot find on the forum just now.

Whe I sort by a column that has null, then the NULL values are either in the top or bottom of the result set depending on whether the order by is asc or desc.

If I have a table
t with a column c which has 5 rows with values 1,2,3,4,NULL
************************************

create table #t(c int)

insert into #t values(1)
insert into #t values(2)
insert into #t values(3)
insert into #t values(4)
insert into #t values(null)

*************************
Then.....
select *
from #t order by 1 asc
results in ....
NULL
1
2
3
4

*******************
and...
select *
from #t order by 1 desc
results in.,...
4
3
2
1
NULL

I need null always at the end. so that I either get
1
2
3
4
NULL

or

4
3
2
1
NULL

Any ideas?

PeterYou have this problem only with ASC. In this case, order like this:

order by isnull(c, 2^31 - 1 ) ASC

instead of

order by 1 ASC|||Yo,
why are you using a bit operator.
can't I just use...
select *
from #t order by isnull(c, 4000 )|||Actually, it isn't a bit operator, but the Power operator. Anything is fine which is larger than your largest number to be expected of c.

Monday, February 20, 2012

Pivot Multiple Values

Is there a way to pivot multiplie values in one 'run'.... In the order of ...

PIVOT ( SUM(DSH_TICKETS) FOR CPRF_NBR IN ([1], [2], [3], [4], [5])

SUM(HALL_CAPACITY) FOR CPRF_NBR IN ([1], [2], [3], [4], [5]) ) PVT

I know that there would be a problem with the headers, but that i could solve by using a second dummy for cprf_nbr and increase it with 10 (ex.)

Until knwo i did the jobg with a case statement, but it would be much nicer with a PIVOT.

No. This is not possible with PIVOT operator. You will have to use the old approach of using multiple aggregate functions with CASE expressions and GROUP BY which is what PIVOT does right now.|||

I am not 100% sure that this matches, but I wrote a blog about taking a set that looked like:

GroupBy PropertyName value1 value2
- -- --
First Property1 1.00 2.00
First Property2 2.00 4.00
Second Property1 4.00 8.00
Second Property2 8.00 16.00

And pivoted to look like:

groupBy Property1-value1 Property1-value2 Property2-value1 Property2-value2
- - -- - -
First 1.00 2.00 2.00 4.00
Second 4.00 8.00 8.00 16.00

The idea was to add another layer in there and Break down the set into two queries (in your case one for DSH_TICKETS, and another for HALL_CAPACITY) and then change the names of the columns to DSH_TICKETS-1, DSH_TICKETS-2, etc, then pivot on these names for the group.

Here it is: http://drsql.spaces.msn.com/blog/cns!80677FB08B3162E4!758.entry

There I used max, but sum should work (I think :)