Top + Order By = Strange Results

Mar 14, 2008

Hi there,

I'm a little bit confused here.

I the TOP 1 function with ORDER BY DESC to get the last id in my table but it doesn't seems to work.

Here's an example:

SELECT TOP 1 ID FROM Worksheet WHERE Style='302' AND Notes='Automatically created from m0851System.' AND Title='STD COST UPDATED FORM m0851System' ORDER BY ID DESC


SELECT ID FROM Worksheet WHERE Style='302' AND Notes='Automatically created from m0851System.' AND Title='STD COST UPDATED FORM m0851System' ORDER BY ID ASC


So basically the first SELECT should return the last id value of the second query but it doesn't.

The first query gives me that: 60721

And the second one gives me that:
60680
60681
60683
60684
60685
60686
60718
60719
60720
60721
61050
61122
61124

So as you can see my TOP 1 ID ORDER BY ID DESC should gave me this result: 61124


Am I missing something or... ?


Please help me this is aleready in function so I have to fix it ASAP.

Thank you,
Regards,

OR-THO

View 5 Replies


ADVERTISEMENT

T-SQL : Order By Clause Is Just Strange

Mar 19, 2008

Hi! I think the order by clause is driving me crazy.The following T-SQL query works: SELECT
count(*) AS c
From F_POST
Where id=@id
Order by c  Ok, so far so good, but in the following case it is NOT possible to order the result set according to "count(*)": Select
T_Date AS TDATE,
count(*) AS c
From F_Post
Where id=@id
Order By case when @OrderBy = 1 then c
elseT_DATE DESC  This is just strange since it is essentially the same query!? Furthermore, it seems to be inpossible to have a order-by-clause that looks like:  Order By case when @OrderBy = 1 then T_Column1 ASC
elseT_Column2 DESC

 Does anyone know how I can implement querys that do (almost) exactly this what the last 2 querys "should" to do?

View 2 Replies View Related

Strange Results Using IN

Mar 2, 2004

I received some strange results after typing the wrong column in a subselect using IN. I've been puzzling over it a while now and can't quite figure out why it is doing what it is.
Here's an example of what is happening.


use northwind
go

select * from Customers where CustomerID in
( select CustomerID from Employees where 1 = 0 )


Now, there is no customerid on the Employees table, so running the subquery alone will produce an error. However when the full query above is run, all rows in the customer table are returned.

It was my understanding that the inner querry is evaluated first, and the results used by the outer query. I'm having a hard time seeing how this query is going anywhere.

Any ideas?

View 13 Replies View Related

Strange Behaviour In ORDER BY Statement

Jul 20, 2005

HiI've done a search and found plenty on ORDER BY problems, but mineshopefully a syntax error.This is a test segment from my stored procedure.DECLARE @Name varchar(50), @SortType IntSET @Name = "canal lock"SET @SortType = 8SELECT dbo.ite_Item.ite_IDFROM dbo.ite_Item LEFT OUTER JOINdbo.iti_ItemImages ONdbo.ite_Item.ite_ID = dbo.iti_ItemImages.iti_LinkToItemWHERE iti_ItemImages.iti_LinkToPhotoType=1AND ite_Name LIKE '%' + @Name + '%'ORDER BYCASEWHEN @SortType = 3 THEN dbo.ite_Item.ite_DateWHEN @SortType = 5 THEN dbo.ite_Item.ite_ViewsWHEN @SortType = 7 THEN dbo.ite_Item.ite_DescriptionEND ASC,CASEWHEN @SortType = 2 THEN dbo.ite_Item.ite_NameWHEN @SortType = 4 THEN dbo.ite_Item.ite_DateWHEN @SortType = 6 THEN dbo.ite_Item.ite_ViewsWHEN @SortType = 8 THEN dbo.ite_Item.ite_DescriptionEND DESC,CASEWHEN @SortType <> 2 THEN dbo.ite_Item.ite_NameEND ASCI get various errors:@SortType = 2. This is a Name field varchar(50)Syntax error converting the varchar value 'Canal Lock' to a column ofdata type smallint.I only have one smallint col and that is the ite_Views column. Why isit trying to convert a varchar(50) col?@SortType = 3. This is a ISO date field nchar(8)The conversion of the nvarchar value '20030909' overflowed an INT2column. Use a larger integer column.Why?@SortType = 7, 8. These are description fields varchar(5000)Syntax error converting the varchar value '<snip>' to a column of datatype smallint.Again, why?All other sort types are fine.What I'm thinking is that when the ORDER BY code is run, it does someconversion but what?Many thanks in advance if anyone has any ideas?Sam

View 3 Replies View Related

SQL To Order Results In Predefined Order

Mar 27, 2008

I have a DB with items which can have lengths from 0 to 400 meter.In my resultset I want to show the items with length 1-400 meter and then the results with length 0 meterHow to build my SQL?

View 4 Replies View Related

Specify Order For Select Results, Order By: Help!

Nov 17, 2006

Lets say I have a table named [Leadership] and I want to select the field 'leadershipName' from the [Leadership] Table.

My query would look something like this:

Select leadershipName
From Leadership

Now, I would like to order the results of this query... but I don't want to simply order them by ASC or DESC. Instead, I need to order them as follows:

Executive Board Members, Delegates, Grievance Chairs, and Negotiators

My question: Can this be done through MS SQL or do I need to add a field to my [Leadership] table named 'leadershipImportance' or something as an integer to denote the level of importance of the position so that I can order on that value ASC or DESC?

Thanks,

Zoop

View 1 Replies View Related

Strange Results From Not In Query

Jul 10, 2006

Hi all,Using SQL Server 2000, SP4.I have a table of street names (Rua) whose ids (cod_rua) are foreignkeys into a consumer table (Consumidor). It turns out that the "Rua"table has many unused records which I'd like to wipe out. For instance,there are some 2800 unused records in the "Rua" table, and only some200 records actually being used by the "Consumidor" table (which,itself, has some 5000 records).Attempting to find the unused records, I issued the following query:a)SELECT COD_RUA FROM RUAWHERE COD_RUA NOT IN (SELECT COD_RUA FROM CONSUMIDOR)To my surprise, the query came out empty. But the following queryshowed the 200 or so records which *are* being used:b)SELECT COD_RUA FROM RUAWHERE COD_RUA IN (SELECT COD_RUA FROM CONSUMIDOR)I've found two solutions for the query to list the records *notexisting* in the Consumidor table:c)SELECT COD_RUA FROM RUAWHERE COD_RUA NOT IN (SELECT COD_RUA FROM CONSUMIDORWHERE COD_RUA IS NOT NULL)d)SELECT COD_RUA FROM RUAWHERE COD_RUA NOT IN (SELECT COD_RUA FROM RUAWHERE COD_RUA IN (SELECT COD_RUA FROM CONSUMIDOR))I know that there are many other possible solutions to the query(including left joins), but what I don't understand is why the query a)failed.Can some of you, oh mighty gurus, enlighten me?For the record, here's how both tables are (partially) declared:CREATE TABLE Rua (Cod_Rua int NOT NULL ,Rua varchar (35) NULL ,-- ...-- other unrelated fields-- ...CONSTRAINT Pk_CodRuaPRIMARY KEY (Cod_Rua))CREATE TABLE Consumidor (Cod_Consumidor int NOT NULL ,Cod_Rua int NULL ,-- ...-- other unrelated fields-- ...CONSTRAINT Pk_CodConsumidorPRIMARY KEY(Cod_Consumidor) ,CONSTRAINT Fk_CodRua_ConsumidorFOREIGN KEY (Cod_Rua)REFERENCES Rua (Cod_Rua))Regards,Branco Medeiros

View 3 Replies View Related

Strange View Results

Jul 20, 2005

Bit of an obscure one here, so please bear with me. I have two copiesof a database which should be identical. Both have a complex viewwhich is identical. I can open the views and the data is as expectedand match. I can query it in several ways as detailed below. The 5thversion of the simple query below based on the second copy of the viewfails, but works under the first copy./*1 Statement below works*/SELECT *FROM AgentHierarchyWHERE AdviserId = 6069819/*2 Statement below works*/SELECT *, AH.AdviserLastName, AH.AdviserFirstNameFROM AgentHierarchy AHWHERE AdviserId = 6069819/*3 Statement below works*/SELECT *, AH.AdviserLastName + ', '+ AH.AdviserFirstNameFROM AgentHierarchy AHWHERE AdviserId = 6069819/*4 Statement below works*/SELECT AH.AdviserLastName + ', '+ AH.AdviserFirstNameFROM AgentHierarchy AH/*5 Statement below fails*/SELECT AH.AdviserLastName + ', '+ AH.AdviserFirstNameFROM AgentHierarchy AHWHERE AdviserId = 6069819The error I get is to do with conversion of data within the view. It'sa little complex, but the view works fine. It looks to me like when Irun the 5th statement above, it re-runs the view and then finds anerror.So, I took the complex view and ran that with the data output into atemporary table with the queries above run against that, and it worksfine. The problem is that the statement I need is based around the 5thone above (part of an update statement).I'm struggling to understand why some of the queries above work andone doesn't. If you look at 3 and 5 I'd expect them both to fail. Ifit failed consistently I could get further into it.The problem is that it's a little difficult to get the view itselfchanged as it was supplied by a third party, but if it hasn't changedand the data hasn't changed then it's got to be something else causingthe problem.Anyway, as I said, it's a bit obscure, but if this sounds familiar I'dbe interested in your opinion.Thanks in advance.

View 4 Replies View Related

Strange Results Converting To Hours

Mar 6, 2008

Hi
I'm getting strange results when converting a number to hours and minutes.

The following section of code....

AbsentMinutes,
CONVERT(varchar(5), DATEADD([minute], [AbsentMinutes], 0), 108) AS AbsentHours,
[Term 1 Minutes],
CONVERT(varchar(5), DATEADD([minute], [Term 1 Minutes], 0), 108) AS Term1Hours,

......is yielding the following results.

AbsentMins 6480 AbsentHours 12:00
Term 1 Mins 21540 Term 1 Hours 23:00

Obviously thats not right but I cant see where.

Can anyone advise please? This has worked for me previously on other data.

View 5 Replies View Related

Strange Results When Calling A Sql Stored Proc From Within An Access2000 Project

Nov 18, 2006

Hi,I have written a stored procedure which includes a DATEPART command, i.e.DATEPART(weekday, <date>)The result when ran from SQL Query Analyser is as expected . i.e. Sundayreturns 1, Monday 2, etcWhen the same proc is called from within the Access 2000 project Sundayis returned as 7, Saturday as 6 instead of 1 and 7 respectively.Basically the same stored proc returns different data depending on fromwhere it has been called.This is causing some issues obviously as the resulting tables andreports are showing incorrect data when presented in Access 2000.Has anyone else experienced this before or have any idea what may cause it.Regards,PB

View 1 Replies View Related

Results In Order

Jun 13, 2007

I have the following query and I am wanting to get the results to be in order. Right now, it shows me the results by date, but the dates are out of order. How can I get it to give me the results by date in date order???

SELECT DISTINCT MDN, dateadd(day, datediff(day, 0, CallDate), 0) as CallDate,sum(PaidBalCost), sum(BonusBalCost), sum(ceiling((Cast(DurationSeconds as Decimal)/60))) as Minutes
FROM VoiceCallDetailRecord
WHERE CallDate >= '02/19/2007' and calldate < '03/19/2007'
and NOT (Left(Endpoint,3) IN ('011')
or (Left(Endpoint,4) IN ('1340','1876','1868','1809',
'1246','1242','1780','1403',
'1250','1604','1807','1519',
'1204','1506','1709','1867',
'1902','1705','1613','1416',
'1905','1902','1514','1450',
'1418','1819','1306','1867')))
AND (((CONVERT(varchar, CallDate, 108) Between '07:00:00' AND '20:59:59'))
AND DATEPART(weekday, CallDate) in (2,3,4,5,6))
Group By MDN, dateadd(day, datediff(day, 0, CallDate), 0)
UNION
SELECT DISTINCT MDN, dateadd(day, datediff(day, 0, CallDate), 0) as CallDate,sum(PaidBalCost), sum(BonusBalCost), sum(ceiling((Cast(DurationSeconds as Decimal)/60))) as Minutes
FROM ZeroChargeVCDRecord
WHERE CallDate >= '02/19/2007' and calldate < '03/19/2007'
and NOT (Left(Endpoint,3) IN ('011')
or (Left(Endpoint,4) IN ('1340','1876','1868','1809',
'1246','1242','1780','1403',
'1250','1604','1807','1519',
'1204','1506','1709','1867',
'1902','1705','1613','1416',
'1905','1902','1514','1450',
'1418','1819','1306','1867')))
AND (((CONVERT(varchar, CallDate, 108) Between '07:00:00' AND '20:59:59'))
AND DATEPART(weekday, CallDate) in (2,3,4,5,6))
Group By MDN, dateadd(day, datediff(day, 0, CallDate), 0)

View 5 Replies View Related

How To Order Results From DateName?

Mar 13, 2008

HiI want to get the dateName of everything but I don't know how to sort them now. Like I have this:DateName(month,TimeDateStamp) As TimeDateStampWhat gets the dateName now I want to sort these so that they are in order.How do I do this?  

View 3 Replies View Related

Order / Rank Results

Feb 8, 2006

Hi,

i want to create a report so that a list of the top 30 records are returned to the report user. In the report i want to have the records position in the list shown (ie the first row should have 1. and the second should be 2. right on down to the 30th having 30.)

how do i achieve this please?


many thanks
FatherJack

View 1 Replies View Related

Select Like And Order Results

Apr 25, 2008

Hello there,

I have two tables I selecting name using like with %string% from the two tables but I need to order the result comes from the two table:
1- the exact match for the search string come first from the two table.
2- and the partial match comes last after the exact match.

this is my DDL for the two tables :


USE [Northwind]
GO
/****** Object: Table [dbo].[Person] Script Date: 04/25/2008 14:33:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Person](
[PersonID] [int] NULL,
[Type] [char](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[email] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF


second table:
USE [Northwind]
GO
/****** Object: Table [dbo].[Members] Script Date: 04/25/2008 14:33:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Members](
[MemberID] [int] NULL,
[Type] [char](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Email] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF


and this my search query I have it in a stored Proc.


select *

from

(





SELECT PersonID, Type, Name, email


FROM Person
WHERE (Name LIKE '%'@Name'%')
union all

SELECT PersonID, Type, Name, email


From Members
WHERE (Name Like '%'@Name'%' )

) Y



Order by

Case[Name] when @Name Then 1 Else 2 End,

Case[Name] when 'm' Then 1 Else 2 End

Thank you for your time
Sms

View 5 Replies View Related

How To Order Search Results By Relevance?

Jul 3, 2007

I need to order my search results by relevance to the keywords entered by the user, how can i do that in sql ?

View 6 Replies View Related

Order Results By Date Not Working

Oct 3, 2006

hi. i'm trying to order my results ascending by date except i'm getting some really weird output. my ouput resembles something like this:

oct 2
oct 3
sep 13
sep 21
sep 22
sep 30
aug 3
aug 5
aug 16

the data is stored in a date field. i use getdate when inserting the date to the database. is there a reason why the dates are showing up weird and not ordering appropriately? thanks for your help.

also, can you not search here any more? i keep getting timeout errors.

View 7 Replies View Related

Concatenate Results In Specific Order

Jul 24, 2013

I am trying to Concatenate resulting classification names (X_DSC_CD_ABR below) in the following order (if the classification exists), separated by '/': WC/STD/LTD/FMLA/State/Military/Paid/Corporate/PFL/Other

Examples:
a. STD/FMLA
b. STD/LTD/FMLA/Other

View 2 Replies View Related

Ordering Results By Order Of The IN' Clause

Jul 28, 2006

Consider this SQL:SELECT my_field FROM my_table WHERE my_field IN ('value2', 'value1','value3')Simple enough, but is there anyway to specify that the result should beordered exactly like the "IN" clause states? So when this recordsetcomes back, I want it like this:my_field------------value2value1value3Possible?Deane

View 5 Replies View Related

MS Access- TOP / Offset? I Need To Order Results As Pages

Feb 18, 2005

Hi,

Sorry I have to post this here, but its sort of related to MS SQL anyway

I'm running a PHP system with MS Access. I need to order results in pages. (For those who are familiar with MySqL and Postgresql - I need the equivalent to LIMIT/OFFSET in MS Access).

I know I can "SELECT TOP 50" in my sql - so that solves the number of results per page.
But what about page 2,3,4..etc.... how do I select results from an offset?

There doesnt seem to be a solution for it

Thanks!

View 2 Replies View Related

SQL Server 2012 :: Get Results In A Specific Order?

Sep 11, 2014

I have a simple example of what I am trying to do. Here is some code to make a quick table to demonstrate:

create table #students
(
lastname varchar(50)
,firstname varchar(50)
,address1 varchar(50)

[Code].....

I want to select all the records, and them them be in alphabetical order first by lastname, then by firstname, then by address. HOWEVER, and this is the tricky part, I want to group names together that have the same address. So, in this example, I want the results to be in this order:

HallC6309 N Olive
HallP6309 N Olive <---- grouped with the C record because they have the same address
HallE5488 W Catalina <---- back to alphabetical by first name
HallJ7222 N Cocopas

View 7 Replies View Related

Brain Teaser - Stagger The Order Of The Results

Sep 5, 2005

This one has been stumping me for several days. I can run a query thatreturns several different items from several different manufacturers,each with a ranking score. Each manufacturer can have any number ofitems:Item_Name Manufacturer rankItem 1 Manu_A 82Item 2 Manu_A 65Item 3 Manu_A 41Item 4 Manu_B 32Item 5 Manu_C 21Item 6 Manu_B 19However, I would like the records to be ordered so that the highestranking item is shown first, then the next highest item from adifferent manufacturer is shown second, then the next highest item froma third manufacturer is show, etc.:Item 1 Manu_A 82Item 4 Manu_B 32Item 5 Manu_C 21Item 2 Manu_A 65Item 6 Manu_B 19Item 3 Manu_A 41Does anyone have any thoughts on how to order the results in thisfashion?thanks,Matt Weiner

View 2 Replies View Related

3 Results From One Field - Show Levels In Right Order

Nov 19, 2007


Hi there

We have a web application (database) that uses one field called Application and another called TicketType.

When a user fills out a ticket they can choose up to 3 levels of this field.
Eg Application, Application2, Application3

Eg TicketType, TicketType2, TicketType3

The extra two levels not being compulsory.

I am using sql server 2005 // Reporting Services

My query is as below:
SELECT Ticket.TicketNumber, Ticket.CreatedDate, Application_2.ApplicationName AS Application, Application_1.ApplicationName AS [App 2],
Application.ApplicationName AS [App 3], TicketType_2.TicketTypeName AS Tickettype, TicketType_1.TicketTypeName AS [Type 2],
TicketType.TicketTypeName AS [Type 3], Ticket.Description, Company.CompanyName
FROM Ticket INNER JOIN
TicketType AS TicketType ON Ticket.TicketTypeID = TicketType.TicketTypeID LEFT OUTER JOIN
TicketType AS TicketType_1 ON TicketType.ParentTicketTypeID = TicketType_1.TicketTypeID LEFT OUTER JOIN
TicketType AS TicketType_2 ON TicketType_1.ParentTicketTypeID = TicketType_2.TicketTypeID INNER JOIN
Application AS Application ON Ticket.ApplicationID = Application.ApplicationID INNER JOIN
Company ON Application.CompanyID = Company.CompanyID FULL OUTER JOIN
Application AS Application_1 ON Application.ParentApplicationID = Application_1.ApplicationID FULL OUTER JOIN
Application AS Application_2 ON Application_1.ParentApplicationID = Application_2.ApplicationID
WHERE (Ticket.CreatedDate >= @StartDate)
ORDER BY Ticket.TicketNumber



End result looks like this:





Application

App 2

App 3

TicketType

Type 2

Type 3


Software

Internal Apps

proACT





SW Other






Office Issues





General




Application

Click Track server



Alert (App)

Service




Network

Other





Network Fault


Software

Internal Apps

Other



User Account

New




Hardware

Network





HW Fault




Application

Click Track server



Alert (App)

Disk space






Office Issues





General






proACT



Configuration

Deployment


Software

Server Software

SharePoint



SW Fault

App Failure (Function)


Software

Server Software

SharePoint



SW Fault

App Failure (Function)


Ultimately I would like the Application (TicketType) fields to have the Master Information in it and the other two fields populated in order as well.

Can someone help please.


Please ask if I haven't explained myself.

thanks
Dianne

View 9 Replies View Related

Best Way To Order Results Sequentially Starting From Somewhere In The Middle

Apr 19, 2007

I'm working with SQL Server 2005, and I'm trying to sort the results based on a user selected letter. Say the user selects 'D' to filter his results. I'd like to return the results starting from D followed by E, F, G...Z, A, B, C. What I'm getting is the results for the D entries at the top of the result set, followed by A, B, C, E...Z.

A solution comes to mind that would be very long and db intensive, by querying on 'like 'D', followed by like 'E', followed by like 'F', etc, but I'm sure that there is a much more efficient way to do this. Below is the code that I'm using now.





' where @SortString = 'd' and @Test is a temp Table



BEGIN

Insert into @Test

Select CompanyName,ContactId, CompanyId

from vContacts where CompanyName like @SortString +'%'

Order by CompanyName



Insert into @Test

Select CompanyName,ContactId, CompanyId

from vContacts where CompanyName not like @SortString +'%'

Order by CompanyName

END



Thanks in advance for your help

View 3 Replies View Related

Extract Distinct Information And Order The Results

Sep 24, 2007

Hi,

MSSQL 2000 T-SQL

I have a problem in extracting information pertaing to a key value and matching that key value to another transaction but the order is based on another value in the same row.


I've attached a sample of DB data below.

tran_nr ret_ref_no msg_type description
5111 12345 420 reversal
5112 12345 200 auths
5113 15236 200 auths
5114 46587 200 auths
5115 46587 420 reversal

Requirement using the above data is to extract data where the ret_ref_no is the same for more than one row but also check that the msg_type 420 happens before the 200. Is there a way of retrieving the information in this way using the tran_nr coloumn values? The tran_nr values is basically the serial number when the transaction is wrriten away to the DB.

I've managed only to retrive the 1st half of my query whereby the same ret_ref_nr is being used by more then one transaction. Still need to figure out the 2nd part where the msg_type of 420 happens before the 200.


SELECT * FROM SAMPLE
WHERE ret_ref_no in
(
SELECT ret_ref_no FROM SAMPLE
GROUP BY ret_ref_no HAVING COUNT(*) > 1
)

Results of query
5111 12345 420 reversal
5112 12345 200 auths
5114 46587 200 auths
5115 46587 420 reversal

If someone could assist with only retreiving the above results in bold to the query analyser i will really appreciate it.

Regards
Deceptive

View 9 Replies View Related

Order By Cluase Cause Wrong Results To Be Returned.

Sep 10, 2007

I have the follow table.

/****** Object: Table [dbo].[deletethisTempOut] Script Date: 09/10/2007 09:20:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[deletethisTempOut](
[ThemeName] [varchar](60) NULL,
[intLocationCount] [int] NULL,
[dblRepValueA] [float] NULL,
[dblRepValueB] [float] NULL,
[dblRepValueC] [float] NULL,
[dblRepValueD] [float] NULL,
[dblTotalRepValue] [float] NULL,
[dblLimit1] [float] NULL,
[dblLimit2] [float] NULL,
[dblLimit3] [float] NULL,
[dblLimit4] [float] NULL,
[dblTotalLimit] [float] NULL,
[fltEmployeecount] [float] NULL,
[intAreaLevel1] [tinyint] NOT NULL,
[strFullName] [varchar](13) NOT NULL,
[strAreaLevel2] [varchar](20) NOT NULL,
[strAreaLevel3] [varchar](20) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF

If I use the following SQL:

SELECT ThemeName, intLocationCount, dblRepValueA, dblRepValueB, dblRepValueC, dblRepValueD, dblTotalRepValue, dblLimit1, dblLimit2, dblLimit3,
dblLimit4, dblTotalLimit, fltEmployeecount, intAreaLevel1, strFullName, strAreaLevel2, strAreaLevel3
FROM deletethisTempOut
ORDER BY strAreaLevel2, strAreaLevel3
GET Following correct results:

















Adair
284
899989594
0
574857716
190479902
1665327212
0
0
0
0
1665327212
0
1
United States
1
1
IF I use the following SQL I get the wrong results:

SELECT ThemeName, intLocationCount, dblRepValueA, dblRepValueB, dblRepValueC, dblRepValueD, dblTotalRepValue, dblLimit1, dblLimit2, dblLimit3,
dblLimit4, dblTotalLimit, fltEmployeecount, intAreaLevel1, strFullName, strAreaLevel2, strAreaLevel3
FROM deletethisTempOut
ORDER BY ThemeName

WRONG results:
















Adair
74
81733110
0
49616018
24671651
156020779
50510500
0
0
0
203870779
0
1
United States
50
1

Adair
437
1468698657
0
495479839
353202768
2317381264
12984266
0
0
0
2315676030
0
1
United States
25
1

Adair
1813
20309722045
0
6597005374
4253819645
31160547064
43636703
0
0
0
31135010742
0
1
United States
11
1

Adair
606
439581417
0
331746662
132240332
903568411
0
0
0
0
903568411
0
1
United States
45
1

Adair
236
350256381
0
524269553
504973831
1379499765
4080368
0
0
0
1380473415
0
1
United States
23
1etc.....

View 6 Replies View Related

SQL7: Order Of Values In IN Clause Affects Results

Dec 14, 1999

Hi!
Has anyone experienced this problem?
Certain queries that work fine in SQL 6.5 and Oracle return inconsistent / inaccurate results in SQL 7 (with SP1). These queries include an IN clause with a range of values.
For example, the following query:
SELECT columnA, columnB, columnC, columnD
FROM table
WHERE columnD = 'I'
AND columnA IN (1,2,3,11,19)
go

returns a different result than this query:
SELECT columnA, columnB, columnC, columnD
FROM table
WHERE columnD = 'I'
AND columnA IN (1,3,11,2,19)
go

The only way we have stumbled upon to get accurate results consistently is to order the range values from largest to smallest:
AND columnA IN (19,11,3,2,1)

Have not seen this documented anywhere. We are in the process of re-ordering these ranges in our code, but I welcome any ideas or comments...
Thanks!

View 2 Replies View Related

Invalid Results For Order By On Select Query Against Table Variable

Jan 21, 2008

I am attempting to sort the results of a query executed against a table variable in descending order. The data is being inserted into the table variable as expected, however when I attempt to order the results in descending order, the results are incorrect. I have included the code as well as the result set.


DECLARE @tblCustomRange AS TABLE

(

RecordID INTEGER IDENTITY(1,1),

RangeMonth INTEGER,

RangeDay INTEGER

)


DECLARE @Month INTEGER

DECLARE @Day INTEGER


-- Initialize month and day variables.

SET @Month = 8

SET @Day = 11

-- Insert records into the table variable.
INSERT INTO @tblCustomRange

(RangeMonth, RangeDay) VALUES (1,2)

INSERT INTO @tblCustomRange

(RangeMonth, RangeDay) VALUES (1,27)

INSERT INTO @tblCustomRange

(RangeMonth, RangeDay) VALUES (6,10)

INSERT INTO @tblCustomRange

(RangeMonth, RangeDay) VALUES (9,22)

INSERT INTO @tblCustomRange

(RangeMonth, RangeDay) VALUES (12,16)


-- Select everything from the table variable ordering the results by month, day in
-- descending order

SELECT * FROM @tblCustomRange

WHERE (RangeMonth < @Month) OR

(RangeMonth = @Month AND RangeDay <= @Day)

ORDER BY RangeMonth, RangeDay DESC



I am getting the following resultset:


RecordID RangeMonth RangeDay

----------- ----------- -----------

2 1 27

1 1 2

3 6 10



I am expecting the following resultset:


RecordID RangeMonth RangeDay

----------- ----------- -----------

3 6 10

2 1 27

1 1 2

View 1 Replies View Related

SQL Server 2012 :: List Of Order Numbers Based On Stock Availability - Filter Results?

Dec 23, 2014

Trying to build a list of order numbers based on stock availability.

The data looks something like this:

OrderNumber Stockcode quantityordered quantityinstock
123 code1 10 5
123 code2 5 10
124 code3 15 20
124 code4 10 10

In this case I would like to output a single result for each order, but based on stock availability order 123 is not a complete order and 124 is so the results will need to reflect this.

View 1 Replies View Related

Strange, Very Strange (BIDS)

Jul 19, 2006

Hi everyone,

I€™m suffering a queer behaviour when I use BIDS. Concretely, when I open a dtsx from my project (it has 10 packages) many times Sequence Container and Data Flow tasks are invisible. I mean, its lines are not visible at all whereas its titles are. I mean, what you see is just a white box€¦

Then, I€™m gonna Data Flow layer and I have to do double-clik over the tasks and are visible but on Control Flow I don€™t see how to solve.

Curiously in our development and production server such behaviour doesn€™t happen (we are accessing by mean Terminal Server from our workstations)

How odd!. Everything is fine except this.

I want to remark you that such project has been copied from the server, this is, these packages are been built on the server

Thanks for your thougts or ideas,

View 5 Replies View Related

Express Will Not Load. Insurmountable Difficulties With Order Of Uninstalls/order Of Installs/ Suggestions Plz

Jan 7, 2007

Finding the "pieces of information" I need to successfully install the SQL Server Express edition is so complex. Uninstalls do "not" really uninstall completely, leading to failure of SQL install. Can you suggest a thorough, one-stop site for directions for the order of app uninstalls and then the order for app installs for the following...

SQL Server Express edition

Visual Studios 2005

Jet 4.0 newest upgrade

.Net Framework 2.0 (or should I use 3.0)

VS2005 Security upgrade

Anything else I need for just creating a database for my VS2005 Visual Basic project?

I was trying to use MS Access as my backend db but would like to try SQL Express



Thank you, Mark





View 7 Replies View Related

Conditional Order By - Sort Result Set By Employee Number Ascending Order

Sep 24, 2012

In SQL sERVER 2008, I have two fields - Depatment and Employees. I need to sort the result set by employee number ascending order, with following exception

1)when department number = 50 - the preferred order is Employee # - 573 followed by 551-572 (employee # belong to Dept 50 = 551-573)

2)When Department number = 20 – the preferred sort order is Employee # 213-220, followed by Employee # 201-213 (employee # belong to Dept 20 = 201-220)

How shall I achieve this?

View 4 Replies View Related

Analysis :: Order Of Rows In Tabular Table Not In Same Order Data Was Retrieved?

May 19, 2015

I never paid much attention to this before but I noticed this today in a new table I was creating.

For tables defined in the tabular model the table properties have something like SELECT Blah FROM TableName ORDER BY Blah Then in the tabular model the table's data is in the same order it was ordered by in the data source for the table.

I have a date table I setup and I noticed it is NOT respecting the sort order.

I have it sorted by DateID which sorts with the oldest date first and newest date as last row.However, the table that is imported and stored in the data model is not in that order.

I can of course manually sort the rows in BIDS/DataTools, but I find this discrepancy odd.

Would this have negative impacts on the EARLIER function for example if the data rows are not in the order specified?

View 8 Replies View Related

Calculate Total Amount Of Order Details Based On Particular Order

Apr 10, 2014

I have a query that calculate the total amount of order details based on a particular order:

Select a.OrderID,SUM(UnitPrice*Quantity-Discount)
From [Order Details]
Inner Join Orders a
On a.OrderID=[Order Details].OrderID
Group by a.OrderID

My question is what if I wanted to create a formula to something like:

UnitPrice * Quantity - DiscountAmount Where DiscountAmount = UnitPrice Quantity * Discount

Do I need to create a function for that? Also is it possible to have m y query as a table variable?

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved