Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





How To Use ORDER BY Clause In An SELECT DISTINCT Sql Query When AS SINGLECOLUMN Is Defined?


Hi,

I wonder if its possible to perform a ORDER BY clause in an SELECT DISTINCT sql query whereby the AS SINGLECOLUMN is used. At present I am recieving error: ORDER BY items must appear in the select list if SELECT DISTINCT is specified. My guess is that I cant perform the Order By clauses because it cant find the columns individually. It is essentail I get this to work somehow...

Can anyone help?
Thanks in advance

Gemma




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Expression Defined In SELECT Clause Overwrites Column Defined In FROM Clause
2 examples:
 
1) Rows ordered using textual id rather than numeric id


Code Snippet
select
 cast(v.id as nvarchar(2)) id
from
 (
  select 1 id
  union select 2 id
  union select 11 id
 ) v
order by
 v.id

 
 



Result set is ordered as: 1, 11, 2
I expect: 1,2,11

 
if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.
 
2) SQL server reject query below with next message
 
Server: Msg 169, Level 15, State 3, Line 16
A column has been specified more than once in the order by list. Columns in the order by list must be unique.

 


Code Snippet
select
 cast(v.id as nvarchar(2)) id
from
 (
  select 1 id
  union select 2 id
  union select 11 id
 ) v
 cross join (
  select 1 id
  union select 2 id
  union select 11 id
 ) u
order by
 v.id
    ,u.id

 


Again, if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.
 
It reproducible on
 
Microsoft SQL Server  2000 - 8.00.2039 (Intel X86)   May  3 2005 23:18:38   Copyright (c) 1988-2003 Microsoft Corporation  Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

 
and
 

Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86)   Feb  9 2007 22:47:07   Copyright (c) 1988-2005 Microsoft Corporation  Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)
 
In both cases database collation is SQL_Latin1_General_CP1251_CS_AS
 
If I check quieries above on database with SQL_Latin1_General_CP1_CI_AS collation then it works fine again.
 
Could someone clarify - is it bug or expected behaviour?

View Replies !
Problem Using WHERE Clause On 'SingleColumn'
 
Hello i have a query that returns the majority of the data into a SingleColumn. The problem i am having is using a WHERE and LIKE clause on this query:
SELECT DISTINCT (dbo.AuthorList(publicationID))+ '.' + ISNULL(' Editor: '+Publication.editor, '')+ '' + ISNULL(' '''+Publication.title+''' ', '')+ '' + ISNULL(' Book: '''+Publication.booktitle+''' ', '')+ '' + ISNULL(' '+Publication.type, '')+ '' + ISNULL(' '+Publication.journal, '')+ '' + ISNULL(' Series: '+Publication.series+'.', '')+ '' + ISNULL(' '+Publication.school, '')+ '' + ISNULL(' '+Publication.institution, '')+ '' + ISNULL(' '+Publication.organisation, '')+ '' + ISNULL(' '+Publication.month, '')+ '' + ISNULL(' ('+convert(nvarchar, Publication.year)+')', '')+ '' + ISNULL(' '+Publication.publisher, '')+ '' + ISNULL(' '+Publication.address+'.', '')+ '' + ISNULL(' '+Publication.howpublished, '')+ '' + ISNULL(' Ed: '+convert(nvarchar, Publication.edition)+'.', '')+ '' + ISNULL(' '+Publication.note, '')+ '' + ISNULL(' Vol '+Publication.volume+'.', '')+ '' + ISNULL(' No '+Publication.number+'.', '')+ '' + ISNULL(' Pages '+Publication.pages+'.', '')+ '' + ISNULL(' Chapter '+Publication.chapter+'.', '') AS SingleColumn, Publication.publicationID, Publication.abstract FROM Publication WHERE ([SingleColumn] LIKE '%' + @authorName + '%')">
The error says that SingleColumn is an invalid column name. I guess this is because the first part of the query is the part actually creating the existence of the SingleColumn. Is there any other way i can get round this?
 
Regards, 

View Replies !
Use Of User Defined In SELECT Clause
I'm having this query:SELECTss.subscription_id AS SubscriptionId,s.id AS ScopeId,s.[name] AS ScopeName,s.base AS ScopeBase,dbo.iqGetShapesByScopeAsString(s.id) AS ShapesAsStringFROMsubscription_scope ss,scope sWHEREss.subscription_id = @subscription_idANDss.scope_id = s.idORDER BYs.[name]The select only returns a single row but my database (SQL Server 2005CTP) seems to execute the "iqGetShapesByScopeAsString" function foreach row in the subscription_scope and scope tables. This is a bug,right? The function should be executed only once for each *returned*row in the SELECT, right? I believe that was the case in SQL 2k thoughI can't check it at the moment.// pt

View Replies !
How Do I Use Order By When I Use Select Distinct.
Hi
    I have a query which returns some rows.. what happens if i use a select distinct instead of a select.. this is my sproc
 DECLARE @Counter TABLE(
PlanId int,
FundId int,
ClientFundName varchar(110),
DisplayOrder int IDENTITY(1,1),
IsDefault bit,
IsPortfolioFundOnly bit
)
INSERT INTO @Counter
(
PlanId,
FundId,
ClientFundName,
IsDefault,
IsPortfolioFundOnly
)
SELECT
5923,
f.FundId,
d.FundName,
CASE WHEN d.FundDefault IS NULL THEN 0 ELSE 1 END,
CASE WHEN Lower(p.FundType) = 'modfundonly' THEN 1 ELSE 0 END
FROM
PlanDetail d
INNER JOIN Statements..Fund f
ON d.CUSIP = f.CUSIP
OR
d.Ticker = f.Ticker
OR
d.Ticker = f.ClientFundId
OR
d.CUSIP = f.ClientFundId
-- Do an internal join on the PlanDetail table to get the value of the FundType to derive whether
--fund can only be chosen as part of a portfolio.
LEFT JOIN PlanDetail p
ON d.FundName = p.FundName
AND
d.PortfolioName = p.PortfolioName
WHERE
d.PlanNumber IS NOT NULL
AND
p.PortFundPercent IS NULL
GROUP BY
f.FundId,
d.FundName,
d.FundDefault,
--d.PlanNumber,
--d.Cusip,
-- d.Ticker,
--d.RowNumber,
p.FundType

ORDER BY
Min(d.PlanNumber),
Min(d.RowNumber)


 any help will be appreciated.
Thanks
Karen

View Replies !
SELECT DISTINCT W/ORDER BY
I get the "ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

SELECT DISTINCT
pdm.Account,
pdm.Customer
FROM
dbo.Demands pdm LEFT OUTER JOIN
dbo.Tickets rct ON pdm.Account = rct.Account
WHERE
pdm.Code IN (66, 51)
ORDER BY
pdm.TransactionDate DESC

Is there any way to make the ORDER BY work in this case?

View Replies !
SELECT DISTINCT Type ORDER BY
I am trying to display items from a table that have a type. For each condition there are between 7 and 10 types. I am looping through each type and displaying all items in that type. I am using DISTINCT to pull the types and count them, so I know how many there are and how times to loop. My problem is that DISTINCT is ordering the types alphabetically! I want them in the same order they went into the table. I tried adding ORDER BY primaryID, but got an error that said I also had to select primaryID as well as type, so now I am selecting every item that fits the condition and not just the DISTINCT types! Is there any way to make it order by column_position? I am using SQL 2K.

View Replies !
How Can I Use SELECT DISTINCT And Maintain The Original Order
Say I have a result set with two fields numbers and letters.

1 A3 A1 B2 B


 The result set is ordered by the letters column. How can I select the distinct numbers from the result set but maintain the current order? When I tryselect distinct Number from MyResultSet

it will reorder the new result set by the Number field and return

123

 However, I'd like maintain the Letter order and return

132

View Replies !
SELECT DISTINCT MyId Order By MyDate
I have the following records,
MyDate MyId
2003/10/25 2
2003/10/26 3
2003/10/26 1
2003/10/27 3
2003/10/28 2
2003/10/29 4

I want to get the most earlier date distinct records.
I try to use "SELECT DISTINCT MyID from Table;"
I expect to get Myid: 2,3,1,4
But the computer returns Myid:1,2,3,4

Is there a way to get the records using
"SELECT DISTINCT MyID from Table ORDER BY MyDate;"

Appreciate help......

View Replies !
SELECT DISTINCT And ORDER BY With Aliased Column
 

This query demonstrates a problem I have run across:
 

USE AdventureWorks

GO

-- This query works fine.

SELECT DISTINCT FirstName AS Name1 FROM Person.Contact ORDER BY FirstName

GO

-- This query also works fine.

SELECT ISNULL(FirstName, '') AS Name1 FROM Person.Contact ORDER BY FirstName

GO

-- This query returns error 145

SELECT DISTINCT ISNULL(FirstName, '') AS Name1 FROM Person.Contact ORDER BY FirstName

GO

 
The last query returns the error "ORDER BY items must appear in the select list if SELECT DISTINCT is specified".
It will work if I change ORDER BY to use "Name1" instead of "FirstName", but in the situation I have at hand, the query is generated by third-party software and I don't have the ability to change it.
Can anyone explain why what's going on here?  Oddly, this same query will work if I run it against SQL Server 2000.

View Replies !
CROSSTAB Query In Defined Order
Taken from another post, the sql listed further below creates/uses the input table
ID ITEM
1 a
1 b
2 a
2 c
2 d
3 b
3 z


and with the SELECT statement returns
ID items
1 a, b
2 a, c, d
3 b, z

The items are sorted in alphab. order (using Min) but I HAVE A 3RD FIELD IN THE INPUT TABLE THAT ORDERS THE ITEMS SO INPUT TABLE NOW IS:
ID ITEM ORDER
1 a 32
1 b 15
2 a 32
2 c 11
2 d 45
3 b 15
3 z 99

SO THE OUTPUT TABLE LOOKS SHOULD BE (items with smaller Order no are added first):
ID items
1 b, a
2 c, a, d
3 b, z

ANY IDEAS on HOW TO CHANGE THE FOLLOWING SQL TO DO THAT?
I've tried ordering the input table on ID, ORDER fields and then using the SELECT statement listed below but it adds the items in alphab. order which I guess it should do since it's using Min. I also tried using the ORDER field in the joins instead of the ITEM field but still didn't work. ANY IDEAS???



CREATE TABLE dbo.table00 (
id INT NOT NULL
, item CHAR(1) NOT NULL
)

INSERT INTO dbo.table00 (id, item)
SELECT 1, 'a'
UNION ALL SELECT 1, 'b'
UNION ALL SELECT 2, 'a'
UNION ALL SELECT 2, 'c'
UNION ALL SELECT 2, 'd'
UNION ALL SELECT 3, 'b'
UNION ALL SELECT 3, 'z'

SELECT a.id, Min(a.item)
+ Coalesce(', ' + Min(b.item), '')
+ Coalesce(', ' + Min(c.item), '')
FROM dbo.table00 AS a
LEFT JOIN dbo.table00 AS b
ON (b.id = a.id
AND a.item < b.item)
LEFT JOIN dbo.table00 AS c
ON (c.id = a.id
AND b.item < c.item)
GROUP BY a.id
ORDER BY a.id

View Replies !
Using The ORDER BY Clause When The Ordered Column Is Not Needed In The SELECT Statement
Greetings,
 
I have a C# application that calls a stored procedure to query the database (MSSQL 2005).   I only have one field/column returned from the query but I need that column ordered.
 
How do I use the ORDER BY clause without returning the index column which does the sorting?  The first example is NOT what I want.  I want something that works like the second example which only returns the 'Name' column.
 

ALTER PROCEDURE [dbo].[MyProcedure]



AS

BEGIN

SELECT DISTINCT A.Name, A.index

FROM
...
...
ORDER BY A.[Index], A.Name ASC

END
 
 

ALTER PROCEDURE [dbo].[MyProcedure]



AS

BEGIN

SELECT DISTINCT A.Name
FROM
...
...
ORDER BY A.[Index]

END
 
Thanks

View Replies !
Order By Clause In DECLARE CURSOR Select Statement Won't Compile
The stored procedure, below, results in this error when I try to compile...


Msg 156, Level 15, State 1, Procedure InsertImportedReportData, Line 69
Incorrect syntax near the keyword 'ORDER'.

However the select statement itself runs perfectly well as a query, no errors.

The T-SQL manual says you can't use the keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO in a cursor select statement, but nothing about plain old ORDER BYs.

What gives with this?

Thanks in advance
R.

The code:




Code Snippet

-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF object_id('InsertImportedReportData ') IS NOT NULL
    DROP PROCEDURE InsertImportedReportData
GO
-- =============================================
-- Author:        -----
-- Create date:
-- Description:    inserts imported records, marking as duplicates if possible
-- =============================================
CREATE PROCEDURE InsertImportedReportData
    -- Add the parameters for the stored procedure here
    @importedReportID int,
    @authCode varchar(12)
AS
BEGIN
    DECLARE @errmsg VARCHAR(80);

--    SET NOCOUNT ON added to prevent extra result sets from
--     interfering with SELECT statements.
    SET NOCOUNT ON;

    --IF (@authCode <> 'TX-TEC')
    --BEGIN
     --   SET @errmsg = 'Unsupported reporting format:' + @authCode
      --  RAISERROR(@errmsg, 11, 1);
    --END

    DECLARE srcRecsCursor CURSOR LOCAL
    FOR    (SELECT
           ImportedRecordID
          ,ImportedReportID
          ,AuthorityCode
          ,[ID]
          ,[Field1] AS RecordType
          ,[Field2] AS FormType
          ,[Field3] AS ItemID
          ,[Field4] AS EntityCode
          ,[Field5] AS LastName
          ,[Field6] AS FirstMiddleNames
          ,[Field7] AS Title
          ,[Field8] AS Suffix
          ,[Field9] AS AddressLine1
          ,[Field10] AS AddressLine2
          ,[Field11] AS City
          ,[Field12] AS [State]
          ,[Field13] AS ZipFull
          ,[Field14] AS OutOfStatePAC
          ,[Field15] AS FecID
          ,[Field16] AS Date
          ,[Field17] AS Amount
          ,[Field18] AS [Description]
          ,[Field19] AS Employer
          ,[Field20] AS Occupation
          ,[Field21] AS AttorneyJob
          ,[Field22] AS SpouseEmployer
          ,[Field23] As ChildParentEmployer1
          ,[Field24] AS ChildParentEmployer2
          ,[Field25] AS InKindTravel
          ,[Field26] AS TravellerLastName
          ,[Field27] AS TravellerFirstMiddleNames
          ,[Field28] AS TravellerTitle
          ,[Field29] AS TravellerSuffix
          ,[Field30] AS TravelMode
          ,[Field31] As DptCity
          ,[Field32] AS DptDate
          ,[Field33] AS ArvCity
          ,[Field34] AS ArvDate
          ,[Field35] AS TravelPurpose
          ,[Field36] AS TravelRecordBackReference
      FROM ImportedNativeRecords
      WHERE ImportedReportID IS NOT NULL
      AND ReportType IN ('RCPT','PLDG')
     ORDER BY ImportedRecordID  -- this should work but gives syntax error!
    );

END

View Replies !
SQL Query Help-- Order By Clause
HiI want a simple select query on a column-name (smalldatetime) withvalues dislayed in desc order with null values FIRST.i.e.Select orderdate from ordersorder by ( null values first and then orderdate in desc order)could any one please helpThanks

View Replies !
Need An Special ORDER BY Clause Query
Table:ColumnsUsersList:UserID, UserName, Country
I need a query which select all the rows from the above mentioned table with all fieldsButThe order the rows is First all the users from "Pakistan"Second all the users from rest of the countries except "Pakistan" in ascending order
So the query first return all the users from Pakistan and the the users from rest of the world in ascending order.
Forexample,
1, ABC, USA2, XYZ, Saudi Arabia3, LMN, Pakistan4, TQR, India5, PTR, Afghanistan
then the query returns.
3, LMN, Pakistan5, PTR, Afghanistan4, TQR, India2, XYZ, Saudi Arabia1, ABC, USA

View Replies !
Query Performance With Order By Clause?
Hi all,Just wondering if anyone can tell me if an order by clause on a selectquery would have any impact on the time it takes to retrieve results?Essentially I'm selecting Top 1 out of a table via various criteriaand currently getting it back without an order by clause. The order bywould only include the column that has the clustered primary index onit.Can anyone tell me if in theory this will slow the query down?Many thanks in advance!Much warmth,Murrau

View Replies !
ERROR: The Nested Query May Be Missing An ORDER BY Clause.
Hi,

on executing the below query i am getting the following error

ERROR:  Errors in the back-end database access module. Nested table keys in a SHAPE query must be sorted in the same order as the parent table. The nested query may be missing an ORDER BY clause.

even though the order by clause is presenet in the nested query

SELECT  t.[ProductId],  Predict ([Association].[Product Basket],3)
From
  [Association]
PREDICTION JOIN
  SHAPE {
  OPENQUERY([Adventure Works Cycle MSCRM],
    'SELECT DISTINCT [ProductId] FROM (SELECT ProductId FROM ProductBase) as [Product] ORDER BY [ProductId]')}
  APPEND
  ({OPENQUERY([Adventure Works Cycle MSCRM],
    'SELECT [ProductId] FROM (SELECT ProductId FROM ProductBase) as [Product] ORDER BY [ProductId]')}
    RELATE [ProductId] To [ProductId]
  )
    AS
      [Product] AS t
ON
  [Association].[Product Id] = t.[ProductId] AND
  [Association].[Product Basket].[Product Id] = t.[Product].[ProductId]

View Replies !
DISTINCT SELECT Query With More Than One Field
Hello, I want to do a DISTINCT  SELECT query with more than one field, for example a ID field with a Type field, as if both fields make the primary key, like (ID 1 ,Type 1) ,( ID 1, Type 2) and (ID 2, Type 1) is ok but not (ID 1, Type1) and (ID 1,Type 1) if its not possible to do a distinct with more than one then what other techniques are possible to get the duplicate data out.   the reason why I want to use distinct is that I can use that query to export that data to where both of these fields make the primary key.
Thanks in advance

View Replies !
Difficult Select Distinct Query
Hi,I have a table as followingaa Text1 aa, Join Bytes!, 15267aa Text1 aa, Join Bytes!, 16598aa Text1 aa, Join Bytes!, 17568aa Text2 aa, Join Bytes!, 25698aa Text3 aa, Join Bytes!, 12258I have to write a query as follows ...SELECT DISTINCT TOP 500 fldText, fldContact, fldItemidFROM tableWHERE fldCat = 10 AND CONTAINS (fldText, 'Text1')In the example you can see the table has rows in which text and contact ordouble but with different itemid's. Now my employer wants me to show only 1row when text and contact or the same. He doesn't mind which itemid I show.... but I have to show one.I've an idea of how to do this using a cursor and a temporary table but Iguess that will be fatal for the performance because then I have to loopthrough all selected rows, check each row with all other rows and store theprimary key in the temporary table if dedected it isn't double. AfterwardsI can execute ... SELECT ... FROM TABLE where primary key in (selecttemp_primarykey from #temptable).I hoped I could do everything in 1 "easy" SELECT but I should not know how?Any ideas are much appreciated.Thanks a lot.Perre Van Wilrijk.

View Replies !
Query Help - Select Distinct Possibly?
I need to return the current case cost for every UPC in my table. In my current query I return case costs that have an effective date of today or earlier. The problem is that in my results, one UPC may have two or more case costs that were are effective <= GETDATE(). I can sort it by effective date (DESC) so I know the first of every UPC in my results will be the current effective case cost, but how do I modify my query so that in my result set I only get the first of every UPC?

Here is my query:

SELECT factCaseCosts.nUpcKey, factCaseCosts.dCaseCost, factCaseCosts.dtEffectiveDate
FROM factCaseCosts
WHERE (factCaseCosts.dtEffectiveDate <= GETDATE())
ORDER BY dtEffectiveDate DESC

Here is my current result set:
52023.762006-08-01 00:00:00
52023.762006-02-18 00:00:00
52123.762006-08-01 00:00:00
52123.762006-02-18 00:00:00
52230.362006-08-01 00:00:00
52230.362006-02-18 00:00:00
52323.762006-08-01 00:00:00
52323.762006-02-18 00:00:00

I only want the first 520 returned, the first 521 returned, the first 522 returned, and the first 523 returned.
How can I do this?
Thanks!

View Replies !
SELECT Distinct Query Problem
Hello,

I'm reasonably new to SQL.

I have a table of information about meetings with various people. In it, I have the person's name and the date/time of the meeting (simplified example).

I need to write a query that SELECTs only the most recent meeting for each person.

Any ideas would be greatly appreciated.

View Replies !
GROUP By Clause Or DISTINCT Clause
Hi, can anyone shed some light on this issue?SELECT Status from lupStatuswith a normal query it returns the correct recordcountSELECT Status from lupStatus GROUP BY Statusbut with a GROUP By clause or DISTINCT clause it return the recordcount= -1

View Replies !
Inconsistent Sort Order Using ORDER BY Clause
I am getting the resultset sorted differently if I use a column number in the ORDER BY clause instead of a column name.

Product: Microsoft SQL Server Express Edition
Version: 9.00.1399.06
Server Collation: SQL_Latin1_General_CP1_CI_AS

for example,

create table test_sort
( description varchar(75) );

insert into test_sort values('Non-A');
insert into test_sort values('Non-O');
insert into test_sort values('Noni');
insert into test_sort values('Nons');

then execute the following selects:
select
*
from
test_sort
order by
cast( 1 as nvarchar(75));

select
*
from
test_sort
order by
cast( description as nvarchar(75));

Resultset1
----------
Non-A
Non-O
Noni
Nons

Resultset2
----------
Non-A
Noni
Non-O
Nons


Any ideas?

View Replies !
Order By Clause In View Doesn't Order.
I have created view by jaoining two table and have order by clause.

The sql generated is as follows

SELECT     TOP (100) PERCENT dbo.UWYearDetail.*,  dbo.UWYearGroup.*
FROM         dbo.UWYearDetail INNER JOIN
                      dbo.UWYearGroup ON dbo.UWYearDetail.UWYearGroupId = dbo.UWYearGroup.UWYearGroupId
ORDER BY dbo.UWYearDetail.PlanVersionId, dbo.UWYearGroup.UWFinancialPlanSegmentId, dbo.UWYearGroup.UWYear, dbo.UWYearGroup.MandDFlag,
                      dbo.UWYearGroup.EarningsMethod, dbo.UWYearGroup.EffectiveMonth

 

If I run sql the results are displayed in proper order but the view only order by first item in order by clause.

Has somebody experience same thing? How to fix this issue?

Thanks,

 

View Replies !
Select DISTINCT On Multiple Columns Is Not Returning Distinct Rows?
Hi, I have the following script segment which is failing:

CREATE TABLE #LatLong (Latitude DECIMAL, Longitude DECIMAL, PRIMARY KEY (Latitude, Longitude))

INSERT INTO #LatLong SELECT DISTINCT Latitude, Longitude FROM RGCcache



When I run it I get the following error: "Violation of PRIMARY KEY constraint 'PK__#LatLong__________7CE3D9D4'. Cannot insert duplicate key in object 'dbo.#LatLong'."



Im not sure how this is failing as when I try creating another table with 2 decimal columns and repeated values, select distinct only returns distinct pairs of values.

The failure may be related to the fact that RGCcache has about 10 million rows, but I can't see why.

Any ideas?

View Replies !
Invalid Results For Order By On Select Query Against Table Variable
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 Replies !
Order By Because Of Distinct
I have a strange situation (I think). Within a view (which explains why I use the top 100% --> to use an order by) I have this query:

select TOP 100 PERCENT *
from tbOfferDetails
where ofd_id = ofd_parent and ofd_fk_off_id = 100

This gives me the following results:
ofd_fk_off_id off_fk_class_id
100 2753
100 2753
100 2071
100 2753

Now I change the query to:

select distinct ofd_fk_off_id, ofd_fk_class_id from
(select TOP 100 PERCENT *
from tbOfferDetails
where ofd_id = ofd_parent and ofd_fk_off_id = 100
order by ofd_sequence ASC ) as tbOffers

This gives me the following results:
ofd_fk_off_id off_fk_class_id
100 2071
100 2753

In the execution plan, it says that a distinct order by is used on off_fk_class_id. My question is: why is this done? I want only a distinct and not an order by. So is there a way to change this (default?) behaviour.

View Replies !
Distinct With Order By
It gives me this error:
ORDER BY clause (TimeStamp) conflicts with Distinct

The sql statement is:

sql Code:






Original
- sql Code




SELECT DISTINCT division from table order by Stamp DESC






SELECT DISTINCT division FROM TABLE ORDER BY Stamp DESC



I've tried:

sql Code:






Original
- sql Code




SELECT DISTINCT division, Stamp FROM table ORDER BY Stamp DESC






SELECT DISTINCT division, Stamp FROM TABLE ORDER BY Stamp DESC


But this produces duplicate rows, which in this specific case is unacceptable.

Is there any way I can acheive what I want?
Stamp is a TimeStamp if you couldn't figure it out. I just want the last one entered, but all the last ones entered per division. . .

View Replies !
Not Part Of DISTINCT Clause But I Do Want It Selected
I get the rows(records) I want by removing the RequestDateTime column from the Select query SELECT distinct et.configname as 'Part Number', substring(email,(charindex('@',email)+1),len(email)) as 'email ending',u.company_name as 'Company',u.city as 'City',u.country as 'Country' --,RequestDateTime as 'Date Downloaded'from  new_products.dbo.modelrequests etleft outer join  cc_host.dbo.usr_list u on et.username = convert(varchar(50),u.[user_id])where interfacename like '%download%'and result=0and u.country = 'JP'and CONVERT(DATETIME, RequestDateTime, 102)>= convert(DATETIME,'12/5/2007', 102)GROUP BY email,et.configname,u.company_name,u.city,u.country,requestdatetime  I want to show the RequestDateTime for the 1600 records that do get selected. How can I put RequestDateTime back in the resulting table output without it being part of the Distinct clause? 

View Replies !
When Does Ssrs Use A DISTINCT Clause In It's Queries?
I am having a heck of a time figuring out what controls how/when the generated SQL for a report puts a DISTINCT clause in front of it. 
 
For instance, not that this report makes any sense, but I have 58 rows in my fact table/entity €“ If I pull in a lookup  field and execute, the distinct is put in the query and I basically get a list of the possible domain values.  It runs the whole joined table query to get them, but it does list (in this case) just 4 records.  Now I put in the primary ID of the fact entity and the distinct goes away and I get my 58 rows.  If I put two lookup fields, the DISTINCT is back.  If I pull in the description field (text string just a direct source field mapping not part of the identifying attributes), the distinct is there.   If I pull in the Company Name field on a different entity (which is essentially the same as pulling in Description only it is part of the identifying attributes), there is no DISTINCT.  I can pull in all my fields on this entity and none of them drive the distinct.  And I swear (ok, I am probably lying but not on purpose) the field/attribute and roles properties are all the same on the attributes.  But you get my general question/situation...
 
Any insight for me?  Does it have to do with how I am building the report rather than the underlying model?
 
Thanks in advance,

View Replies !
SQL Distinct Value And Order By Some Field......
Dear all,In SQL Server 2000 , how to get distinct records sort by onefield .ExampleSELECT DISTINCT A FROM tblTEST ORBER BY BHere, In TableField 'A' contain more than one same data...Field 'B' contain all are different Data......I want distince in Field 'A' and order by Field 'B'..... how to getit.........regardskrishnan

View Replies !
DISTINCT Requires ORDER BY
OK I am trying the following select statement but I am getting a 'DISTINCT requires ORDER BY to be used' error. I have an ORDER BY in it so I am not sure what I have missed?

SELECT DISTINCT tbl_final_CP.ExtEnum + tbl_final_CP.ExtEnum AS [Full Cost]
FROM tbl_final_CP INNER JOIN
ContractorAreaRelationship ON tbl_final_CP.Area = ContractorAreaRelationship.AreaNo INNER JOIN
tbl_CPCost ON tbl_final_CP.CP = tbl_CPCost.CP
WHERE (DATEPART(yyyy, tbl_final_CP.dCount) = DATEPART(yyyy, GETDATE())) AND (ContractorAreaRelationship.ContractorNumber = 6112) AND
(DATENAME(mm, tbl_final_CP.dCount) = 'Conwy') AND (ContractorAreaRelationship.AreaName = 'Conwy') AND (tbl_final_CP.Video > 0) OR
(DATEPART(yyyy, tbl_final_CP.dCount) = DATEPART(yyyy, GETDATE())) AND (ContractorAreaRelationship.ContractorNumber = 6112) AND
(DATENAME(mm, tbl_final_CP.dCount) = 'March') AND (ContractorAreaRelationship.AreaName = 'Conwy') AND (tbl_final_CP.ExtEnum > 0) OR
(DATEPART(yyyy, tbl_final_CP.dCount) = DATEPART(yyyy, GETDATE())) AND (DATENAME(mm, tbl_final_CP.dCount) = 'March') AND
(ContractorAreaRelationship.AreaName = 'Conwy') AND (tbl_final_CP.Video > 0) AND (ContractorAreaRelationship.AdminID = 6112) OR
(DATEPART(yyyy, tbl_final_CP.dCount) = DATEPART(yyyy, GETDATE())) AND (DATENAME(mm, tbl_final_CP.dCount) = 'March') AND
(ContractorAreaRelationship.AreaName = 'Conwy') AND (tbl_final_CP.ExtEnum > 0) AND (ContractorAreaRelationship.AdminID = 6112)
ORDER BY tbl_final_CP.CP, tbl_final_CP.ExtEnum + tbl_final_CP.ExtEnum

View Replies !
Distinct & Dynamic ORDER BY
Hello,

I have a stored procedure with dynamic ORDER BY. I would like to use the DISTINCT too. Is it somehow possible?
Thank you

Here is the stored procedure:

SELECT identifier_company + cast(identifier_number as nvarchar(3)) as identifier,
CASE WHEN canceled = 'True' THEN 'canceledPO' ELSE '' END AS style,
staff.staff_name,
purchase.purchase_id,
purchase.traveller_name,
nominal_department.department_name,
purchase.canceled,
purchase.travel_date,
convert(nvarchar(20), purchase.date_raised, 103) as dated,
supplier
FROM purchase INNER JOIN purchase_project ON purchase.purchase_id = purchase_project.purchase_id
INNER JOIN staff ON purchase.raised = staff.staff_id
INNER JOIN nominal_department ON purchase.department = nominal_department.nominal_dep_id
WHERE (raised in (SELECT staff_id FROM staff WHERE department like @FromDepartment) or purchase.raised = @raisedBy)
and purchase_project.project_number like '%' + @Query + '%'
ORDER BY
CASE @SortDir
WHEN 'ASC' THEN
CASE @OrderBy
WHEN 'staff_name' THEN cast(staff_name as nvarchar(100))
WHEN 'traveller_name' THEN cast(traveller_name as nvarchar(100))
WHEN 'department_name' THEN cast(department_name as nvarchar(100))
WHEN 'supplier' THEN cast(supplier as nvarchar(100))
WHEN 'canceled' THEN cast(canceled as nvarchar(10))
END
END
ASC,
CASE @SortDir
WHEN 'DESC' THEN
CASE @OrderBy
WHEN 'staff_name' THEN cast(staff_name as nvarchar(100))
WHEN 'traveller_name' THEN cast(traveller_name as nvarchar(100))
WHEN 'department_name' THEN cast(department_name as nvarchar(100))
WHEN 'supplier' THEN cast(supplier as nvarchar(100))
WHEN 'canceled' THEN cast(canceled as nvarchar(10))
END
END
DESC

View Replies !
Scan Order Of User Defined Aggregates
Hi all!

I have created (in CLR) a user defined aggregate. The scan order of this aggregate is important, because it return different results for different orders.

When i use it with a single group (using order by and where) is working fine.

For example

select id, dbo.cmp(myclolumn) as myres from (select top 100 percent * from mytable order by id,clmdate) where id=10 group by id

This works correctly. Now lets expand it by removing where id=10 clause

select id, dbo.cmp(myclolumn) as myres from (select top 100 percent * from mytable order by id,clmdate) group by id

I get slightly different results from what the right result must be.

Any idea?

View Replies !
Default Sort Order - Open Table - Select Without Order By
Hi!
 
I recently run into a senario when a procedure quiered a table without a order by clause. Luckily it retrived data in the prefered order.
 
The table returns the data in the same order in SQL Manager "Open Table"
 
So I started to wonder what deterimins the sort order when there is no order by clause ?
 
I researched this for a bit but found no straight answers. My table has no PK, but an identiy column.
 
Peace.
 
/P

View Replies !
Trying To Add A NON-DISTINCT Field To A DISTINCT Record Set In A Query.
I need to run a SELECT DISTINCT query acrossmultiple fields, but I need to add another field that is NON-DISTINCTto my record set.Here is my query:SELECT DISTINCT lastname, firstname, middleinitial, address1,address2, city, state, zip, age, genderFROM gpresultsWHERE age>='18' and serviceline not in ('4TH','4E','4W')and financialclass not in ('Z','X') and age not in('1','2','3','4','5','6','7','8','9','0')and (CAST (ADMITDATE AS DATETIME) >= DATEDIFF(day, 60, GETDATE()))ORDER BY zipThis query runs perfect. No problems whatsoever. However, I need toalso include another field called "admitdate" that should be treatedas NON-DISTINCT. How do I add this in to the query?I've tried this but doesn't work:SELECT admitdateFROM (SELECT DISTINCT lastname, firstname, middleinitial, address1,address2, city, state, zip, age, gender from gpresults)WHERE age>='18' and serviceline not in ('4TH','4E','4W')and financialclass not in ('Z','X') and age not in('1','2','3','4','5','6','7','8','9','0')and (CAST (ADMITDATE AS DATETIME) >= DATEDIFF(day, 60, GETDATE()))ORDER BY zipThis has to be simple but I do not know the syntax to accomplishthis.Thanks

View Replies !
Extract Distinct Information And Order The Results
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 Replies !
Is It Possible To Re-reference A Column Alias From A Select Clause In Another Column Of The Same Select Clause?
Example, suppose you have these 2 tables(NOTE: My example is totally different, but I'm simply trying to setupthe a simpler version, so excuse the bad design; not the point here)CarsSold {CarsSoldID int (primary key)MonthID intDealershipID intNumberCarsSold int}Dealership {DealershipID int, (primary key)SalesTax decimal}so you may have many delearships selling cars the same month, and youwanted a report to sum up totals of all dealerships per month.select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',sum(cs.NumberCarsSold) * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDMy question is, is there a way to achieve something like this:select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',TotalCarsSoldInMonth * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDNotice the only difference is the 3rd column in the select. Myparticular query is performing some crazy math and the only way I knowof how to get it to work is to copy and past the logic which isgetting out way out of hand...Thanks,Dave

View Replies !
Order By Clause
If I use the order by clause to sort on a date, where the date andtime stamp are the exact same for multiple records, how does SQLoutput the data?At random... or does it look at the primary key?

View Replies !
Order By Clause
Hello,
can any one tell me about the difference between the following queries.



1. SELECT * FROM Symp_User ORDER BY
2. SELECT * FROM Symp_User ORDER BY ASC


I don't think there is any difference in the above queries. kinldy make me clear on this.


thnkx,
rahul jha

View Replies !
Order By Clause
Hi there,
i'm trying to order the follow query:


SELECT count(nome) as CNT FROM utenti WHERE nome like '%" & rs("nome") & "%' ORDER BY CNT ASC

why i've this error:

Microsoft OLE DB Provider for ODBC Drivers errore "80040e10"
[Microsoft][Driver ODBC Microsoft Access] Parametri insufficienti. Previsto 1.

Thank you in advance...

View Replies !
Order By Clause
I am looking to get a cyclic order in the order by clause. how do I do this?

for example I have 5 customers with ids like
xyz 1
xyz 2
xyz 3
xyz 4
xyz 5

when I am selecting xyz 3 I want the list to show
xyz 4
xyz 5
xyz 1
xyz 2
xyz 3

How do I do this by using the order by clause?

View Replies !
Order By In() Clause ??
Hi!

My problem is this one:

I'm doing a simple query like this (simplified):

SELECT Me_id, Det_id, Det_val
FROM oFormsMsgDet
WHERE (Det_id IN (2411, 2409, 2410, 2408))

And I want the recordset order by my IN list. My In list is given dynamicly so I can't play with it and my query is returned in Det_id order. How can I do it?

Thanks a lot

Genviou

View Replies !
Reg. Order By Clause
Can you explain the below scenario

The ORDER BY clause can include items that do not appear in the select list. However, if SELECT DISTINCT is specified, or if the statement contains a GROUP BY clause, or if the SELECT statement contains a UNION operator, the sort columns must appear in the select list.

what is the reason behind this.

View Replies !
&&"distinct&&" In Select Query
when i use select :

select flattened

(select productid, $support from [model name].[table] )......

i have result with many record same.

so i write :

select flattened

(select distinct productid, $support from [model name].[table] )......

but when i run, it's error. ( don't know what error).

how can i do to get table record with not same record (loop)

note : it write in DTS and i use sql 2000

View Replies !
Order By Clause Problem
Hello,Ive got a column which stores integers ranging from 0-200. I need to order them so that 1 is first, and 0 is last like 1,2,2,3,4,6,8....98....0,0,0My Order By clause statement looks like 'ORDER BY column_name', but obviously this will put the '0' records at the top. Is there a way around this?Thanks, Curt. 

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved