Query Sort Question
Jul 20, 2005
I have a field called "type" in my "school" table that can have three
possibilities:
Elementary
Middle
High
In my result set, I always want Elementary to come first, Middle to
come second, and High to come third. An alpha sort gets me this:
Elementary
High
Middle
Sure, I could create a look-up that assigns an integer to the "type"
field to get the right sort order (i.e. elementary = 0, middle = 1,
high = 2) ... but is there a better way to do this with SQL syntax?
Thanks,
Ralph Noble
Join Bytes!
View 1 Replies
ADVERTISEMENT
Feb 28, 2005
Trying to get data from result of MDX query in dec order:
iLoopFrom = cst.Axes(1).Positions.Count - 1
iLoopTo = 0
iLoopStep = -1
im using these lines to read the data from bottom to top but what exactly does Position.Count do? and is the -1 there because the result has headers??
Thanks
View 1 Replies
View Related
Jan 2, 2007
I'm trying to find a way to sort my query like the following:
SELECT * FROM tbl_Post WHERE ID = 3 OR ID = 1 OR ID = 4 OR ID = 2 ORDER BY (3,1,4,2)
Now if ID is my primary key, the sort by default would be 1, 2, 3, 4.
I would like to specify order so that I could return the order as 3, 1, 4, 2 if I wanted to.
Is there any way to do this?
Thanks,Russ
View 2 Replies
View Related
Dec 18, 2007
Dear All,
i need your help,
i had created a table student, studentid column with alpha numeric primary key with varchar datatype
now my problem: i want to sort the student id accroding to studentid like
STU1
STU2
STU3
STU4
STU5
.
.
.
STU9
STU10
STU11
but i’m getting the sorted result like this, how to overcome this problem,guide me PLEASE
STU1
STU10
STU11
STU12
.
.
.
STU100
.
.
.
STU1000
STU10000
STU2
STU20
STU200
STU2000
STU20000
STU20001
Thank's In Advances
View 9 Replies
View Related
Feb 27, 2005
I have a query:
SELECT *
FROM Mobile_Subscriber
WHERE (sub_ID IN (17, 2, 19))
The result return:
sub_ID sub_name
2 John
17 Alice
19 Eddy
But what I want is:
sub_ID sub_name
17Alice
2John
19Eddy
Is it possible to return the result order by the query with: sub_ID IN (17,2,19)?
View 3 Replies
View Related
Oct 14, 2005
Hello everyone,
I Have a table with columns:
- CustomerID
- DateTransactionCompleted
- AmountPaid
Illustration data as follow
GO
INSERT INTO Cus_Tab_Dev_2 VALUES(30,'12-12-2004','18000.00')
INSERT INTO Cus_Tab_Dev_2 VALUES(30,'12-15-2004','2000.00')
INSERT INTO CUS_Tab_Dev_2 VALUES(30,'1-16-2005','15000.00')
INSERT INTO CUS_TAB_DEV_2 VALUES(42,'2-2-2005','12000.00')
GO
What I want is a report that tells me the Total Sales per month Per Customer in the following manner:
Customer ID Month/Year Total Per Month
----------- ----------- ----------------
30 12-2004 20000.00
30 1-2005 15000.00
42 2-2005 12000.00
This is a homework, and I have been trying to get it to work since this morning. Any help is appreciated.
PS: If you do not feel you want/should help. Please don't call me names! I don't ask people to help me with my homework usually. But, I am running out of time on the assignment.
View 4 Replies
View Related
Jul 23, 2005
I have three tables:tblBook has the fields bookID, bookRangeID, bookSubjectID, bookCodetblBookRange has the fields bookRangeID, bookRangeDescriptiontblBookSubject has the fields bookSubjectID, bookSubjectDescriptionso some typical data in tblBook might be:1, 1, 1, B1HBSCI2, 1, 2, B2HBFRE13, 1, 3, B3HBGER4, 2, 1, B4PBSCI5, 2, 2, B5PBFRE6, 2, 3, B6PBGER7, 3, 1, B7CDSCI8, 3, 2, B8CDFRE9, 3, 3, B9CDGER110, 3, 3, B10CDGER211, 1, 2, B11HBFRE2tblBookRange would be:1, HardBack2, PaperBack3, CD RomtblBookSubject would be:1, Science2, French3, GermanI'd like to create a query which will return me the subjects along thetop, the book range down the side, and the bookcodes in the cells, abit like this:BookRange , Science, French, GermanHardBack , B1HBSCI, B2HBFRE1 B11HBFRE2, B3HBGERPaperBack , B4PBSCI, B5PBFRE, B6PBGERCD Rom , B7CDSCI, B8CDFRE, B9CDGER1 B10CDGER2Does that make any sense? So basically I'd like to get some kind ofdynamic SQL working which will do this kind of thing. I don't want tohard code the subjects in or the book ranges. I get the feeling thatdynamic SQL is the way forward with this and possibly using a cursor ortwo too, but it got quite nasty and convoluted when I tried variousattempts to get it working. (one of the ways I tried included workingout each result in a dynamic script, but it ran out of characters asthere were too many "subjects".)If anyone has any nice but quite dynamic solutions, I'd be delighted tohear.(and I know some of you have already told me you don't like tablesbeginnig with tbl, but I'm not hear for a lecture on namingconventions, I'm hear to learn and share ideas :o) )
View 2 Replies
View Related
Aug 3, 2007
I want to sort on a field that I construct during a query....how can I solve this?Basically what i am doing is selecting mediafiles with comments in descending order. (so mediafile with most comments on top)Here's my (not working) query, because it throws the error that the mediaComments column is unknown....SELECT *FROM(select ROW_NUMBER() OVER (ORDER BY mediaComments DESC) as RowNum,m.title,m.usercode,mediaComments=(select count(*) from MediaComments where mediaid=m.mediaid)FROM Media m WHERE m.usercode>0group by m.title,m.usercode) as InfoWHERE RowNum between @startRowIndex AND (@startRowIndex + @maximumRows-1)
View 4 Replies
View Related
Aug 7, 2007
I am trying to set sorting up on a DataGrid in ASP.NET 2.0. I have it working so that when you click on the column header, it sorts by that column, what I would like to do is set it up so that when you click the column header again it sorts on that field again, but in the opposite direction. I have it working using the following code in the stored procedure: CASE WHEN @SortColumn = 'Field1' AND @SortOrder = 'DESC' THEN Convert(sql_variant, FileName) end DESC,
case when @SortColumn = 'Field1' AND @SortOrder = 'ASC' then Convert(sql_variant, FileName) end ASC,
case WHEN @SortColumn = 'Field2' and @SortOrder = 'DESC' THEN CONVERT(sql_variant, Convert(varchar(8000), FileDesc)) end DESC,
case when @SortColumn = 'Field2' and @SortOrder = 'ASC' then convert(sql_variant, convert(varchar(8000), FileDesc)) end ASC,
case when @SortColumn = 'VersionNotes' and @SortOrder = 'DESC' then convert(sql_variant, convert(varchar(8000), VersionNotes)) end DESC,
case when @SortColumn = 'VersionNotes' and @SortOrder = 'ASC' then convert(sql_variant, convert(varchar(8000), VersionNotes)) end ASC,
case WHEN @SortColumn = 'FileDataID' and @SortOrder = 'DESC' THEN CONVERT(sql_variant, FileDataID) end DESC,
case WHEN @SortColumn = 'FileDataID' and @SortOrder = 'ASC' THEN CONVERT(sql_variant, FileDataID) end ASC And I gotta tell you, that is ugly code, in my opinion. What I am trying to do is something like this: case when @SortColumn = 'Field1' then FileName end,
case when @SortColumn = 'FileDataID' then FileDataID end,
case when @SortColumn = 'Field2' then FileDesc
when @SortColumn = 'VersionNotes' then VersionNotes
end
case when @SortOrder = 'DESC' then DESC
when @SortOrder = 'ASC' then ASC
end and it's not working at all, i get an error saying: Incorrect syntax near the keyword 'case' when i put a comma after the end on line 5 i get: Incorrect syntax near the keyword 'DESC' What am I missing here? Thanks in advance for any help -Madrak
View 1 Replies
View Related
Mar 15, 2007
Hi Everyone,I am creating a portal and want the user to be able to select four variants from four separate drop down boxes... Such as chapter, story, etc... The user will then be able to click Find and shorten up the gridview list. The below query is what I am using for my current gridview (with custom paging). What I want to do is something like this: Pass a variable such as @Story. If no Story is chosen, then the variable would be *. If a variable is chosen, the the @Story would the StoryID. However, I don't believe SQL recognizes the * in this case. I was thinking it should, but I don't believe it does. I was hoping it would just take it and I could write, SELECT * from Stories where StoryId=@Story, or something like that... and if * was @Story, then it would just select all... or if it was 1, then just stories with a StoryId of 1.Am I totally off base here? Thanks! CREATE PROCEDURE SortAllStories@startRowIndex int,@maximumRows int,@totalRows int OUTPUTASDECLARE @first_id int, @startRow intSET @startRowIndex = (@startRowIndex - 1) * @maximumRowsIF @startRowIndex = 0SET @startRowIndex = 1SET ROWCOUNT @startRowIndexSELECT @first_id = StoriesID FROM Storie ORDER BY StoriesIdPRINT @first_idSET ROWCOUNT @maximumRowsSELECT Stories.StoryId, Chapters.ChapterName, Chapters.EnglishName, Translations.Translation,Stories.Verse, Stories.StoryFROM Chapters, Stories, TranslationsWHERE Chapters.ChapterId=Stories.ChapterId AND Translations.TranslationId = Stories.TranslationId AND Stories.StoryId >= @first_idORDER BY Stories.StoryIdSET ROWCOUNT 0SELECT @totalRows = COUNT(StoryId) FROM Stories
View 3 Replies
View Related
Jan 16, 2005
Hi,
Anyone can help me for the Sql query?
I want to sort a table with a priority column, e.g. in the following...
Table A
======
value
======
9
3
1
7
4
======
After sorting:
Table A
========
no value
========
1 1
2 3
3 4
4 7
5 9
========
Anyone can help me?
Thanks.
Daniel.
View 1 Replies
View Related
Jan 30, 2015
which have a lot of impact to database performace since it do not fit onto memory and spill over to disks.
The question is when i ran a profiler and tried to catch a sort warning i cannot find the query which cause the alert.
View 1 Replies
View Related
Sep 17, 2015
I am using a table to store different size numbers for example:
Look at the picture below:
But I want this type of output look at the picture below:
How to sort the query to return greater than zero values to sort up and zeros go down.
I am using sql server 2008.
View 14 Replies
View Related
Aug 2, 2006
this data. need help
Sort following numbers by asc and desc order
Before query sort
-1.1
-8.8
-15.5
0.0
+0.5
+0.2
Sort asc
+0.5
+0.2
0.0
-1.1
-8.8
Sort Desc
-8.8
-1.1
0.0
+0.2
+0.5
View 5 Replies
View Related
Jul 20, 2005
I haven't a clue how to accomplish this.All the data is in one table. The data is stored by registration dateand includes county and number of students brokne out by grade.Any help appreciated!Rob
View 4 Replies
View Related
Oct 26, 2006
i encounter this error..
Cannot sort a row of size 8107, which is greater than the allowable maximum
of 8094.?
why this error occur? can someone explain? how to avoid this? thanks!!
View 1 Replies
View Related
Dec 10, 2007
We are using a modeling technique called Anchor Modeling in our data warehouses. You can read more about the technique itself at our homepage http://www.intellibis.se, where we have published a fact sheet and a recently held presentation (TDWI European conference). One of the features with this technique is its simple way to historize data. This is done by having a fromDate column which together with the surrogate key will yield a unique combination. On the tables that has this kind of historization we add a primary key, which in turn will create a clustered index, with the following specification (surrogateKey asc, fromDate desc). This will physically order data on the storage media according to the specificed columns and ordering. Now I move on to create a "latest view" of this table which does a subselect to find the latest version for every surrogateKey using max(fromDate). Should not the optimizer now figure out that data is ordered so that the latest version always comes first for every surrogateKey, hence any sorting would be unneccessary? If I look at the actual execution plan after running a query that uses the view there is a sort in the plan, but the cost is always 0%. Does this mean that it did not sort the data, or that it did call a sorting routine, but it actually took very little time to do the sorting? If so, is there a reason that is has to do the sorting or could it have been left out by an even smarter optimizer?
I would also like to applaud the people behind the optimizer, since it will figure out which tables are in fact necessary to query and eliminate others, even if I have left joined them into the view I am using. This speeds up performance and makes anchor modeling feasible. Unfortunately optimizers from other vendors seem to have trouble doing this...
Regards,
Lars
View 2 Replies
View Related
Mar 11, 2008
I've been racking my brain all day and I finally decided to ask for help. I've got two tables with rows from the first that need to be sorted by the second. The problem is that the rows don't always exist in the second table. I've tried various forms of INNER, LEFT, RIGHT, OUTER, LEFT OUTER, CROSS, etc., etc., etc. and nothing (oh yeah UNION too). Every time I get close, I lose the records that don't have matches.
Something close-
SELECT A.IDDoc, B.First
FROM A
LEFT JOIN B
ON A.IDDoc = B.IDDoc
WHERE B.Dept = 'A'
ORDER BY B.First
Example Data
Table A
IDDoc Document
---------------------------
1 1467.doc
2 8722.doc
3 A47F.doc
4 88DQ.doc
5 ABCD.doc
Table B
IDDoc Dept First
----------------------------
1 A John
2 A Bob
3 A Ralph
4 A Diane
Results I Want
IDDoc First
-------------------
5 NULL
2 Bob
4 Diane
1 John
3 Ralph
Any help is appreciated. If I've posted in the wrong forum, please feel free to direct me to a better one.
Thanks in advance!
Jim
View 3 Replies
View Related
Oct 12, 2006
SELECT
LEFT(CONVERT(CHAR(11),convert(datetime,task_date),109),3) + ' ' +
RIGHT(CONVERT(CHAR(11),convert(datetime,task_date),109),4) as Date,SUM(CASE a.status_id WHEN 1000 THEN b.act_point ELSE 0 END) as Programming,SUM(CASE a.status_id WHEN 1016 THEN b.act_point ELSE 0 END) as Design,SUM(CASE a.status_id WHEN 1752 THEN b.act_point ELSE 0 END) as Upload,SUM(CASE a.status_id WHEN 1032 THEN b.act_point ELSE 0 END) as Testing,SUM(CASE a.status_id WHEN 1128 THEN b.act_point ELSE 0 END) as Meeting,SUM(CASE a.status_id WHEN 1172 THEN b.act_point ELSE 0 END) as OthersFrom
task_table a,act_table b where a.status_id=b.act_id and
a.user_id=(select user_id from user_table where user_name='Raghu') and
a.task_date like '%/%/2006' GROUP BYLEFT(CONVERT(CHAR(11),convert(datetime,task_date),109),3) + ' ' + RIGHT(CONVERT(CHAR(11),convert(datetime,task_date),109),4)Output :Aug 2006 294 0 0 80 0 0 Jan 2006 14 0 0 0 0 0 Oct 2006 336 0 0 0 0 0 Sep 2006 3262 20 24 8 16 0 How to sort the date in ascending Order ?Jan 2006Aug 2006Sep 2006Oct 2006
View 2 Replies
View Related
Feb 27, 2008
I have: 4 tables and 1 table variable.
CCenters (ID, Name)
Campaigns (ID, Name)
Rel (ID, CCenterID, CampaignID) - [many to many]
and @SCampaigns (ID, CampaignID) - represents the selected campaigns by the user
performing the commands below I would get the centers associated with the campaigns selected.SELECT CCenterID
FROM Rel
INNER JOIN @Campaigns ON @SCampaigns.CampaignID = Rel.CampaignID
But what I really want are the common centers to the selected campaigns.
Thanks
View 1 Replies
View Related
Mar 18, 2004
I am trying to select a record from a table where it has the smallest priority
how would you go about doing this
is there a cool sort command or is there a select command syntax that can do this
thanks
View 3 Replies
View Related
Aug 31, 2005
I've made this example and it loads a picture into a database. (MsSql )Take a look at the code, it works just fine however it leaves a process in sleeping mode "avaiting command" in Enterprise manager under "Management/current Activity/Process Info"Is it supposed to be like this or is it supposed to be reemoved after .net is finished??Code snip_______________________________________________________
Dim conn As New SqlConnection("Data Source = (local);Initial Catalog = " & "test;User ID = NAME; Password=PASSWORD;")
Dim cmd As New SqlCommand("Select * from tab_bild", cnn)
Try
conn.Open()
Dim myDatareader As SqlDataReader
myDatareader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While (myDatareader.Read())
Response.ContentType = myDatareader.Item("PersonImageType")
Response.BinaryWrite(myDatareader.Item("PersonImage"))
Loop
conn.Close()
Response.Write("Picture info succesfully retrieved")
Catch SQLexc As SqlException
Response.Write("Read failed, Reason: " & SQLexc.ToString())
End Try
End Sub________________________________________________________________Please can someone explain this for me or sort this out for me.All help is welcome even if its only points me too a direction.RegardsTombola
View 3 Replies
View Related
Mar 29, 2001
When sorting records in a table how do you sort by the occurence of a field.
So, if the table contained: 1,1,2,2,2,3,3 how would you get it to sort using the desc syntax to give 2,2,2,3,3,1,1
View 2 Replies
View Related
Mar 29, 2001
When sorting records in a table how do you sort by the occurence of a field.
So, if the table contained: 1,1,2,2,2,3,3 how would you get it to sort using the desc syntax to give 2,2,2,3,3,1,1
View 1 Replies
View Related
Jul 20, 2000
Hi,
I am trying to restore .DAT file from dump. Its giving me error ..saying that the sort order id used for dumping was 42 not the default value 52.
How can i change the sort order to 42.
I am using sql server 6.5
Thanks
Srinivas
View 4 Replies
View Related
Jan 13, 2000
We have a vendor who insists that sql server 7 be set to a binary sort order. Is there any real advantage to this as opposed to a dictionary sort?
View 2 Replies
View Related
Sep 21, 2000
I have a table that most of the data has the same value, but there are only a few that do not match that value. I want to populate a listbox with all values from the table, but I'd like to have the majority listed first, followed by the others (the few that don't matach). What's the best way to approach this with SQL?
Thanks.
View 3 Replies
View Related
Sep 20, 2000
HOW CAN I CHECK THE SORT ORDER OF MY OLD SERVER?
HELP
View 1 Replies
View Related
Oct 5, 1999
Is there a query you can run against a 7.0 server to return the chracter set and sort order.
View 1 Replies
View Related
Oct 18, 1999
I'm trying to setup a duplicate of an old SQL Server 4.2 server to put in place while we upgrade the server, but I can't get the sort-order right. I know the existing server uses sort order id 40, but I can't find which sort-order that corresponds to during the install process. If anyone can give me a system table that lists all the sort orders names and id's, or can tell me what the text name for sort order 40 is, I would be very grateful.
Thanks,
Rob.
View 2 Replies
View Related
Jul 13, 2004
Hi All,
I have a table with 3 columns. Product, Location and Value. The data looks like this:
NULL NULL 100
Atlanta NULL 50
Atlanta Cookie1 30
Atlanta Cookie2 20
Dallas NULL 120
Dallas Cookie1 80
Dallas Cookie2 40
This table gets filled with a Groupby with Rollup option. The NULLS show subtotals/total. Is there a way to build a query that returns the results with NULLs at the bottom of each section like:
Atlanta Cookie1 30
Atlanta Cookie2 20
Atlanta NULL 50
Dallas Cookie1 80
Dallas Cookie2 40
Dallas NULL 120
NULL NULL 100
Thanks,
Shab
View 4 Replies
View Related
Jul 17, 1998
I need to copy the structure and data of an existing SQL 6.5 server to one with a different sort order. Normally, I would use the transfer tool to accomplish this, but the servers are on different networks. My question is, is BCP the answer? In other words, will the data copied via BCP from the sending server be able to be copied on the recieiving server. Also, is there a way to automatically generate the BCP statements for all tables? What I would really like is to be able to get at the scripts and data files created by the transfer tool.
View 1 Replies
View Related
Jul 9, 2001
How can I set the sort order to 42, nocase when I install sql server 6.5
does Setup gives you some option to check to set sort order ?
View 1 Replies
View Related