Showing posts with label error. Show all posts
Showing posts with label error. Show all posts

Friday, March 30, 2012

ORDER BY with alias

Hi NG,
in my following query I get the error "Invalid column name 'price'" but
everything seems ok:
SELECT row_number() over (order by price) as row_num,
dbo.getProductPrice('1234') as price
MS describes the use of aliases in ORDER BY
http://msdn2.microsoft.com/ms188385.aspx
Any ideas?
Thanks
Andre ScheiberleAndre Scheiberle wrote:
> Hi NG,
> in my following query I get the error "Invalid column name 'price'" but
> everything seems ok:
> SELECT row_number() over (order by price) as row_num,
> dbo.getProductPrice('1234') as price
> MS describes the use of aliases in ORDER BY
> http://msdn2.microsoft.com/ms188385.aspx
> Any ideas?
> Thanks
> Andre Scheiberle
ORDER BY in a query is different to ORDER BY in a ranking function. In
the latter case you can only reference base columns, not aliases. Try
the following (I assume you omitted the FROM clause in error).
SELECT ROW_NUMBER() OVER (ORDER BY price) AS row_num, price
FROM
(SELECT dbo.getProductPrice('1234')
FROM tbl) AS T(price) ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||does dbo.getProductPrice('1234')
return a table or a scalar value?
--
"Andre Scheiberle" wrote:

> Hi NG,
> in my following query I get the error "Invalid column name 'price'" but
> everything seems ok:
> SELECT row_number() over (order by price) as row_num,
> dbo.getProductPrice('1234') as price
> MS describes the use of aliases in ORDER BY
> http://msdn2.microsoft.com/ms188385.aspx
> Any ideas?
> Thanks
> Andre Scheiberle
>|||ok, in this example it works, but in my Application I use this Query:
SELECT ROW_NUMBER() OVER (ORDER BY price) AS row_num, price, article
FROM
products,
(SELECT dbo.getProductPrice(products.article)M tbl) AS T(price) ;
Now an error appears "The multi-part identifier "products.article" could not
be bound."
Thanks
Andre
"David Portas" wrote:

> Andre Scheiberle wrote:
> ORDER BY in a query is different to ORDER BY in a ranking function. In
> the latter case you can only reference base columns, not aliases. Try
> the following (I assume you omitted the FROM clause in error).
> SELECT ROW_NUMBER() OVER (ORDER BY price) AS row_num, price
> FROM
> (SELECT dbo.getProductPrice('1234')
> FROM tbl) AS T(price) ;
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||The table return a scalar value
"Omnibuzz" wrote:
> does dbo.getProductPrice('1234')
> return a table or a scalar value?
> --
>
>
> "Andre Scheiberle" wrote:
>|||try this then.
SELECT ROW_NUMBER() OVER (ORDER BY price) AS row_num, price, article
from
(SELECT dbo.getProductPrice(article), article
FROM
products) AS T(price, article)
"Omnibuzz" wrote:
> does dbo.getProductPrice('1234')
> return a table or a scalar value?
> --
>
>
> "Andre Scheiberle" wrote:
>|||Andre Scheiberle wrote:
> ok, in this example it works, but in my Application I use this Query:
> SELECT ROW_NUMBER() OVER (ORDER BY price) AS row_num, price, article
> FROM
> products,
> (SELECT dbo.getProductPrice(products.article)M tbl) AS T(price) ;
> Now an error appears "The multi-part identifier "products.article" could n
ot
> be bound."
> Thanks
> Andre
>
You can't reference a table from the outer query in a derived table
subquery. Try this (assuming your function is scalar):
SELECT ROW_NUMBER() OVER (ORDER BY price) AS row_num,
price, article
FROM
(SELECT dbo.getProductPrice(article), article
FROM products) AS T(price,article) ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Here is how a SELECT works in SQL ... at least in theory. Real
products will optimize things, but the code has to produce the same
results.
a) Start in the FROM clause and build a working table from all of the
joins, unions, intersections, and whatever other table constructors are
there. The <table expression> AS <correlation name> option allows you
give a name to this working table which you then have to use for the
rest of the containing query.
b) Go to the WHERE clause and remove rows that do not pass criteria;
that is, that do not test to TRUE (i.e. reject UNKNOWN and FALSE). The
WHERE clause is applied to the working set in the FROM clause.
c) Go to the optional GROUP BY clause, make groups and reduce each
group to a single row, replacing the original working table with the
new grouped table. The rows of a grouped table must be group
characteristics: (1) a grouping column (2) a statistic about the group
(i.e. aggregate functions) (3) a function or (4) an expression made up
those three items. The original table no longer exists.
d) Go to the optional HAVING clause and apply it against the grouped
working table; if there was no GROUP BY clause, treat the entire table
as one group.
e) Go to the SELECT clause and construct the expressions in the list.
This means that the scalar subqueries, function calls and expressions
in the SELECT are done after all the other clauses are done. The AS
operator can also give names to expressions in the SELECT list. These
new names come into existence all at once, but after the WHERE clause,
GROUP BY clause and HAVING clause have been executed; you cannot use
them in the SELECT list or the WHERE clause for that reason.
If there is a SELECT DISTINCT, then redundant duplicate rows are
removed. For purposes of defining a duplicate row, NULLs are treated
as matching (just like in the GROUP BY).
f) Nested query expressions follow the usual scoping rules you would
expect from a block structured language like C, Pascal, Algol, etc.
Namely, the innermost queries can reference columns and tables in the
queries in which they are contained.
g) The ORDER BY clause is part of a cursor, not a query. The result
set is passed to the cursor, which can only see the names in the SELECT
clause list, and the sorting is done there. The ORDER BY clause cannot
have expression in it, or references to other columns because the
result set has been converted into a sequential file structure and that
is what is being sorted.
As you can see, things happen "all at once" in SQL, not "from left to
right" as they would in a sequential file/procedural language model. In
those languages, these two statements produce different results:
READ (a, b, c) FROM File_X;
READ (c, a, b) FROM File_X;
while these two statements return the same data:
SELECT a, b, c FROM Table_X;
SELECT c, a, b FROM Table_X;
Think about what a mess this statement is in the SQL model.
SELECT f(c2) AS c1, f(c1) AS c2 FROM Foobar;
That is why such nonsense is illegal syntax.

Order By Update Error

Hi Every1,
I'm getting the following error
Server: Msg 1033, Level 15, State 1, Line 13
The ORDER BY clause is invalid in views, inline functions, derived
tables, and subqueries, unless TOP is also specified.
what I'm trying to do is to update a table based on the select criteria
I have. In that I'm using ORDER BY Clause & this is giving me error.
Here is my sql:
SELECT SUBSTRING(A.DESCR,1,10), B.SUPPORT_TEAM_MBR, EMPLID, COUNT(*)
from PS_TEAM_CODE_TBL A, PS_TEAM_MEMBERS B, PS_MEMBER_PERSON C
WHERE A.SUPPORT_TEAM_CD = B.SUPPORT_TEAM_CD
AND A.EFF_STATUS = 'A'
AND A.EFFDT >= (SELECT MAX(AX.EFFDT) FROM PS_TEAM_CODE_TBL AX
WHERE A.SETID = AX.SETID
AND A.SUPPORT_TEAM_CD = AX.SUPPORT_TEAM_CD)
AND B.SUPPORT_TEAM_MBR = C.SUPPORT_TEAM_MBR
GROUP BY SUBSTRING(A.DESCR,1,10), B.SUPPORT_TEAM_MBR, EMPLID
HAVING COUNT(*) > 1
ORDER BY SUBSTRING(A.DESCR,1,10)
Is it possible to fix this error?
Thanks in advance for your help.Tony,
The query you posted is not an UPDATE statement, View or Function.
I don't see any problems with the query you posted. However, it is not
valid as a view definition, because of the ORDER BY clause, missing
column names for the resultset and maybe more.
In what way to you think that the order is important when updating a
table? What is the actual UPDATE statement you are trying to use?
Gert-Jan
Tony Schplik wrote:
> Hi Every1,
> I'm getting the following error
> Server: Msg 1033, Level 15, State 1, Line 13
> The ORDER BY clause is invalid in views, inline functions, derived
> tables, and subqueries, unless TOP is also specified.
> what I'm trying to do is to update a table based on the select criteria
> I have. In that I'm using ORDER BY Clause & this is giving me error.
> Here is my sql:
> SELECT SUBSTRING(A.DESCR,1,10), B.SUPPORT_TEAM_MBR, EMPLID, COUNT(*)
> from PS_TEAM_CODE_TBL A, PS_TEAM_MEMBERS B, PS_MEMBER_PERSON C
> WHERE A.SUPPORT_TEAM_CD = B.SUPPORT_TEAM_CD
> AND A.EFF_STATUS = 'A'
> AND A.EFFDT >= (SELECT MAX(AX.EFFDT) FROM PS_TEAM_CODE_TBL AX
> WHERE A.SETID = AX.SETID
> AND A.SUPPORT_TEAM_CD = AX.SUPPORT_TEAM_CD)
> AND B.SUPPORT_TEAM_MBR = C.SUPPORT_TEAM_MBR
> GROUP BY SUBSTRING(A.DESCR,1,10), B.SUPPORT_TEAM_MBR, EMPLID
> HAVING COUNT(*) > 1
> ORDER BY SUBSTRING(A.DESCR,1,10)
> Is it possible to fix this error?
> Thanks in advance for your help.|||Gert-Jan,
Thanks for your response. Sorry I forgot to put the update statement.
Here it is
UPDATE Name1
SET NAME1 = 'Z' FROM PS_MEMBER_PERSON WHERE NAME1 =(SELECT SUBSTRING(A.DESCR,1,10), B.SUPPORT_TEAM_MBR, EMPLID, COUNT(*)
from PS_TEAM_CODE_TBL A, PS_TEAM_MEMBERS B, PS_MEMBER_PERSON C
WHERE A.SUPPORT_TEAM_CD = B.SUPPORT_TEAM_CD
AND A.EFF_STATUS = 'A'
AND A.EFFDT >= (SELECT MAX(AX.EFFDT) FROM PS_TEAM_CODE_TBL AX
WHERE A.SETID = AX.SETID
AND A.SUPPORT_TEAM_CD = AX.SUPPORT_TEAM_CD)
AND B.SUPPORT_TEAM_MBR = C.SUPPORT_TEAM_MBR
GROUP BY SUBSTRING(A.DESCR,1,10), B.SUPPORT_TEAM_MBR, EMPLID
HAVING COUNT(*) > 1
ORDER BY SUBSTRING(A.DESCR,1,10)
Even if I take out the order by clause in the update, then it will give
me a different error for the subquery
Do you have any suggestions for that ...
Thanks in advance for your help|||Tony,
Have you looked into the syntax of the UPDATE statement in SQL Server Books
Online?
--
Anithsql

Monday, March 26, 2012

ORDER BY error, need help!

When I run this query, I get an ORDER BY error "Incorrect syntax near the keyword 'ORDER'. I've bolded it below.

If I take the ORDER by out then it works correctly, but I need the ORDER BY because of the TOP 9. Any Suggestions?
Code: ( sql )

    (SELECT TOP 9 trans.vchTrustee, trans.vchCaseNumber, Trans.TotalReceipts + SUM(a.mnyBalanceAmount) AS Top9Total FROM tblCase c1 LEFT JOIN tblAsset a ON c1.intCaseID = a.intCaseID LEFT JOIN (SELECT trans40.vchTrustee, trans40.vchCaseNumber, SUM(trans40.TdMnyAmount) AS TotalReceipts FROM (SELECT c.vchTrustee, c.vchCaseNumber, SUM(td.mnyAmount) AS TdMnyAmount FROM tblTransactionDetail td INNER JOIN tblTransaction t ON td.intTransactionID = t.intTransactionID INNER JOIN tblBankAccount b ON t.intAccountID = b.intAccountID INNER JOIN tblCase c ON b.intCaseID = c.intCaseID GROUP BY c.intDeleted, b.intDeleted, td.intDeleted, t.intDeleted, c.vchTrustee, c.vchCaseNumber, c.intCaseID, td.intTransactionType, t.intTransactionMethod, c.intStatus HAVING t.intDeleted = 0 AND td.intDeleted = 0 AND b.intDeleted = 0 AND c.intDeleted = 0 AND td.intTransactionType = 200 AND (t.intTransactionMethod = 40 OR t.intTransactionMethod = 41 OR t.intTransactionMethod = 43) AND c.vchTrustee = 'RLW' AND c.intStatus = 1 ) AS Trans40 GROUP BY Trans40.vchTrustee, Trans40.vchCaseNumber ) AS Trans ON c1.vchCaseNumber = Trans.vchCaseNumber GROUP BY trans.vchTrustee, trans.vchCaseNumber, a.intDeleted, c1.intDeleted, trans.TotalReceipts, c1.intStatus HAVING a.intDeleted = 0 AND c1.intDeleted = 0 AND trans.vchTrustee = 'RLW' AND c1.intStatus = 1 [B]ORDER BY (Trans.TotalReceipts + SUM(a.mnyBalanceAmount)) DESC[/B]) UNION ALL (SELECT Top9.vchTrustee, ' ', (AllCases.TR - SUM(Top9.Top9Total)) AS TRMinusTop9 FROM (SELECT AllTotalReceipts.vchTrustee, SUM(AllTotalReceipts.TotalMoney) AS TR FROM (SELECT trans.vchTrustee, trans.vchCaseNumber, Trans.TotalReceipts, SUM(a.mnyBalanceAmount) AS totalAssetBalance, (Trans.TotalReceipts + SUM(a.mnyBalanceAmount)) AS TotalMoney FROM tblCase c1 LEFT JOIN tblAsset a ON c1.intCaseID = a.intCaseID LEFT JOIN (SELECT trans40.vchTrustee, trans40.vchCaseNumber, SUM(trans40.TdMnyAmount) AS TotalReceipts FROM (SELECT c.vchTrustee, c.vchCaseNumber, SUM(td.mnyAmount) AS TdMnyAmount FROM tblTransactionDetail td INNER JOIN tblTransaction t ON td.intTransactionID = t.intTransactionID INNER JOIN tblBankAccount b ON t.intAccountID = b.intAccountID INNER JOIN tblCase c ON b.intCaseID = c.intCaseID GROUP BY c.intDeleted, b.intDeleted, td.intDeleted, t.intDeleted, c.vchTrustee, c.vchCaseNumber, c.intCaseID, td.intTransactionType, t.intTransactionMethod, c.intStatus HAVING t.intDeleted = 0 AND td.intDeleted = 0 AND b.intDeleted = 0 AND c.intDeleted = 0 AND td.intTransactionType = 200 AND (t.intTransactionMethod = 40 OR t.intTransactionMethod = 41 OR t.intTransactionMethod = 43) AND c.vchTrustee = 'RLW' AND c.intStatus = 1 ) AS Trans40 GROUP BY Trans40.vchTrustee, Trans40.vchCaseNumber ) AS Trans ON c1.vchCaseNumber = Trans.vchCaseNumber GROUP BY trans.vchTrustee, trans.vchCaseNumber, a.intDeleted, c1.intDeleted, trans.TotalReceipts, c1.intStatus HAVING a.intDeleted = 0 AND c1.intDeleted = 0 AND trans.vchTrustee = 'RLW' AND c1.intStatus = 1 ) AS AllTotalReceipts GROUP BY AllTotalReceipts.vchTrustee) AS AllCases LEFT JOIN (SELECT TOP 9 trans.vchTrustee, trans.vchCaseNumber, Trans.TotalReceipts, SUM(a.mnyBalanceAmount) AS totalAssetBalance, Trans.TotalReceipts + SUM(a.mnyBalanceAmount) AS Top9Total FROM tblCase c1 LEFT JOIN tblAsset a ON c1.intCaseID = a.intCaseID LEFT JOIN (SELECT trans40.vchTrustee, trans40.vchCaseNumber, SUM(trans40.TdMnyAmount) AS TotalReceipts FROM (SELECT c.vchTrustee, c.vchCaseNumber, SUM(td.mnyAmount) AS TdMnyAmount FROM tblTransactionDetail td INNER JOIN tblTransaction t ON td.intTransactionID = t.intTransactionID INNER JOIN tblBankAccount b ON t.intAccountID = b.intAccountID INNER JOIN tblCase c ON b.intCaseID = c.intCaseID GROUP BY c.intDeleted, b.intDeleted, td.intDeleted, t.intDeleted, c.vchTrustee, c.vchCaseNumber, c.intCaseID, td.intTransactionType, t.intTransactionMethod, c.intStatus HAVING t.intDeleted = 0 AND td.intDeleted = 0 AND b.intDeleted = 0 AND c.intDeleted = 0 AND td.intTransactionType = 200 AND (t.intTransactionMethod = 40 OR t.intTransactionMethod = 41 OR t.intTransactionMethod = 43) AND c.vchTrustee = 'RLW' AND c.intStatus = 1 ) AS Trans40 GROUP BY Trans40.vchTrustee, Trans40.vchCaseNumber ) AS Trans ON c1.vchCaseNumber = Trans.vchCaseNumber GROUP BY trans.vchTrustee, trans.vchCaseNumber, a.intDeleted, c1.intDeleted, trans.TotalReceipts, c1.intStatus HAVING a.intDeleted = 0 AND c1.intDeleted = 0 AND trans.vchTrustee = 'RLW' AND c1.intStatus = 1 ORDER BY Trans.TotalReceipts + SUM(a.mnyBalanceAmount) DESC ) AS Top9 ON AllCases.vchTrustee = Top9.vchTrustee GROUP BY Top9.vchTrustee, AllCases.TR )

Quote:

Originally Posted by speavey

When I run this query, I get an ORDER BY error "Incorrect syntax near the keyword 'ORDER'. I've bolded it below.

If I take the ORDER by out then it works correctly, but I need the ORDER BY because of the TOP 9. Any Suggestions?

(SELECT TOP 9 trans.vchTrustee, trans.vchCaseNumber, Trans.TotalReceipts + SUM(a.mnyBalanceAmount) As Top9Total

FROM tblCase c1

LEFT JOIN tblAsset a ON c1.intCaseID = a.intCaseID
LEFT JOIN
(Select trans40.vchTrustee, trans40.vchCaseNumber, SUM(trans40.TdMnyAmount) As TotalReceipts

From
(SELECT c.vchTrustee, c.vchCaseNumber, SUM(td.mnyAmount) As TdMnyAmount
FROM tblTransactionDetail td

INNER JOIN tblTransaction t ON td.intTransactionID = t.intTransactionID
INNER JOIN tblBankAccount b ON t.intAccountID = b.intAccountID
INNER JOIN tblCase c ON b.intCaseID = c.intCaseID

GROUP BY c.intDeleted, b.intDeleted, td.intDeleted, t.intDeleted,
c.vchTrustee, c.vchCaseNumber, c.intCaseID, td.intTransactionType,
t.intTransactionMethod, c.intStatus

HAVING t.intDeleted = 0 AND td.intDeleted = 0 AND b.intDeleted = 0 AND c.intDeleted = 0
AND td.intTransactionType = 200
AND (t.intTransactionMethod = 40 OR t.intTransactionMethod = 41 OR t.intTransactionMethod = 43)
AND c.vchTrustee = 'RLW' AND c.intStatus = 1

) As Trans40

GROUP BY Trans40.vchTrustee, Trans40.vchCaseNumber
) As Trans ON c1.vchCaseNumber = Trans.vchCaseNumber

GROUP BY trans.vchTrustee, trans.vchCaseNumber, a.intDeleted, c1.intDeleted, trans.TotalReceipts, c1.intStatus

HAVING a.intDeleted = 0 AND c1.intDeleted = 0 AND trans.vchTrustee = 'RLW' AND c1.intStatus = 1

ORDER BY (Trans.TotalReceipts + SUM(a.mnyBalanceAmount)) DESC)

UNION All

(SELECT Top9.vchTrustee, ' ', (AllCases.TR - SUM(Top9.Top9Total)) As TRMinusTop9
FROM

(SELECT AllTotalReceipts.vchTrustee, SUM(AllTotalReceipts.TotalMoney) As TR
FROM

(SELECT trans.vchTrustee, trans.vchCaseNumber, Trans.TotalReceipts, SUM(a.mnyBalanceAmount) As totalAssetBalance,
(Trans.TotalReceipts + SUM(a.mnyBalanceAmount)) As TotalMoney

FROM tblCase c1

LEFT JOIN tblAsset a ON c1.intCaseID = a.intCaseID
LEFT JOIN
(Select trans40.vchTrustee, trans40.vchCaseNumber, SUM(trans40.TdMnyAmount) As TotalReceipts

From
(SELECT c.vchTrustee, c.vchCaseNumber, SUM(td.mnyAmount) As TdMnyAmount
FROM tblTransactionDetail td
INNER JOIN tblTransaction t ON td.intTransactionID = t.intTransactionID
INNER JOIN tblBankAccount b ON t.intAccountID = b.intAccountID
INNER JOIN tblCase c ON b.intCaseID = c.intCaseID

GROUP BY c.intDeleted, b.intDeleted, td.intDeleted, t.intDeleted,
c.vchTrustee, c.vchCaseNumber, c.intCaseID, td.intTransactionType,
t.intTransactionMethod, c.intStatus

HAVING t.intDeleted = 0 AND td.intDeleted = 0 AND b.intDeleted = 0 AND c.intDeleted = 0
AND td.intTransactionType = 200
AND (t.intTransactionMethod = 40 OR t.intTransactionMethod = 41 OR t.intTransactionMethod = 43)
AND c.vchTrustee = 'RLW' AND c.intStatus = 1

) As Trans40

GROUP BY Trans40.vchTrustee, Trans40.vchCaseNumber
) As Trans ON c1.vchCaseNumber = Trans.vchCaseNumber

GROUP BY trans.vchTrustee, trans.vchCaseNumber, a.intDeleted, c1.intDeleted, trans.TotalReceipts, c1.intStatus
HAVING a.intDeleted = 0 AND c1.intDeleted = 0 AND trans.vchTrustee = 'RLW' AND c1.intStatus = 1
) As AllTotalReceipts

GROUP BY AllTotalReceipts.vchTrustee) As AllCases

LEFT JOIN

(SELECT TOP 9 trans.vchTrustee, trans.vchCaseNumber, Trans.TotalReceipts, SUM(a.mnyBalanceAmount) As totalAssetBalance,
Trans.TotalReceipts + SUM(a.mnyBalanceAmount) As Top9Total

FROM tblCase c1

LEFT JOIN tblAsset a ON c1.intCaseID = a.intCaseID
LEFT JOIN
(Select trans40.vchTrustee, trans40.vchCaseNumber, SUM(trans40.TdMnyAmount) As TotalReceipts

From
(SELECT c.vchTrustee, c.vchCaseNumber, SUM(td.mnyAmount) As TdMnyAmount
FROM tblTransactionDetail td

INNER JOIN tblTransaction t ON td.intTransactionID = t.intTransactionID
INNER JOIN tblBankAccount b ON t.intAccountID = b.intAccountID
INNER JOIN tblCase c ON b.intCaseID = c.intCaseID

GROUP BY c.intDeleted, b.intDeleted, td.intDeleted, t.intDeleted,
c.vchTrustee, c.vchCaseNumber, c.intCaseID, td.intTransactionType,
t.intTransactionMethod, c.intStatus

HAVING t.intDeleted = 0 AND td.intDeleted = 0 AND b.intDeleted = 0 AND c.intDeleted = 0
AND td.intTransactionType = 200 AND (t.intTransactionMethod = 40 OR t.intTransactionMethod = 41 OR t.intTransactionMethod = 43)
AND c.vchTrustee = 'RLW' AND c.intStatus = 1

) As Trans40

GROUP BY Trans40.vchTrustee, Trans40.vchCaseNumber
) As Trans ON c1.vchCaseNumber = Trans.vchCaseNumber

GROUP BY trans.vchTrustee, trans.vchCaseNumber, a.intDeleted, c1.intDeleted, trans.TotalReceipts, c1.intStatus

HAVING a.intDeleted = 0 AND c1.intDeleted = 0 AND trans.vchTrustee = 'RLW' AND c1.intStatus = 1
ORDER BY Trans.TotalReceipts + SUM(a.mnyBalanceAmount) DESC
) As Top9

ON AllCases.vchTrustee = Top9.vchTrustee
GROUP By Top9.vchTrustee, AllCases.TR

)


i believe ORDER BY has to be placed on the outermost QUERY, resulting in a sorted final returned resultset|||

Quote:

Originally Posted by ck9663

i believe ORDER BY has to be placed on the outermost QUERY, resulting in a sorted final returned resultset


I tried that and it won't produce the correct order by, because the First query with the TOP 9 isn't being sorted.

So if I put it on the outermost query, it doesn't sort correctly.

Maybe you can help me with my query, its very long and probably too much code. I'm trying to create a query the will SUM a value from two tables and pull the TOP 9 cases. Then also add a TOTAL SUM value - Top 9 Sum Value.

Any help would be great!!

ORDER BY error

Hello,

in a complex stored procedure, i get an error when i want to apply an ORDER BY statement :

Here is a part of this Stored Procedure :

SELECT TaOperations.Id_Operation, TaOperations.HeureDebut, TaOperations.Signe, TaOperations.Facturer, TaOperations.IdUserVerrou,

TaOperations.Id_Client, TaTypeOperation.Facturable, CONVERT(CHAR(10), TaOperations.HeureDebut,

103) + ' - ' + TaTypeOperation.TypeOperation AS Code

FROM TaOperations INNER JOIN

TaTypeOperation ON TaOperations.Id_TypeOperation = TaTypeOperation.Id_TypeOperation

WHERE (TaOperations.Id_Client = CONVERT(int, @.Id_Client)) AND (TaTypeOperation.Facturable = 1) AND (TaOperations.IdUserVerrou IS NULL)

If I want to apply an ORDER BY statement, i have

SELECT TaOperations.Id_Operation, TaOperations.HeureDebut, TaOperations.Signe, TaOperations.Facturer, TaOperations.IdUserVerrou,

TaOperations.Id_Client, TaTypeOperation.Facturable, CONVERT(CHAR(10), TaOperations.HeureDebut, 103)

+ ' - ' + TaTypeOperation.TypeOperation AS Code

FROM TaOperations INNER JOIN

TaTypeOperation ON TaOperations.Id_TypeOperation = TaTypeOperation.Id_TypeOperation

WHERE (TaOperations.Id_Client = CONVERT(int, @.Id_Client)) AND (TaTypeOperation.Facturable = 1) AND (TaOperations.IdUserVerrou IS NULL)

ORDER BY TaOperations.HeureDebut

I get this error :

Msg 156, Level 15, State 1, Procedure SIE_ListeOperationsFacturablesParClient, Line 46

Incorrect syntax near the keyword 'ORDER'.

Does anyone cab help me ?

Is there anything else after the SELECT statement?

WesleyB

Visit my SQL Server weblog @. http://dis4ea.blogspot.com

|||

Here is the whole code :

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go

ALTER PROCEDURE [dbo].[SIE_ListeOperationsFacturablesParClient]

@.Id_Client char(5),

@.Cas int

AS

BEGIN

SET NOCOUNT ON;

If @.cas = 0 (

SELECT TaOperations.Id_Operation, TaOperations.HeureDebut, TaOperations.Signe, TaOperations.Facturer, TaOperations.IdUserVerrou,

TaOperations.Id_Client, TaTypeOperation.Facturable, CONVERT(CHAR(10), TaOperations.HeureDebut,

103) + ' - ' + TaTypeOperation.TypeOperation AS Code

FROM TaOperations INNER JOIN

TaTypeOperation ON TaOperations.Id_TypeOperation = TaTypeOperation.Id_TypeOperation

WHERE (TaOperations.Id_Client = CONVERT(int, @.Id_Client)) AND (TaTypeOperation.Facturable = 1) AND (TaOperations.Signe = 1) AND

(TaOperations.IdUserVerrou IS NOT NULL))

If @.cas = 1 (

SELECT TaOperations.Id_Operation, TaOperations.HeureDebut, TaOperations.Signe, TaOperations.Facturer, TaOperations.IdUserVerrou,

TaOperations.Id_Client, TaTypeOperation.Facturable, CONVERT(CHAR(10), TaOperations.HeureDebut,

103) + ' - ' + TaTypeOperation.TypeOperation AS Code

FROM TaOperations INNER JOIN

TaTypeOperation ON TaOperations.Id_TypeOperation = TaTypeOperation.Id_TypeOperation

WHERE (TaOperations.Id_Client = CONVERT(int, @.Id_Client)) AND (TaTypeOperation.Facturable = 1) AND (TaOperations.Signe = 0) AND

(TaOperations.IdUserVerrou IS NOT NULL))

If @.cas = 2 (

SELECT TaOperations.Id_Operation, TaOperations.HeureDebut, TaOperations.Signe, TaOperations.Facturer, TaOperations.IdUserVerrou,

TaOperations.Id_Client, TaTypeOperation.Facturable, CONVERT(CHAR(10), TaOperations.HeureDebut, 103)

+ ' - ' + TaTypeOperation.TypeOperation AS Code

FROM TaOperations INNER JOIN

TaTypeOperation ON TaOperations.Id_TypeOperation = TaTypeOperation.Id_TypeOperation

WHERE (TaOperations.Id_Client = CONVERT(int, @.Id_Client)) AND (TaTypeOperation.Facturable = 1) AND (TaOperations.IdUserVerrou IS NULL)

ORDER BY TaOperations.HeureDebut DESC

)

END

|||T-SQL normally uses the following syntax but you can leave out the BEGIN and END if you are only executing one query (or a single line of code).

IF @.var = x
BEGIN
YOUR CODE
END

Could you try leaving out the ( and ) for the if clauses?

If @.cas = 2

SELECT TaOperations.Id_Operation, TaOperations.HeureDebut, TaOperations.Signe, TaOperations.Facturer, TaOperations.IdUserVerrou,

TaOperations.Id_Client, TaTypeOperation.Facturable,CONVERT(CHAR(10), TaOperations.HeureDebut, 103)

+' - '+ TaTypeOperation.TypeOperation AS Code

FROM TaOperations INNERJOIN

TaTypeOperation ON TaOperations.Id_TypeOperation = TaTypeOperation.Id_TypeOperation

WHERE(TaOperations.Id_Client =CONVERT(int, @.Id_Client))AND(TaTypeOperation.Facturable = 1)AND(TaOperations.IdUserVerrou ISNULL)

ORDERBY TaOperations.HeureDebut DESC


WesleyB

Visit my SQL Server weblog @. http://dis4ea.blogspot.com

|||Wonderful !!! it works thanks a lotsql

order by does not work

insert table1
select distinct a,b,c
from table2
order by d,e,f
Microsoft SQL server gives error:
"Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is
specified."
Why? Is there any option I can set to turn this feature
off?
(I have solved it by using an intermediate table. Table1 has an
identity column and that's why it is important to get the data in
right order.)
On Apr 10, 12:05 pm, "David Portas"
<REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
> <bang...@.yahoo.com> wrote in message
> news:1176182612.603459.136470@.q75g2000hsh.googlegr oups.com...
>
>
> The output of a SELECT DISTINCT query may have fewer rows than the base
> table. So if you order by some column that isn't in the result how can SQL
> Server know which row in the base table should determine the correct order?
> For example you could try one of the following::
> SELECT a,b,c
> FROM table2
> GROUP BY a,b,c
> ORDER BY MIN(d), MIN(e), MIN(f);
> SELECT a,b,c
> FROM table2
> GROUP BY a,b,c
> ORDER BY MAX(d), MAX(e), MAX(f);
> Both those queries will return the same rows as DISTINCT but they may result
> in different orders depending on whether you use MIN or MAX.
So?

> A table has no order.
Ok, sounds something new to me.

>IDENTITY isn't guaranteed to match insertion order and
> in some circumstances the allocation order if the IDENTITY values may not
> match your ORDER BY clause, especially in SQL Server 2000.
Its better be GURANTEED every time I execute this query. Thanks.
In 2005, use the
> ROW_NUMBER() to generate such a sequence. ROW_NUMBER() has its own
> independent ORDER BY clause.
Sorry, that's not an option (because I am using server 2k).

> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
|||On Apr 10, 12:38 pm, bang...@.yahoo.com wrote:
> On Apr 10, 12:05 pm, "David Portas"
>
>
> <REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
>
>
>
>
> So?
>
> Ok, sounds something new to me.
>
> Its better be GURANTEED every time I execute this query. Thanks.
> In 2005, use the
>
> Sorry, that's not an option (because I am using server 2k).
>
>
>
> - Show quoted text -- Hide quoted text -
> - Show quoted text -
select distinct a,b
from t2
order by c
What I am trying to say is FIRST select all rows order by column c.
SECOND, based on that result set, select distinct rows for column a
and b. I think this should be fairly simple to do.
|||On 10 Apr, 07:38, bang...@.yahoo.com wrote:
> On Apr 10, 12:05 pm, "David Portas"
>
> Ok, sounds something new to me.
>
In that case I highly recommend that you read some introductory books
or take a course. Unordered tables are a pretty fundamental feature of
relational databases and SQL.

> What I am trying to say is FIRST select all rows order by column c.
> SECOND, based on that result set, select distinct rows for column a
> and b. I think this should be fairly simple to do.- Hide quoted text -
>
The best way to explain what you mean is to give an example using DDL
(CREATE TABLE statements) and some sample data (INSERT statements).
Here's a guess:
CREATE TABLE t2 (a INT NOT NULL, b INT NOT NULL, c INT NOT NULL,
PRIMARY KEY (a,b,c));
INSERT INTO t2 (a, b, c)
SELECT 1, 2, 1 UNION ALL
SELECT 1, 2, 4 UNION ALL
SELECT 1, 3, 2 UNION ALL
SELECT 1, 3, 1 ;
What result would you want based on this sample data? Notice that the
key of t2 may be an important factor but unfortunately you didn't
specify that information. If I'm wrong then please modify my CREATE
TABLE statement to match your actual case.
As you are using SQL Server 2000 the best solution may be to use a
subquery or a join to derive a deterministic "row number" for each
row. Here's an example using the Pubs database:
SELECT au_id,
(SELECT COUNT(*)
FROM authors
WHERE au_id <= a.au_id) AS row_number
FROM authors AS a ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
|||> > > A table has no order.
>
> In that case I highly recommend that you read some introductory books
> or take a course. Unordered tables are a pretty fundamental feature of
> relational databases and SQL.
Gee, that was a joke for starters.
My problem is very simple (at least that's the best I can do to
without getting into the details of the actual problem).
select distinct a,b,c
from table1
order by d,e,f
First I want the server to select the rows order by d,e and f
Second, select the distinct rows from that set maintaining the
original order (so internally I would expect that the server would get
the rows from the original set in that order!! ! I know I an not find
that out without getting into the id of each row).
This should be fairly simple data manipulation to do in my opinion.
|||On 10 Apr, 11:42, bang...@.yahoo.com wrote:
> My problem is very simple (at least that's the best I can do to
> without getting into the details of the actual problem).
> select distinct a,b,c
> from table1
> order by d,e,f
> First I want the server to select the rows order by d,e and f
> Second, select the distinct rows from that set maintaining the
> original order (so internally I would expect that the server would get
> the rows from the original set in that order!! ! I know I an not find
> that out without getting into the id of each row).
>
You didn't give the extra information I asked for so I can only repeat
the suggestion I made earlier. Try:
SELECT a, b, c
FROM table1
GROUP BY a, b, c
ORDER BY MIN(d), MIN(e), MIN(f);
Hope this helps.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
|||<bangla2@.yahoo.com> wrote in message
news:1176187133.447900.81300@.y66g2000hsf.googlegro ups.com...
> On Apr 10, 12:05 pm, "David Portas"
> <REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
>
> Ok, sounds something new to me.
As David points out, that's a fundamental definition of a table under SQL.
>
>
> Its better be GURANTEED every time I execute this query. Thanks.
Well I can't say it will be. However, there is another fundamental issue
that may arise.
Given your query, it's very possible I could be inserting 1000 rows into the
database where columns D, E fall into the range of your query. However, as
written, there would be no locking on that range, which means your select
could return some random subset of those rows.
Also, since you can only have one IDENTITY column per table (insert CELKO's
rant here), I'm not sure what you're getting at when trying to sort by 3
columns anyway.
You're much better off probably simply putting the columns into your select
and ignoring them at the other end.

>
> In 2005, use the
>
> Sorry, that's not an option (because I am using server 2k).
>
>
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html
|||> Ok, sounds something new to me.
> As David points out, that's a fundamental definition of a table under SQL.
>
>
> Well I can't say it will be. However, there is another fundamental issue
> that may arise.
> Given your query, it's very possible I could be inserting 1000 rows into the
> database where columns D, E fall into the range of your query. However, as
> written, there would be no locking on that range, which means your select
> could return some random subset of those rows.
> Also, since you can only have one IDENTITY column per table (insert CELKO's
> rant here), I'm not sure what you're getting at when trying to sort by 3
> columns anyway.
> You're much better off probably simply putting the columns into your select
> and ignoring them at the other end.
>
SQL is never meant to be a set based and all that. We EXPECT and
DEMAND from SQL Server to do many other things other than just simple
set based operations. You need to think outside the box if you want to
be sql developer. Besides, SQL server very poor serving the customs
while keeping and maintaining the spirit of relational model as well.
|||<bangla2@.yahoo.com> wrote in message
news:1176262461.536205.289270@.o5g2000hsb.googlegro ups.com...
> SQL is never meant to be a set based and all that.
Oh? Hmm, perhaps your reading of Codd and Date's work is different than
mine.

> We EXPECT and
> DEMAND from SQL Server to do many other things other than just simple
> set based operations. You need to think outside the box if you want to
> be sql developer. Besides, SQL server very poor serving the customs
> while keeping and maintaining the spirit of relational model as well.
>
Very poor serving the customs (sic. I assume you mean customers). I don't
know. Seems to me it serves them quite well and served my previous
employers very well.
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html
|||
>
> Well I can't say it will be. However, there is another fundamental issue
> that may arise.
> Given your query, it's very possible I could be inserting 1000 rows into the
> database where columns D, E fall into the range of your query. However, as
> written, there would be no locking on that range, which means your select
> could return some random subset of those rows.
> Also, since you can only have one IDENTITY column per table (insert CELKO's
> rant here), I'm not sure what you're getting at when trying to sort by 3
> columns anyway.
> You're much better off probably simply putting the columns into your select
> and ignoring them at the other end.
SQL is never meant to be ONLY set based and all that. We EXPECT and
DEMAND from SQL Server to do many other things other than just simple
set based operations. You need to think outside the box if you want
to
be a sql developer. Besides, SQL server is very poor serving the
customers
while keeping and maintaining the spirit of relational model as well.
It is not possible to develop an end to end application using SQL
Server compared to other database products in the market.

order by does not work

insert table1
select distinct a,b,c
from table2
order by d,e,f
Microsoft SQL server gives error:
"Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is
specified."
Why? Is there any option I can set to turn this feature
off?
(I have solved it by using an intermediate table. Table1 has an
identity column and that's why it is important to get the data in
right order.)<bangla2@.yahoo.com> wrote in message
news:1176182612.603459.136470@.q75g2000hsh.googlegroups.com...
> insert table1
> select distinct a,b,c
> from table2
> order by d,e,f
> Microsoft SQL server gives error:
> "Msg 145, Level 15, State 1, Line 1
> ORDER BY items must appear in the select list if SELECT DISTINCT is
> specified."
> Why? Is there any option I can set to turn this feature
> off?
The output of a SELECT DISTINCT query may have fewer rows than the base
table. So if you order by some column that isn't in the result how can SQL
Server know which row in the base table should determine the correct order?
For example you could try one of the following::
SELECT a,b,c
FROM table2
GROUP BY a,b,c
ORDER BY MIN(d), MIN(e), MIN(f);
SELECT a,b,c
FROM table2
GROUP BY a,b,c
ORDER BY MAX(d), MAX(e), MAX(f);
Both those queries will return the same rows as DISTINCT but they may result
in different orders depending on whether you use MIN or MAX.
> (I have solved it by using an intermediate table. Table1 has an
> identity column and that's why it is important to get the data in
> right order.)
>
A table has no order. IDENTITY isn't guaranteed to match insertion order and
in some circumstances the allocation order if the IDENTITY values may not
match your ORDER BY clause, especially in SQL Server 2000. In 2005, use the
ROW_NUMBER() to generate such a sequence. ROW_NUMBER() has its own
independent ORDER BY clause.
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||On Apr 10, 12:05 pm, "David Portas"
<REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
> <bang...@.yahoo.com> wrote in message
> news:1176182612.603459.136470@.q75g2000hsh.googlegroups.com...
> > insert table1
> > select distinct a,b,c
> > from table2
> > order by d,e,f
> > Microsoft SQL server gives error:
> > "Msg 145, Level 15, State 1, Line 1
> > ORDER BY items must appear in the select list if SELECT DISTINCT is
> > specified."
> > Why? Is there any option I can set to turn this feature
> > off?
> The output of a SELECT DISTINCT query may have fewer rows than the base
> table. So if you order by some column that isn't in the result how can SQL
> Server know which row in the base table should determine the correct order?
> For example you could try one of the following::
> SELECT a,b,c
> FROM table2
> GROUP BY a,b,c
> ORDER BY MIN(d), MIN(e), MIN(f);
> SELECT a,b,c
> FROM table2
> GROUP BY a,b,c
> ORDER BY MAX(d), MAX(e), MAX(f);
> Both those queries will return the same rows as DISTINCT but they may result
> in different orders depending on whether you use MIN or MAX.
So?
> > (I have solved it by using an intermediate table. Table1 has an
> > identity column and that's why it is important to get the data in
> > right order.)
> A table has no order.
Ok, sounds something new to me.
>IDENTITY isn't guaranteed to match insertion order and
> in some circumstances the allocation order if the IDENTITY values may not
> match your ORDER BY clause, especially in SQL Server 2000.
Its better be GURANTEED every time I execute this query. Thanks.
In 2005, use the
> ROW_NUMBER() to generate such a sequence. ROW_NUMBER() has its own
> independent ORDER BY clause.
Sorry, that's not an option (because I am using server 2k).
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --|||On Apr 10, 12:38 pm, bang...@.yahoo.com wrote:
> On Apr 10, 12:05 pm, "David Portas"
>
>
> <REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
> > <bang...@.yahoo.com> wrote in message
> >news:1176182612.603459.136470@.q75g2000hsh.googlegroups.com...
> > > insert table1
> > > select distinct a,b,c
> > > from table2
> > > order by d,e,f
> > > Microsoft SQL server gives error:
> > > "Msg 145, Level 15, State 1, Line 1
> > > ORDER BY items must appear in the select list if SELECT DISTINCT is
> > > specified."
> > > Why? Is there any option I can set to turn this feature
> > > off?
> > The output of a SELECT DISTINCT query may have fewer rows than the base
> > table. So if you order by some column that isn't in the result how can SQL
> > Server know which row in the base table should determine the correct order?
> > For example you could try one of the following::
> > SELECT a,b,c
> > FROM table2
> > GROUP BY a,b,c
> > ORDER BY MIN(d), MIN(e), MIN(f);
> > SELECT a,b,c
> > FROM table2
> > GROUP BY a,b,c
> > ORDER BY MAX(d), MAX(e), MAX(f);
> > Both those queries will return the same rows as DISTINCT but they may result
> > in different orders depending on whether you use MIN or MAX.
> So?
> > > (I have solved it by using an intermediate table. Table1 has an
> > > identity column and that's why it is important to get the data in
> > > right order.)
> > A table has no order.
> Ok, sounds something new to me.
> >IDENTITY isn't guaranteed to match insertion order and
> > in some circumstances the allocation order if the IDENTITY values may not
> > match your ORDER BY clause, especially in SQL Server 2000.
> Its better be GURANTEED every time I execute this query. Thanks.
> In 2005, use the
> > ROW_NUMBER() to generate such a sequence. ROW_NUMBER() has its own
> > independent ORDER BY clause.
> Sorry, that's not an option (because I am using server 2k).
>
> > --
> > David Portas, SQL Server MVP
> > Whenever possible please post enough code to reproduce your problem.
> > Including CREATE TABLE and INSERT statements usually helps.
> > State what version of SQL Server you are using and specify the content
> > of any error messages.
> > SQL Server Books Online:http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> > -- Hide quoted text -
> - Show quoted text -- Hide quoted text -
> - Show quoted text -
select distinct a,b
from t2
order by c
What I am trying to say is FIRST select all rows order by column c.
SECOND, based on that result set, select distinct rows for column a
and b. I think this should be fairly simple to do.|||On 10 Apr, 07:38, bang...@.yahoo.com wrote:
> On Apr 10, 12:05 pm, "David Portas"
>
> > A table has no order.
> Ok, sounds something new to me.
>
In that case I highly recommend that you read some introductory books
or take a course. Unordered tables are a pretty fundamental feature of
relational databases and SQL.
> What I am trying to say is FIRST select all rows order by column c.
> SECOND, based on that result set, select distinct rows for column a
> and b. I think this should be fairly simple to do.- Hide quoted text -
>
The best way to explain what you mean is to give an example using DDL
(CREATE TABLE statements) and some sample data (INSERT statements).
Here's a guess:
CREATE TABLE t2 (a INT NOT NULL, b INT NOT NULL, c INT NOT NULL,
PRIMARY KEY (a,b,c));
INSERT INTO t2 (a, b, c)
SELECT 1, 2, 1 UNION ALL
SELECT 1, 2, 4 UNION ALL
SELECT 1, 3, 2 UNION ALL
SELECT 1, 3, 1 ;
What result would you want based on this sample data? Notice that the
key of t2 may be an important factor but unfortunately you didn't
specify that information. If I'm wrong then please modify my CREATE
TABLE statement to match your actual case.
As you are using SQL Server 2000 the best solution may be to use a
subquery or a join to derive a deterministic "row number" for each
row. Here's an example using the Pubs database:
SELECT au_id,
(SELECT COUNT(*)
FROM authors
WHERE au_id <= a.au_id) AS row_number
FROM authors AS a ;
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||> > > A table has no order.
> > Ok, sounds something new to me.
> In that case I highly recommend that you read some introductory books
> or take a course. Unordered tables are a pretty fundamental feature of
> relational databases and SQL.
Gee, that was a joke for starters.
My problem is very simple (at least that's the best I can do to
without getting into the details of the actual problem).
select distinct a,b,c
from table1
order by d,e,f
First I want the server to select the rows order by d,e and f
Second, select the distinct rows from that set maintaining the
original order (so internally I would expect that the server would get
the rows from the original set in that order!! ! I know I an not find
that out without getting into the id of each row).
This should be fairly simple data manipulation to do in my opinion.|||On 10 Apr, 11:42, bang...@.yahoo.com wrote:
> My problem is very simple (at least that's the best I can do to
> without getting into the details of the actual problem).
> select distinct a,b,c
> from table1
> order by d,e,f
> First I want the server to select the rows order by d,e and f
> Second, select the distinct rows from that set maintaining the
> original order (so internally I would expect that the server would get
> the rows from the original set in that order!! ! I know I an not find
> that out without getting into the id of each row).
>
You didn't give the extra information I asked for so I can only repeat
the suggestion I made earlier. Try:
SELECT a, b, c
FROM table1
GROUP BY a, b, c
ORDER BY MIN(d), MIN(e), MIN(f);
Hope this helps.
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||<bangla2@.yahoo.com> wrote in message
news:1176187133.447900.81300@.y66g2000hsf.googlegroups.com...
> On Apr 10, 12:05 pm, "David Portas"
> <REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
>> <bang...@.yahoo.com> wrote in message
>> A table has no order.
>
> Ok, sounds something new to me.
As David points out, that's a fundamental definition of a table under SQL.
>
>>IDENTITY isn't guaranteed to match insertion order and
>> in some circumstances the allocation order if the IDENTITY values may not
>> match your ORDER BY clause, especially in SQL Server 2000.
>
> Its better be GURANTEED every time I execute this query. Thanks.
Well I can't say it will be. However, there is another fundamental issue
that may arise.
Given your query, it's very possible I could be inserting 1000 rows into the
database where columns D, E fall into the range of your query. However, as
written, there would be no locking on that range, which means your select
could return some random subset of those rows.
Also, since you can only have one IDENTITY column per table (insert CELKO's
rant here), I'm not sure what you're getting at when trying to sort by 3
columns anyway.
You're much better off probably simply putting the columns into your select
and ignoring them at the other end.
>
> In 2005, use the
>> ROW_NUMBER() to generate such a sequence. ROW_NUMBER() has its own
>> independent ORDER BY clause.
>
> Sorry, that's not an option (because I am using server 2k).
>
>> --
>> David Portas, SQL Server MVP
>> Whenever possible please post enough code to reproduce your problem.
>> Including CREATE TABLE and INSERT statements usually helps.
>> State what version of SQL Server you are using and specify the content
>> of any error messages.
>> SQL Server Books
>> Online:http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
>> --
>
--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||> Ok, sounds something new to me.
> As David points out, that's a fundamental definition of a table under SQL.
>
> >>IDENTITY isn't guaranteed to match insertion order and
> >> in some circumstances the allocation order if the IDENTITY values may not
> >> match your ORDER BY clause, especially in SQL Server 2000.
> > Its better be GURANTEED every time I execute this query. Thanks.
> Well I can't say it will be. However, there is another fundamental issue
> that may arise.
> Given your query, it's very possible I could be inserting 1000 rows into the
> database where columns D, E fall into the range of your query. However, as
> written, there would be no locking on that range, which means your select
> could return some random subset of those rows.
> Also, since you can only have one IDENTITY column per table (insert CELKO's
> rant here), I'm not sure what you're getting at when trying to sort by 3
> columns anyway.
> You're much better off probably simply putting the columns into your select
> and ignoring them at the other end.
>
SQL is never meant to be a set based and all that. We EXPECT and
DEMAND from SQL Server to do many other things other than just simple
set based operations. You need to think outside the box if you want to
be sql developer. Besides, SQL server very poor serving the customs
while keeping and maintaining the spirit of relational model as well.|||> >>IDENTITY isn't guaranteed to match insertion order and
> >> in some circumstances the allocation order if the IDENTITY values may not
> >> match your ORDER BY clause, especially in SQL Server 2000.
> > Its better be GURANTEED every time I execute this query. Thanks.
> Well I can't say it will be. However, there is another fundamental issue
> that may arise.
> Given your query, it's very possible I could be inserting 1000 rows into the
> database where columns D, E fall into the range of your query. However, as
> written, there would be no locking on that range, which means your select
> could return some random subset of those rows.
> Also, since you can only have one IDENTITY column per table (insert CELKO's
> rant here), I'm not sure what you're getting at when trying to sort by 3
> columns anyway.
> You're much better off probably simply putting the columns into your select
> and ignoring them at the other end.
SQL is never meant to be ONLY set based and all that. We EXPECT and
DEMAND from SQL Server to do many other things other than just simple
set based operations. You need to think outside the box if you want
to
be a sql developer. Besides, SQL server is very poor serving the
customers
while keeping and maintaining the spirit of relational model as well.
It is not possible to develop an end to end application using SQL
Server compared to other database products in the market.|||<bangla2@.yahoo.com> wrote in message
news:1176262461.536205.289270@.o5g2000hsb.googlegroups.com...
> > Ok, sounds something new to me.
>> As David points out, that's a fundamental definition of a table under
>> SQL.
>>
>> >>IDENTITY isn't guaranteed to match insertion order and
>> >> in some circumstances the allocation order if the IDENTITY values may
>> >> not
>> >> match your ORDER BY clause, especially in SQL Server 2000.
>> > Its better be GURANTEED every time I execute this query. Thanks.
>> Well I can't say it will be. However, there is another fundamental issue
>> that may arise.
>> Given your query, it's very possible I could be inserting 1000 rows into
>> the
>> database where columns D, E fall into the range of your query. However,
>> as
>> written, there would be no locking on that range, which means your select
>> could return some random subset of those rows.
>> Also, since you can only have one IDENTITY column per table (insert
>> CELKO's
>> rant here), I'm not sure what you're getting at when trying to sort by 3
>> columns anyway.
>> You're much better off probably simply putting the columns into your
>> select
>> and ignoring them at the other end.
> SQL is never meant to be a set based and all that.
Oh? Hmm, perhaps your reading of Codd and Date's work is different than
mine.
> We EXPECT and
> DEMAND from SQL Server to do many other things other than just simple
> set based operations. You need to think outside the box if you want to
> be sql developer. Besides, SQL server very poor serving the customs
> while keeping and maintaining the spirit of relational model as well.
>
Very poor serving the customs (sic. I assume you mean customers). I don't
know. Seems to me it serves them quite well and served my previous
employers very well.
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||<bangla2@.yahoo.com> wrote in message
news:1176267522.771378.242170@.b75g2000hsg.googlegroups.com...
> It is not possible to develop an end to end application using SQL
> Server compared to other database products in the market.
Really? Wow. I guess the last 8 years of my life was a dream then.
Since we did exactly that.
And I'll guess a number of other people here have done exactly the same
thing.
But hey, what do we know.
>
--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||> > It is not possible to develop an end to end application using SQL
> > Server compared to other database products in the market.
> Really? Wow. I guess the last 8 years of my life was a dream then.
> Since we did exactly that.
> And I'll guess a number of other people here have done exactly the same
> thing.
> But hey, what do we know.
End to end is developing form scratch to the end product including
processes related to BEFORE and AFFTER the project using Microsoft SQl
Server ONLY!
Example: Oracle (Forms), Sybase (Powersoft)|||<bangla2@.yahoo.com> wrote in message
news:1176269834.788198.90610@.o5g2000hsb.googlegroups.com...
>> > It is not possible to develop an end to end application using SQL
>> > Server compared to other database products in the market.
>> Really? Wow. I guess the last 8 years of my life was a dream then.
>> Since we did exactly that.
>> And I'll guess a number of other people here have done exactly the same
>> thing.
>> But hey, what do we know.
> End to end is developing form scratch to the end product including
> processes related to BEFORE and AFFTER the project using Microsoft SQl
> Server ONLY!
> Example: Oracle (Forms), Sybase (Powersoft)
>
.NET integrates well with SQL Server and I never heard a customer complain
about the fact that .NET comes on a separate disc. Why should it be a
problem that there are separate SKUs for the DBMS and the developer tool?
Even in the case of the products you mentioned the API components are a
separate install as far as I recall. I'm not sure what the purpose of your
question is.
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:OBxaix$eHHA.3632@.TK2MSFTNGP02.phx.gbl...
> <bangla2@.yahoo.com> wrote in message
> news:1176269834.788198.90610@.o5g2000hsb.googlegroups.com...
>> > It is not possible to develop an end to end application using SQL
>> > Server compared to other database products in the market.
>> Really? Wow. I guess the last 8 years of my life was a dream then.
>> Since we did exactly that.
>> And I'll guess a number of other people here have done exactly the same
>> thing.
>> But hey, what do we know.
>> End to end is developing form scratch to the end product including
>> processes related to BEFORE and AFFTER the project using Microsoft SQl
>> Server ONLY!
>> Example: Oracle (Forms), Sybase (Powersoft)
> .NET integrates well with SQL Server and I never heard a customer complain
> about the fact that .NET comes on a separate disc. Why should it be a
> problem that there are separate SKUs for the DBMS and the developer tool?
> Even in the case of the products you mentioned the API components are a
> separate install as far as I recall. I'm not sure what the purpose of your
> question is.
Exactly, neither are part of the RDBMS itself.
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>
--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||On 9 Apr 2007 23:42:37 -0700, bangla2@.yahoo.com wrote:
(snip)
>select distinct a,b
>from t2
>order by c
>What I am trying to say is FIRST select all rows order by column c.
>SECOND, based on that result set, select distinct rows for column a
>and b. I think this should be fairly simple to do.
Hi bangla,
Unfortunately, it is not. Consider the sample rows below (should display
properly with a fixed font). I have already executed the first step,
ordering by column c. But as you see, the duplicates for a and b are
still there.
RowNum a b c
1 1 1 1
2 2 2 2
3 1 1 3
4 3 3 4
5 1 1 5
I agree that it's fairly easy to perform the second step, removing the
duplicated for columns a and b, as well. In fact, this is so easy that I
have three different options to choose from: either I remove the rows
with rownumbers 1 and 3, or the rows wiith rownumbers 1 and 5, or the
rows with rownumbers 3 and 5. That leaves me with three different result
sets, that shoould all be considered "correct":
a b a b a b
1 1 2 2 2 2
2 2 1 1 3 3
3 3 3 3 1 1
Unfortunately, SQL is expected to return deterministic results. If three
different result sets, all with a different order, are all "correct"
then the results are not deterministic. That is why this is not allowed.
You have to tell SQL Server which of the three result sets you want. one
way of doing that, is to use the query already suggested by David:
SELECT a,b
FROM t2
GROUP BY a,b
ORDER BY MIN(c);
Which will return only this result set:
a b
1 1
2 2
3 3
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||On Apr 11, 10:57 am, "Greg D. Moore \(Strider\)"
<mooregr_deletet...@.greenms.com> wrote:
> <bang...@.yahoo.com> wrote in message
> news:1176262461.536205.289270@.o5g2000hsb.googlegroups.com...
>
>
> > > Ok, sounds something new to me.
> >> As David points out, that's a fundamental definition of a table under
> >> SQL.
> >> >>IDENTITY isn't guaranteed to match insertion order and
> >> >> in some circumstances the allocation order if the IDENTITY values may
> >> >> not
> >> >> match your ORDER BY clause, especially in SQL Server 2000.
> >> > Its better be GURANTEED every time I execute this query. Thanks.
> >> Well I can't say it will be. However, there is another fundamental issue
> >> that may arise.
> >> Given your query, it's very possible I could be inserting 1000 rows into
> >> the
> >> database where columns D, E fall into the range of your query. However,
> >> as
> >> written, there would be no locking on that range, which means your select
> >> could return some random subset of those rows.
> >> Also, since you can only have one IDENTITY column per table (insert
> >> CELKO's
> >> rant here), I'm not sure what you're getting at when trying to sort by 3
> >> columns anyway.
> >> You're much better off probably simply putting the columns into your
> >> select
> >> and ignoring them at the other end.
> > SQL is never meant to be a set based and all that.
> Oh? Hmm, perhaps your reading of Codd and Date's work is different than
> mine.
> > We EXPECT and
> > DEMAND from SQL Server to do many other things other than just simple
> > set based operations. You need to think outside the box if you want to
> > be sql developer. Besides, SQL server very poor serving the customs
> > while keeping and maintaining the spirit of relational model as well.
> Very poor serving the customs (sic. I assume you mean customers). I don't
> know. Seems to me it serves them quite well and served my previous
> employers very well.
> --
> Greg Moore
> SQL Server DBA Consulting Remote and Onsite available!
> Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html- Hide quoted text -
> - Show quoted text -
You should learn to read before venturing out writing beginning sql
codes. Thanks for listening.

Friday, March 23, 2012

order by does not work

insert table1
select distinct a,b,c
from table2
order by d,e,f
Microsoft SQL server gives error:
"Msg 145, Level 15, State 1, Line 1
ORDER BY items must appear in the select list if SELECT DISTINCT is
specified."
Why? Is there any option I can set to turn this feature
off?
(I have solved it by using an intermediate table. Table1 has an
identity column and that's why it is important to get the data in
right order.)<bangla2@.yahoo.com> wrote in message
news:1176182612.603459.136470@.q75g2000hsh.googlegroups.com...
> insert table1
> select distinct a,b,c
> from table2
> order by d,e,f
> Microsoft SQL server gives error:
> "Msg 145, Level 15, State 1, Line 1
> ORDER BY items must appear in the select list if SELECT DISTINCT is
> specified."
> Why? Is there any option I can set to turn this feature
> off?
The output of a SELECT DISTINCT query may have fewer rows than the base
table. So if you order by some column that isn't in the result how can SQL
Server know which row in the base table should determine the correct order?
For example you could try one of the following::
SELECT a,b,c
FROM table2
GROUP BY a,b,c
ORDER BY MIN(d), MIN(e), MIN(f);
SELECT a,b,c
FROM table2
GROUP BY a,b,c
ORDER BY MAX(d), MAX(e), MAX(f);
Both those queries will return the same rows as DISTINCT but they may result
in different orders depending on whether you use MIN or MAX.

> (I have solved it by using an intermediate table. Table1 has an
> identity column and that's why it is important to get the data in
> right order.)
>
A table has no order. IDENTITY isn't guaranteed to match insertion order and
in some circumstances the allocation order if the IDENTITY values may not
match your ORDER BY clause, especially in SQL Server 2000. In 2005, use the
ROW_NUMBER() to generate such a sequence. ROW_NUMBER() has its own
independent ORDER BY clause.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||On Apr 10, 12:05 pm, "David Portas"
<REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
> <bang...@.yahoo.com> wrote in message
> news:1176182612.603459.136470@.q75g2000hsh.googlegroups.com...
>
>
>
> The output of a SELECT DISTINCT query may have fewer rows than the base
> table. So if you order by some column that isn't in the result how can SQL
> Server know which row in the base table should determine the correct order
?
> For example you could try one of the following::
> SELECT a,b,c
> FROM table2
> GROUP BY a,b,c
> ORDER BY MIN(d), MIN(e), MIN(f);
> SELECT a,b,c
> FROM table2
> GROUP BY a,b,c
> ORDER BY MAX(d), MAX(e), MAX(f);
> Both those queries will return the same rows as DISTINCT but they may resu
lt
> in different orders depending on whether you use MIN or MAX.
So?

> A table has no order.
Ok, sounds something new to me.

>IDENTITY isn't guaranteed to match insertion order and
> in some circumstances the allocation order if the IDENTITY values may not
> match your ORDER BY clause, especially in SQL Server 2000.
Its better be GURANTEED every time I execute this query. Thanks.
In 2005, use the
> ROW_NUMBER() to generate such a sequence. ROW_NUMBER() has its own
> independent ORDER BY clause.
Sorry, that's not an option (because I am using server 2k).

> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:http://msdn2.microsoft.com/library/ms130214(en-US,
SQL.90).aspx
> --|||On Apr 10, 12:38 pm, bang...@.yahoo.com wrote:
> On Apr 10, 12:05 pm, "David Portas"
>
>
> <REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
>
>
>
>
>
>
>
>
> So?
>
>
> Ok, sounds something new to me.
>
> Its better be GURANTEED every time I execute this query. Thanks.
> In 2005, use the
>
> Sorry, that's not an option (because I am using server 2k).
>
>
>
>
> - Show quoted text -- Hide quoted text -
> - Show quoted text -
select distinct a,b
from t2
order by c
What I am trying to say is FIRST select all rows order by column c.
SECOND, based on that result set, select distinct rows for column a
and b. I think this should be fairly simple to do.|||On 10 Apr, 07:38, bang...@.yahoo.com wrote:
> On Apr 10, 12:05 pm, "David Portas"
>
> Ok, sounds something new to me.
>
In that case I highly recommend that you read some introductory books
or take a course. Unordered tables are a pretty fundamental feature of
relational databases and SQL.

> What I am trying to say is FIRST select all rows order by column c.
> SECOND, based on that result set, select distinct rows for column a
> and b. I think this should be fairly simple to do.- Hide quoted text -
>
The best way to explain what you mean is to give an example using DDL
(CREATE TABLE statements) and some sample data (INSERT statements).
Here's a guess:
CREATE TABLE t2 (a INT NOT NULL, b INT NOT NULL, c INT NOT NULL,
PRIMARY KEY (a,b,c));
INSERT INTO t2 (a, b, c)
SELECT 1, 2, 1 UNION ALL
SELECT 1, 2, 4 UNION ALL
SELECT 1, 3, 2 UNION ALL
SELECT 1, 3, 1 ;
What result would you want based on this sample data? Notice that the
key of t2 may be an important factor but unfortunately you didn't
specify that information. If I'm wrong then please modify my CREATE
TABLE statement to match your actual case.
As you are using SQL Server 2000 the best solution may be to use a
subquery or a join to derive a deterministic "row number" for each
row. Here's an example using the Pubs database:
SELECT au_id,
(SELECT COUNT(*)
FROM authors
WHERE au_id <= a.au_id) AS row_number
FROM authors AS a ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||> > > A table has no order.
>
> In that case I highly recommend that you read some introductory books
> or take a course. Unordered tables are a pretty fundamental feature of
> relational databases and SQL.
Gee, that was a joke for starters.
My problem is very simple (at least that's the best I can do to
without getting into the details of the actual problem).
select distinct a,b,c
from table1
order by d,e,f
First I want the server to select the rows order by d,e and f
Second, select the distinct rows from that set maintaining the
original order (so internally I would expect that the server would get
the rows from the original set in that order!! ! I know I an not find
that out without getting into the id of each row).
This should be fairly simple data manipulation to do in my opinion.|||On 10 Apr, 11:42, bang...@.yahoo.com wrote:
> My problem is very simple (at least that's the best I can do to
> without getting into the details of the actual problem).
> select distinct a,b,c
> from table1
> order by d,e,f
> First I want the server to select the rows order by d,e and f
> Second, select the distinct rows from that set maintaining the
> original order (so internally I would expect that the server would get
> the rows from the original set in that order!! ! I know I an not find
> that out without getting into the id of each row).
>
You didn't give the extra information I asked for so I can only repeat
the suggestion I made earlier. Try:
SELECT a, b, c
FROM table1
GROUP BY a, b, c
ORDER BY MIN(d), MIN(e), MIN(f);
Hope this helps.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||<bangla2@.yahoo.com> wrote in message
news:1176187133.447900.81300@.y66g2000hsf.googlegroups.com...
> On Apr 10, 12:05 pm, "David Portas"
> <REMOVE_BEFORE_REPLYING_dpor...@.acm.org> wrote:
>
> Ok, sounds something new to me.
As David points out, that's a fundamental definition of a table under SQL.
>
>
> Its better be GURANTEED every time I execute this query. Thanks.
Well I can't say it will be. However, there is another fundamental issue
that may arise.
Given your query, it's very possible I could be inserting 1000 rows into the
database where columns D, E fall into the range of your query. However, as
written, there would be no locking on that range, which means your select
could return some random subset of those rows.
Also, since you can only have one IDENTITY column per table (insert CELKO's
rant here), I'm not sure what you're getting at when trying to sort by 3
columns anyway.
You're much better off probably simply putting the columns into your select
and ignoring them at the other end.

>
> In 2005, use the
>
> Sorry, that's not an option (because I am using server 2k).
>
>
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||
>
> Well I can't say it will be. However, there is another fundamental issue
> that may arise.
> Given your query, it's very possible I could be inserting 1000 rows into t
he
> database where columns D, E fall into the range of your query. However, a
s
> written, there would be no locking on that range, which means your select
> could return some random subset of those rows.
> Also, since you can only have one IDENTITY column per table (insert CELKO'
s
> rant here), I'm not sure what you're getting at when trying to sort by 3
> columns anyway.
> You're much better off probably simply putting the columns into your selec
t
> and ignoring them at the other end.
SQL is never meant to be ONLY set based and all that. We EXPECT and
DEMAND from SQL Server to do many other things other than just simple
set based operations. You need to think outside the box if you want
to
be a sql developer. Besides, SQL server is very poor serving the
customers
while keeping and maintaining the spirit of relational model as well.
It is not possible to develop an end to end application using SQL
Server compared to other database products in the market.|||<bangla2@.yahoo.com> wrote in message
news:1176267522.771378.242170@.b75g2000hsg.googlegroups.com...
> It is not possible to develop an end to end application using SQL
> Server compared to other database products in the market.
Really? Wow. I guess the last 8 years of my life was a dream then.
Since we did exactly that.
And I'll guess a number of other people here have done exactly the same
thing.
But hey, what do we know.

>
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.htmlsql

Wednesday, March 21, 2012

Order By Case Cast Convert Error

I have created a SQL Stored Procedure that uses a Case statement to
determine the Order By. For one of the Case statements I am trying to
turn a Char field into Datetime in for the Order By, however I can not
get it to work. Can someone please take a look and my code below and
tell me what I am doing wrong. Thank you.

ORDER BY
CASE WHEN @.SortBy = 'dttm_stamp' THEN dttm_stamp End,
CASE WHEN @.SortBy = 'Event_Date1' THEN CAST(CONVERT(char(10),
Event_Date1,101) as datetime) End,
CASE WHEN @.SortBy = 'FullName' THEN Emp_lastname + ', ' +
Emp_firstname End,
CASE WHEN @.SortBy = 'FullName Desc' THEN Emp_lastname + ', ' +
Emp_firstname End DESC,
CASE WHEN @.SortBy = 'Emp_SSN' THEN Emp_SSN End<jguilford@.cybergroup.com> wrote in message
news:1105983724.986065.70140@.c13g2000cwb.googlegro ups.com...
>I have created a SQL Stored Procedure that uses a Case statement to
> determine the Order By. For one of the Case statements I am trying to
> turn a Char field into Datetime in for the Order By, however I can not
> get it to work. Can someone please take a look and my code below and
> tell me what I am doing wrong. Thank you.
> ORDER BY
> CASE WHEN @.SortBy = 'dttm_stamp' THEN dttm_stamp End,
> CASE WHEN @.SortBy = 'Event_Date1' THEN CAST(CONVERT(char(10),
> Event_Date1,101) as datetime) End,
> CASE WHEN @.SortBy = 'FullName' THEN Emp_lastname + ', ' +
> Emp_firstname End,
> CASE WHEN @.SortBy = 'FullName Desc' THEN Emp_lastname + ', ' +
> Emp_firstname End DESC,
> CASE WHEN @.SortBy = 'Emp_SSN' THEN Emp_SSN End

What does "can not get it to work" mean? Do you get errors, or do you get
unexpected results? The best idea would probably be to post CREATE TABLE and
INSERT statements to set up a test case which illustrates your problem.

http://www.aspfaq.com/etiquette.asp?id=5006

Simon|||On 17 Jan 2005 09:42:05 -0800, jguilford@.cybergroup.com wrote:

>I have created a SQL Stored Procedure that uses a Case statement to
>determine the Order By. For one of the Case statements I am trying to
>turn a Char field into Datetime in for the Order By, however I can not
>get it to work. Can someone please take a look and my code below and
>tell me what I am doing wrong. Thank you.

Hi jquilford,

I guess that this is the line that's giving you trouble:

>CASE WHEN @.SortBy = 'Event_Date1' THEN CAST(CONVERT(char(10),
>Event_Date1,101) as datetime) End,

You are converting the datetime variable to the american mm/dd/yyyy
format, which is not very well suited for sorting. Then you are converting
it back to datetime, running alll kinds of risks because this format is
ambiguous - it's easily misinterpreted as dd/mm/yyyy, causing either wrong
sorting or conversion errors.

If your intention is to strip the time part from the datetime column, so
you can order by the date part only, use

CASE WHEN @.SortBy = 'Event_Date1' THEN DATEADD(day, DATEDIFF(day,
'20000101', Event_Date1), '20000101')

Or, if you really want to do it by conversion to string and back, use the
safe yyyymmdd format:

CASE WHEN @.SortBy = 'Event_Date1' THEN CAST(CONVERT(char(8),
Event_Date1,112) as datetime) End,

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo Kornelis (hugo@.pe_NO_rFact.in_SPAM_fo) writes:
> Or, if you really want to do it by conversion to string and back, use the
> safe yyyymmdd format:
> CASE WHEN @.SortBy = 'Event_Date1' THEN CAST(CONVERT(char(8),
> Event_Date1,112) as datetime) End,

Or simply say:

CASE WHEN @.SortBy = 'Event_Date1'
THEN CONVERT(char(8), Event_Date1,112)
End,

Then again, we have no idea jguildford mean "I can not get it to work".

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||On Mon, 17 Jan 2005 22:40:11 +0000 (UTC), Erland Sommarskog wrote:

>Hugo Kornelis (hugo@.pe_NO_rFact.in_SPAM_fo) writes:
>> Or, if you really want to do it by conversion to string and back, use the
>> safe yyyymmdd format:
>>
>> CASE WHEN @.SortBy = 'Event_Date1' THEN CAST(CONVERT(char(8),
>> Event_Date1,112) as datetime) End,
>Or simply say:
> CASE WHEN @.SortBy = 'Event_Date1'
> THEN CONVERT(char(8), Event_Date1,112)
> End,

Hi Erland,

Of course - no need to change it back to datetime in this case. Thanks!

>Then again, we have no idea jguildford mean "I can not get it to work".

Maybe he (she?) will post with more details?

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||1) why are you using a CASE expression in an ORDER BY? Is the
destruction of portable code one of your design goals?

2) The column used for a sort should appear in the output so a human
being can use it to search the list. Basic human factors, etc. Put it
in the SELECT list.

3) Why are you making a date into a string in the first place? You can
sort of temporal datatypes too. And why are you converting it to a
string that is not in temporal order?|||Let me try to better explain my problem. I have created a page in
asp.net that has a datagrid that pulls a few fields form a SQL Server
table. Also on this page there is a dropdown box that allows you to
pick the way the data is sorted. You can pick to sort it by the data
the record was created, name (both ascending and descending), social
security number and by the date of the event. Now here is my problem,
the Event_Date1 field is a 10 character field (00/00/0000) instead of a
datetime field, it was set up like this a long time ago and can not be
changed. Because it is a character field when you use it to sort the
data it is sorted by month then day then year instead of year then
month then day. I tried to use a Cast and Convert statement to change
it to a datetime so it would sort correctly but now when I try to sort
by Event_Date1 I receive this error: "The conversion of a char data
type to a datetime data type resulted in an out-of-range datetime
value." I have included all of the code in my stored procedure below.
I hop this clears up some of the confusion. Let me know if there is
anything else I did not clear up. Thank you.

CREATE PROCEDURE spShowArchives
@.SecurityID int,
@.SortBy varchar(50)
AS
SELECT ID, Emp_lastname + ', ' + Emp_firstname as FullName, Emp_SSN,
Event_Date1, Injury_Illness_Type, Jurisdiction, Injury_Cause_Desc,
SISCO_claim, dttm_stamp FROM omni_table
WHERE security_id = @.SecurityID
AND omni_table.deleted_flag = 0
AND (SISCO_claim <> '' or SISCO_claim <> null or SISCO_claim <>
'Submit')
ORDER BY
CASE WHEN @.SortBy = 'dttm_stamp' THEN dttm_stamp End,
CASE WHEN @.SortBy = 'Event_Date1' THEN CAST(CONVERT(char(10),
Event_Date1,101) as datetime) End,
CASE WHEN @.SortBy = 'FullName' THEN Emp_lastname + ', ' +
Emp_firstname End,
CASE WHEN @.SortBy = 'FullName Desc' THEN Emp_lastname + ', ' +
Emp_firstname End DESC,
CASE WHEN @.SortBy = 'Emp_SSN' THEN Emp_SSN End
GO|||On 18 Jan 2005 11:53:03 -0800, jagguil4d wrote:

>Let me try to better explain my problem.
(snip)
> Now here is my problem,
>the Event_Date1 field is a 10 character field (00/00/0000) instead of a
>datetime field, it was set up like this a long time ago and can not be
>changed.

Hi jagguil4d / jguilford,

This is not correct. Of course it *can* be changed. You probably meant to
write that someone in your organization doesn't *want* it to be changed.
And that someone is most likely the person who's budget is impacted by the
cost of actually imprivong your system, but doesn't suffer from the
(eventually) much higher costs of numerous workarounds, bugfixes and error
recovery.

> Because it is a character field when you use it to sort the
>data it is sorted by month then day then year instead of year then
>month then day. I tried to use a Cast and Convert statement to change
>it to a datetime so it would sort correctly but now when I try to sort
>by Event_Date1 I receive this error: "The conversion of a char data
>type to a datetime data type resulted in an out-of-range datetime
>value."

You might try if you have more luck with
CASE WHEN @.SortBy = 'Event_Date1' THEN CONVERT(datetime, Event_Date1,
101) End,

If that fails as well, you have at least one row in your table with an
invalid date (and boy, are you lucky if it is indeed only one <g>). These
can be hard to find. A good starting point would be
SELECT KeyColumn, Event_Date1
FROM omni_table
WHERE ISDATE(Event_Date1) = 0

If the above returns no rows, but you get errors converting Event_Date1 to
datetime, then you probably have rows with a date in DD/MM/YYYY format, or
some other date format. The following will hopefully catch most of these
buggers:
SELECT KeyColumn, Event_Date1
FROM omni_table
WHERE Event_Date1 >= '13'
OR Event_Date1 NOT LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'

Good luck! (You'll need it...)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||jagguil4d (jguilford@.cybergroup.com) writes:
> Now here is my problem, the Event_Date1 field is a 10 character field
> (00/00/0000) instead of a datetime field, it was set up like this a long
> time ago and can not be changed.

Of course it can! I hear this lame excuse every time, but seriously,
yes it can be changed. Just why would it be left unchanged?

Anyway, as Hugo points out you have garabge in this column, so if
you insist on that you don't want to change it, do this:

CASE WHEN @.SortBy = 'Event_Date1' THEN
substring(Event_Date1, 7, 4) + substring(Event_Date1, 1, 2) +
substring(Event_Date1, 4, 2)

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||--CELKO-- (jcelko212@.earthlink.net) writes:
> 1) why are you using a CASE expression in an ORDER BY? Is the
> destruction of portable code one of your design goals?

Because he more cares about serving his users than paying sacrifice
to the Holy Church of Portability.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||>> he more cares about serving his users than paying sacrifice to the
Holy Church of Portability. <<

When you can get portability for no extra cost, there is no sacrifice
and considerable gains in maintaining the code over the life of the
system. Would really use getdate() instead of CURRENT_TIMESTAMP to
save a few keystrokes? Or ISNULL() instead of COALESCE()?|||--CELKO-- (jcelko212@.earthlink.net) writes:
> When you can get portability for no extra cost, there is no sacrifice
> and considerable gains in maintaining the code over the life of the
> system. Would really use getdate() instead of CURRENT_TIMESTAMP to
> save a few keystrokes? Or ISNULL() instead of COALESCE()?

In this case you questioned the use of CASE in ORDER BY, which
jguilford had added to offer desired functionailty to his application.
So there is a cost to be portable here.

By the way, there is a situations where isnull() works, but not
coalesce().

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

ORDER BY before UNION syntax error

I have a list of Nationalities which I want to sort alphabetically except
for the value of Nationality which is "not disclosed" which I would like to
put at the top of the list.
I'm trying to do this with the following query but there seems to be a
problem with putting the ORDER BY in front of the UNION keyword
:
SELECT TOP 100 PERCENT NationalityID, Nationality
FROM dbo.Nationality
WHERE (Nationality <>'not disclosed')
ORDER BY Nationality
UNION
SELECT TOP 100 PERCENT NationalityID, Nationality
FROM dbo.Nationality
WHERE (Nationality = 'not disclosed')
I tried using brackets around the first part of the query but that didn't
work.
Any help much appreciated.
PeteHi
You can add an extra columns (examples are not tested!)
SELECT TOP 100 PERCENT NationalityID, Nationality, 0 as OrderBy
FROM dbo.Nationality
WHERE Nationality <>'not disclosed'
UNION
SELECT TOP 100 PERCENT NationalityID, Nationality, 1
FROM dbo.Nationality
WHERE Nationality = 'not disclosed'
ORDER BY OrderBy, Nationality
Although you do not need a UNION in this example:
SELECT DISTINCT NationalityID, Nationality, CASE WHEN Nationality = 'not
disclosed' THEN 1 ELSE 0 END as OrderBy
FROM dbo.Nationality
ORDER BY OrderBy, Nationality
If you want to remove this from the result set you can use a derived table.
SELECT NationalityID, Nationality
FROM
( SELECT DISTINCT NationalityID, Nationality, CASE WHEN Nationality =
'not disclosed' THEN 1 ELSE 0 END as OrderBy
FROM dbo.Nationality ) A
ORDER BY OrderBy, Nationality
John
"Italian Pete" wrote:

> I have a list of Nationalities which I want to sort alphabetically except
> for the value of Nationality which is "not disclosed" which I would like t
o
> put at the top of the list.
> I'm trying to do this with the following query but there seems to be a
> problem with putting the ORDER BY in front of the UNION keyword
> :
> SELECT TOP 100 PERCENT NationalityID, Nationality
> FROM dbo.Nationality
> WHERE (Nationality <>'not disclosed')
> ORDER BY Nationality
> UNION
> SELECT TOP 100 PERCENT NationalityID, Nationality
> FROM dbo.Nationality
> WHERE (Nationality = 'not disclosed')
> I tried using brackets around the first part of the query but that didn't
> work.
> Any help much appreciated.
> Pete|||Perfect!! Works a treat.
Thanks John
"John Bell" wrote:
> Hi
> You can add an extra columns (examples are not tested!)
> SELECT TOP 100 PERCENT NationalityID, Nationality, 0 as OrderBy
> FROM dbo.Nationality
> WHERE Nationality <>'not disclosed'
> UNION
> SELECT TOP 100 PERCENT NationalityID, Nationality, 1
> FROM dbo.Nationality
> WHERE Nationality = 'not disclosed'
> ORDER BY OrderBy, Nationality
> Although you do not need a UNION in this example:
> SELECT DISTINCT NationalityID, Nationality, CASE WHEN Nationality = 'n
ot
> disclosed' THEN 1 ELSE 0 END as OrderBy
> FROM dbo.Nationality
> ORDER BY OrderBy, Nationality
> If you want to remove this from the result set you can use a derived table
.
> SELECT NationalityID, Nationality
> FROM
> ( SELECT DISTINCT NationalityID, Nationality, CASE WHEN Nationality =
> 'not disclosed' THEN 1 ELSE 0 END as OrderBy
> FROM dbo.Nationality ) A
> ORDER BY OrderBy, Nationality
> John
> "Italian Pete" wrote:
>|||Italian wrote on Fri, 27 May 2005 04:59:53 -0700:
> Perfect!! Works a treat.
> Thanks John
> "John Bell" wrote:
>
Rather than using a UNION, you can do this in a single SELECT which should
be more efficient:
SELECT TOP 100 PERCENT NationalityID, Nationality
FROM dbo.Nationality
ORDER BY CASE WHEN Nationality = 'not disclosed' THEN 0 ELSE 1 END
Dan|||Daniel wrote to Italian Pete on Fri, 27 May 2005 15:25:34 +0100:

> Italian wrote on Fri, 27 May 2005 04:59:53 -0700:
>
> Rather than using a UNION, you can do this in a single SELECT which should
> be more efficient:
> SELECT TOP 100 PERCENT NationalityID, Nationality
> FROM dbo.Nationality
> ORDER BY CASE WHEN Nationality = 'not disclosed' THEN 0 ELSE 1 END
>
Just noticed that's almost the same as Italian Pete posted. However, this
gives you just the 2 columns you wanted and doesn't require a derived table.
Dan|||Daniel wrote to Daniel Crichton on Fri, 27 May 2005 15:39:22 +0100:

> Just noticed that's almost the same as Italian Pete posted. However, this
> gives you just the 2 columns you wanted and doesn't require a derived
> table.
You know what, I need more caffeine and sleep. I meant John Bell.
:\
Dan

order by and UNION

Hi, I got an error "ORDER BY items must appear in the select list if the
statement contains a UNION operator." when trying to put an order clause at
the end ot the union query.
How to set order to the whole set? Thanks.That will order the entire set, if the column exists. Does it? Can you
post the code you're having trouble with?
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"js" <js@.someone@.hotmail.com> wrote in message
news:%23FAx7z1IFHA.1248@.TK2MSFTNGP10.phx.gbl...
> Hi, I got an error "ORDER BY items must appear in the select list if the
> statement contains a UNION operator." when trying to put an order clause
at
> the end ot the union query.
> How to set order to the whole set? Thanks.
>|||When using the ORDER BY clause in a query with a UNION, you must adhere
to the ANSI SQL-92 standard, which says you cannot use expressions in
the ORDER BY clause, but only the names or ordinal positions of the
columns in the resultset.
Hope this helps,
Gert-Jan
js wrote:
> Hi, I got an error "ORDER BY items must appear in the select list if the
> statement contains a UNION operator." when trying to put an order clause a
t
> the end ot the union query.
> How to set order to the whole set? Thanks.|||select colA,colB
from tableA
union
select stuff as colA,blah as ColB
from tableB
order by 1,2 asc
// 1 = colA and 2=colB
2005 Microsoft MVP C#
Robbe Morris
http://www.robbemorris.com
http://www.learncsharp.net/home/listings.aspx
"js" <js@.someone@.hotmail.com> wrote in message
news:%23FAx7z1IFHA.1248@.TK2MSFTNGP10.phx.gbl...
> Hi, I got an error "ORDER BY items must appear in the select list if the
> statement contains a UNION operator." when trying to put an order clause
> at the end ot the union query.
> How to set order to the whole set? Thanks.
>