Getting Order Number Into Query Grouped By Something

Apr 30, 2008

I have a table of transaction that includes student ids and dates. I need to select all records from the table and include a new value that is the sequential transaction numbered for each student with the oldest transaction for each student being numbered one, the next oldest numbered two and so on. So the result should look like student1, 10/1/2000, 1, student1, 10/15/2000, 2, student1, 2/12/2001, 3, student2, 9/1/1999, 1, student2 10/2/2000, 2, student2 , 12/15/2000, 3, student2, 11/4/2001, 4 and so on.

View 8 Replies


ADVERTISEMENT

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

Sep 24, 2012

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

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

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

How shall I achieve this?

View 4 Replies View Related

How To Get Last Records In Grouped Query.

Jan 23, 2007

Hi,I want to create query where I could group records by quarters, and getthe last record in each group.e.gCreate Table MyTable(Value [float],date[datetime])Insert into MyTable (value, [date]) values (100, '1-1-2000')Insert into MyTable (value, [date]) values (110, '1-2-2000')Insert into MyTable (value, [date]) values (120, '1-3-2000')Insert into MyTable (value, [date]) values (130, '1-4-2000')Insert into MyTable (value, [date]) values (140, '1-5-2000')Insert into MyTable (value, [date]) values (150, '1-6-2000')Insert into MyTable (value, [date]) values (160, '1-7-2000')Now I would like to get this data grouped by quarter, and get the lastvalue from each quarter. So here I would like to get result like this(120, q1 -2000)(150, q2 -2000)(160, q3 -2000)I know how to create aggregate functions but I have problem with gettingthat last record from each group.*** Sent via Developersdex http://www.developersdex.com ***

View 2 Replies View Related

Want To Get The Order Number Of Each Record

Dec 22, 2006

I want to retrieve data from SQL server database table I also want to get the order number of each record also For example consider the following table I want to get one (1) associated with A, Two (2) associated with B Three (3) associated with E Name Mark A 10 B 9 E 10 How can I do this?
I want to retrieve data from SQL server database table
 
I  want to get the order number of each record also
 
For example   consider the following table 
 
I want to get one
 
Name          Mark
A                  10
B                   9
E                 10
 
(1) associated with A,
 
  Two (2) associated with B
Three (3) associated with E
 
 
 
 
 
How can I do this?
Please help me
 
 
 
hopefully
Sujithukvl

View 2 Replies View Related

Use Trigger To Number Each Order Line

Jan 24, 2006

I am wanting to set up a trigger on our SQL server 2000 to create a sequential order line number in the OrderDetails table for OrderID.

I will be inserting data from an OrderLinesAdd table into the OrderLines table but want the LineNumber field to be incremented by 1 for each group of orders grouped by OrderID that I insert into the table eg.

OrderID LineNumber
1 - 1
1 - 2
1 - 3
2 - 1
2 - 2
3 - 1
3 - 2

I have just started using SQL so am not sure how I go about writing the code for the trigger ? It would seem like I will need to use the Max function in the code.

Thanking you in advance.

View 3 Replies View Related

How To Select First Missing Number In Order

Feb 21, 2014

I am assigning temporary Ids in my table, and right now I am assigning new ones via find the MAX(Temp_Id), stripping out the number and adding one.

Since these are temporary I would like to be able to reuse older ones when they are no longer in the table.

For example I have:
ID0001
ID0002
ID0003
ID0006

My code right now will add ID0007. I would like to re-use ID0004 and ID0005 since they're no longer in use. How do I go about do this?

View 3 Replies View Related

Find Logic Flaw, Order Number Generator

Mar 15, 2000

This procedure has been returning duplicate numbers. (Tested with scripts that called this proc and put value in a table.)

How can it return duplicates? Does the transaction Begin/Commit not guarantee transactional consistency?


CREATE PROCEDURE sp_UpdateOrderNumber @customer int AS
DECLARE @NewOrderId int,
@nSQLError int,
@nRowCount int
BEGIN TRAN
UPDATE CUSTOMERS
SET ORDER_NUMBER=ORDER_NUMBER + 1
WHERE COMPANY_ID=@customer
SELECT@nSQLError = @@error,
@nRowCount = @@rowcount
If @nSQLError != 0 OR @nRowCount != 1 /* Check for Errors */
Begin
Rollback Tran
Return -999
End
SELECTORDER_NUMBER
FROMCUSTOMERS
WHERECOMPANY_ID=@customer
SELECT@nSQLError = @@error,
@nRowCount = @@rowcount
If @nSQLError != 0 OR @nRowCount != 1 /* Check for Errors */
Begin
Rollback Tran
Return -998
End
COMMIT TRAN

View 1 Replies View Related

SQL Server 2014 :: Order By Month Number In A Group By

Dec 19, 2014

Sample Data
SET NOCOUNT ON;
USE tempdb;
GO
CREATE TABLE CheckRegistry (
CheckNumber smallint,

[code]...

How can I get the result orderd by the month number?

View 3 Replies View Related

Create A View That Will Give Most Current Status (by Statusdatetime) Of Each Order Number

Jan 20, 2015

We are having trouble figuring out how to create a view for this scenario:

We have a status log table that holds an order number, statusdatetime, and statuscode. This table will have multiple status' for the same order number. I want to create a view that will give me the most current status (by statusdatetime) of each order number. This view would show: order number, statusdatetime, and statuscode.

Here is a sample of the data:

Order numberStatusDateTimeStatusCode
1234512/15/2014 15:00CREATE
1234512/15/2014 16:30CONFIRMED
4567812/16/2014 08:00CREATE
9876412/18/2014 12:00CREATE
9876412/19/2014 08:00CONFIRMED
4567812/17/2014 09:30CONFIRMED
4567812/19/2014 15:30IN-TRANSIT

So my view should result in :

Order numberStatusDateTimeStatusCode
1234512/15/2014 16:30CONFIRMED
9876412/19/2014 08:00CONFIRMED
4567812/19/2014 15:30IN-TRANSIT

View 4 Replies View Related

How To Query A Number (street Number)...

Jul 30, 2007

I have a table that has a street number field.
if the user types in a street number of '2' i would like to return all street numbers the begin with 2 (2,20,21, 200, 201,205,2009,...)
how can this be done.

View 10 Replies View Related

Grouped By Month

Jul 12, 2006

Dear All,

I'd like to write a query that lists items from a single table but groups the listed items by a date (data of item entered into the table)

So all items matching a criteria and were entered during March should be listed underneath one-another
Then all items matching the same criteria but entered during April should be grouped again.

Not sure what would be the right approach here.

I'm thinkning, creating a temp table putting data in there but altering the data enterd field into just year and month, and then group the result by that field?

Will this work?

View 1 Replies View Related

Get The Max() From Grouped Set With Varchar

Jan 16, 2008

I want to grab the Max footage in this query, there are two values for each group, so i should be able to get the bigger number. The only problem is, its in varchar format, so for some reason its only grabbing the ones with the highest number to the left. So instead of grabbing 12ft, it says 7ft is the max. What am i doing wrong. is there another way to go around this. This is supposed to be a subquery for a a much bigger query.



Code Block
SELECT MAX(Qry_Questions.Response) AS Max_Footage,
CONVERT(varchar, dbo.Qry_Questions.Date, 110) AS shortDate,
Qry_Sales_Group.salesperson_purchaser_code,
Qry_Questions.StoreName,
MIN(Qry_Questions.Response) as Min_Footage

FROM Qry_Questions

INNER JOIN Qry_Sales_Group

ON Qry_Questions.sales_person_code COLLATE SQL_Latin1_General_CP1_CI_AS = dbo.Qry_Sales_Group.SalesPerson_Purchaser_Code
INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Customer AS Customer

ON Customer.Customer_Code = dbo.Qry_Questions.Customer COLLATE SQL_Latin1_General_CP1_CI_AS
INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Customer_Category AS CusCat

ON CusCat.Customer_Category_Id = Customer.Customer_Category_Id

WHERE (dbo.Qry_Questions.[Question Code] IN ('SN017', 'SN015')) AND (CusCat.Customer_Category_Id = 6201)
GROUP BY CONVERT(varchar, dbo.Qry_Questions.Date, 110), Qry_Sales_Group.salesperson_purchaser_code, dbo.Qry_Questions.StoreName






This displays this:
Max Footage Date store name Min Footage
8ft 09-07-2007 12140 PETCO #1437 8ft
8ft 09-10-2007 12069 PETCO #698 8ft
8ft 09-11-2007 12106 PETCO #1916 8ft
8ft 09-11-2007 12108 PETCO #683 4ft
8ft 09-13-2007 12140 PETCO #918 12ft

View 5 Replies View Related

Order By Query

Jun 14, 2007

Hi, I am using below query: 
SELECT     tbh_Articles.ArticleID, tbh_Articles.AddedDate, tbh_Articles.AddedBy, tbh_Articles.CategoryID, tbh_Articles.Title, tbh_Articles.Abstract, tbh_Articles.Body,                       tbh_Articles.Country, tbh_Articles.State, tbh_Articles.City, tbh_Articles.ReleaseDate, tbh_Articles.ExpireDate, tbh_Articles.Approved, tbh_Articles.Listed,                       tbh_Articles.CommentsEnabled, tbh_Articles.OnlyForMembers, tbh_Articles.ViewCount, tbh_Articles.Votes, tbh_Articles.TotalRating,                       tbh_Articles.ImageURL, tbh_Articles.specialFROM         tbh_Lang CROSS JOIN                      tbh_ArticlesWHERE     (tbh_Lang.LangID = @LanguageID) AND (tbh_Articles.ArticleID = tbh_Lang.ArticleMain OR                      tbh_Articles.ArticleID = tbh_Lang.ArticleSecond1 OR                      tbh_Articles.ArticleID = tbh_Lang.ArticleSecond2 OR                      tbh_Articles.ArticleID = tbh_Lang.ArticleSecond3 OR                      tbh_Articles.ArticleID = tbh_Lang.ArticleSecond4 OR                      tbh_Articles.ArticleID = tbh_Lang.ArticleSecond5)
Problem is that I want to sort in a manner which the results returns as ArticleMain as the first column, ArticleSecond1 as the second and so on...
Tables structure:  tbh_Articles(id, title, body...) ; tbh_Lang(id,ArticleMain,ArticleSecond1 ,ArticleSecond2.... )
 Any suggestions?
 
 
 

View 9 Replies View Related

Order By Query

Sep 29, 2007

I have a Comment Table where a comment can have a reply, if the comment is replied to I want the reply to appear under the comment.


Based on the Fields CommentID and Parent ID the parentID is the Comment and the Comment with a ParentID set too that comment is the answer.


How do I build this Query?

View 7 Replies View Related

Display Grouped Records

Apr 11, 2008

I have the following sql table and would like to group the results by "StoryTitle" to display in a datalist. The Storytitle field in the datalist is a LabelID     StoryTitle       StoryAuthor      Rating     StoryID    Comments
1      About Me       goodyone            6          20           Great Story
2      About Me       goodyone            5          20           Love your work
3      Hello World    magicme             6          26           What a Story
4      Hello World    magicme             7          26           This Reminds me of...
I know i have to do something in the SQL Datasource statement. Not sure how to do it. here is my statement below
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:BrillConnectionString1 %>"
SelectCommand="SELECT * FROM [iaw.comments]">
</asp:SqlDataSource>
 

View 5 Replies View Related

Pains Of A Grouped Subquery

Feb 8, 2000

I have a query that will not run in Transact SQL:

SQL = "SELECT email
FROM Contacts
WHERE email = ANY (
SELECT email
FROM Contacts
GROUP BY email
HAVING COUNT(email) > 1)"


It is supposed to return all of the records that have duplicate email addresses (i.e. the subquery finds the duplicate addys and the main query finds all of the records with those emails.)

Help would be great.

View 2 Replies View Related

2 Grouped Counts On 1 Table

Oct 10, 2007

I am trying to get a count of a job received date and a job closed date from the same table. I need these counts to be grouped by which team they are for. This is what I have and it isn't working:

SELECT HEAT.dbo.Profile.PrimaryTeamName,
COUNT(CallLog1.RecvdDate) AS OpenCalls,
COUNT(CallLog2.ClosedDate) AS ClosedCalls
FROM HEAT.dbo.Profile,
HEAT.dbo.CallLog CallLog1,
HEAT.dbo.CallLog CallLog2
WHERE HEAT.dbo.Profile.CustID = CallLog1.CustID AND
HEAT.dbo.Profile.CustID = CallLog2.CustID AND
CallLog1.CallID = CallLog2.CallID AND
((HEAT.dbo.Profile.PrimarySupportGroupID = 'ATS') OR
(HEAT.dbo.Profile.PrimarySupportGroupID = 'ats'))
GROUP BY HEAT.dbo.Profile.PrimaryTeamName,
CallLog1.RecvdDate,
CallLog2.ClosedDate
HAVING (CallLog1.RecvdDate = CONVERT([VARCHAR](10), GETDATE(), 120)) OR
(CallLog2.ClosedDate = CONVERT([VARCHAR](10), GETDATE(), 120))

I can get both counts to work individually, but as soon as I try to get them to go together I get some very interesting returns. I am drawing a complete blank as to what to do. Any info would be very helpful.

Thanks

View 5 Replies View Related

Updating Grouped Rows...

Jul 9, 2004

I am new here, and I am sure this is a simple query, but im being forcefed database chores from my job, so i have to teach this stuff to myself/get help from places like this,
I need help with a query,
lets say that there are columns a,b,c,d,e,f,g
if columns c,d,e are the same, than I want the info in column g changed to the info in column b in the first record of that group
the reason I am doing this is,
I have like items (sku's) grouped in my database, and i want to create a blanket part number for skus that have matching descriptions which is the information in colums c,d,e,
I want to link them to the part number of the first product with that description, and add that part number in a new column at the end of the grouped SKU's record

this is what i start out with

a b c d e f g
2 4 5 6 9 8
2 5 5 6 9 9
2 7 5 6 0 5
1 2 3 4 5 6
1 3 3 4 5 7
1 4 3 4 5 8
1 5 3 4 5 9

i want to end up with
a b c d e f g
2 4 5 6 9 8 4
2 5 5 6 9 9 4
2 7 5 6 0 5 7
1 2 3 4 5 6 2
1 3 3 4 5 7 2
1 4 3 4 5 8 2
1 5 3 4 5 9 2

View 2 Replies View Related

Data Grouped By 20 Minutes?

Nov 28, 2005

Hi,I want to get the count of rows per each 20 minutes, is that possible?Is there a date function or any other function that I can use in Groupby clause, which will group the data of every 20 minutes and give methe count?Thank you.Vidya

View 3 Replies View Related

How To Obtain Just The Last Record Grouped By

Jul 20, 2005

Sorry for my englishI have a table that contains data of career about the person (staff)like this ...EMATREANIDEMEIDEGIIDecc. ..ecc. ..ecc. ..ecc. ..1199912312002123111200311000321999123120021231122003110003419991231200073115199912312001131161999123120021231162003110003719991231200212311whereEMATR is a not unique key (person ID)EANID, EMEID, EGIID (assembled) are the date of the last advance ofcareerI want extract from the table below only the actual position,therefore a view that return this rowsEMATREANIDEMEIDEGIIDecc. ..ecc. ..ecc. ..ecc. ..1200311000322003110003419991231200073115199912312001131162003110003719991231200212311I hope of to have been explainThank you from Maximiliano (italy)RE-Sorry for my english--Posted via Mailgate.ORG Server - http://www.Mailgate.ORG

View 1 Replies View Related

How To Match Grouped Rows In MS Sql

Apr 8, 2008

Hi,

Data in my table is loking like this.













InvID
ItemInputDtTime
SrNo
ItemId
Rate

Qty
GroupID

8252
07-04-2008 15:51
1
001138
9.99
1
1

8252
07-04-2008 15:51
2
000009
0.5
1
1

8252
07-04-2008 15:51
3
000016
1
1
1

8252
07-04-2008 15:52
4
000207
NULL
1
1

8252
07-04-2008 15:52
5
000203
NULL
1


1



8252


07-04-2008 15:52
6
001138
11.9
1
2

8252
07-04-2008 15:52
7
000016
1
1
2

8252
07-04-2008 15:52
8
000009
0.5
1
2

8252
07-04-2008 15:52
9
000207
NULL
1
2

8252
07-04-2008 15:52
10
000203
NULL
1
2

8252
07-04-2008 15:52
11
001138
11.9
1
3

8252
07-04-2008 15:52
12
000009
0.5
1
3

8252
07-04-2008 15:52
13
000008
0.5
1
3

8252
07-04-2008 15:53
14
001106
5
1
4

8252
07-04-2008 15:53
15
001000
10
1
5

8252
07-04-2008 15:54
16
001202
10
1
6

8252
07-04-2008 15:54
17
001117
13.9
1
7

8252
07-04-2008 15:54
18
001113
NULL
1
7

8252
07-04-2008 15:54
19
001117
13.9
1
8

8252
07-04-2008 15:54
20
001113
NULL
1
8

8252
07-04-2008 15:54
21
001117
13.9
1
9

8252
07-04-2008 15:54
22
001115
2
1
9




same colored items are grouped by GroupID. Each group contains ItemID, Qty and rate.
How can i compare IteamID, Qty and Rate of each group with other group's ItemID, Qty and rate?
OR
How can i get number of groups with same ItemID, Qty and rate?


All I need to do by T-SQL


Thanx

View 14 Replies View Related

Grouped Information From Two Tables

Sep 21, 2007



Hi,

I have two statements which when I join by a union statement give the folowing:

2005 11 0.000000
2005 12 0.000000
2006 1 0.000000
2006 1 50813.058500
2006 10 0.000000
2006 11 0.000000
2006 12 0.000000
2006 12 63224.511250
2006 2 0.000000
2006 2 59164.234500
2006 3 0.000000
2006 4 0.000000
2006 5 0.000000
2006 6 0.000000
2006 6 82442.570750
2006 7 0.000000
2006 7 61809.497750
2006 8 0.000000
2006 9 0.000000
2007 1 0.000000
2007 2 0.000000
2007 3 0.000000
2007 4 0.000000
2007 5 0.000000
2007 6 0.000000
2007 7 0.000000
2007 8 0.000000


What I want is to merge the values
2006 1 0.000000
2006 1 50813.058500

into one row, the months with zero figures are required.

Thanks

View 1 Replies View Related

Show All Grouped Rows

Aug 22, 2007

So i have a data table with a group in it.

I want a row for every item and i'ts count displayed. the problem is, if the count is 0, the row is not displayed.


how can i make all the rows show?

View 3 Replies View Related

Top 10 Chart Grouped By Month

Jan 19, 2007

Hello,

I have a bar chart that I need to show the top 10 items by Month. What I get currently is a chart by month with the total Top 10 Items (rather than the top 10 per month). I have tried adding a scope onto my Value expression but that didn't help.

=countDistinct(Fields!incident_ref.Value, "catGrpDate")

Please Help!

View 1 Replies View Related

SQL Query Or SP? Order Value Between Two Dates

Feb 7, 2008

Hi all,

Been having a good root around the forums and the site here and there's some real smart people on here, i'm hoping one or more of them can help me out. I'm expecting this to be a simple question for some of you, however it's way beyond me at this point!

Table Structure (abridged, relevant columns):

Orders:

Code:

[Orders](
[OrderID] [int] IDENTITY(1,1)
[OrderDateTime] [datetime]
[OrderSiteID] [nvarchar](255)
[OrderOffline] [bit]
[OrderSentToWP] [bit]
[OrderReceivedFromWP] [bit]
[OrderAuthorised] [bit]
[OrderCancelled] [bit]
[OrderApproved] [bit]
[OrderFraud] [bit]
[OrderDispatched] [bit]


OrderItems:

Code:

[OrderItems](
[OrderID] [int]
[ProductID] [nvarchar](255)
[Quantity] [int]
[Price] [real]
[Weight] [real]


Products:

Code:

[Products](
[ProductID] [uniqueidentifier]
[ProductCode] [nvarchar](255)
[ProductTitle] [nvarchar](255)



Product price is captured at time of order, so that reports aren't affected by discounts or promotions, and stored with the productid in orderitems.

I want to get a report between a set of dates and with certain flags set (see below example) and then get a list of unique products, quantity sold and sales values for that products. Results table would have 4 columns; ProductCode, ProductTitle, QuantitySold, Sales Value.

So far I have this:

Code:

SELECT Products.ProductCode, Products.ProductTitle, SUM(OrderItems.Quantity) AS QuantitySold
FROM Orders INNER JOIN
OrderItems ON Orders.OrderID = OrderItems.OrderID INNER JOIN
Products ON OrderItems.ProductID = Products.ProductID
WHERE (Orders.OrderDateTime BETWEEN '2007/01/01' AND '2007/12/31') AND
(Orders.OrderSentToWP = 1) AND (Orders.OrderReceivedFromWP = 1) AND (Orders.OrderAuthorised = 1) AND (Orders.OrderCancelled = 0) AND
(Orders.OrderDispatched = 1) AND (Orders.OrderApproved = 1) AND (Orders.OrderFraud = 0) AND Orders.OrderSiteID= 'someguid'
GROUP BY Products.ProductCode, Products.ProductTitle



Which gets my summed quantities, and I guess I could use ASP to multiply that by the current price, but that defeats the point of setting the database up properly in the first place! I know how to design data, i just don't know how to get it back out again

I could most likely just do the whole thing in ASP and get it to output the correct answer, so if it's impossible/very difficult to do it in pure SQL then I'll go that route. Ideal situation would be a stored proc or saved query that I can pass a start date, an end date and a siteid to and that will get me the answers I want!

Thanks in advance to anyone that looks at this for me.

Also, any recommended books/sites to learn this kind of query?

Richard

View 4 Replies View Related

Parsename Query Order

Jun 5, 2008

Greatful for any help....

Have the query below which is taking delimited address information from _Venue column. This works well apart from the order it is returned, for example, the output below has the address tittle displayed in a different column for each row

Queen Elizabeth's Hunting Lodge is in Address1
All Saints' Church is in Address2
Audley End House is in Address3

As I need to reference from the query the correct part of the address from the same location each time, is there anyway to get around this?

Thanks in advance


SELECT coalesce (PARSENAME(REPLACE(_Venue,',', '.'),4), '-') address1
,coalesce(PARSENAME(REPLACE(_Venue, ',', '.'),3), '-') address2
,coalesce(PARSENAME(REPLACE(_Venue, ',', '.'),2), '-') address3
,coalesce(PARSENAME(REPLACE(_Venue, ',', '.'),1), '-') address4
FROM table



Address1 Address2Address3Address4
----------------------------------------------------------------------------------------
Queen Elizabeth's Hunting LodgeRangers RoadChingfordLondon E4 7 QH
- All Saints' ChurchShrub End RoadColchester
---Audley End House

View 10 Replies View Related

How To Get Row From Select Query In Order

Jan 20, 2014

I have table called 'UserDetails'. If I execute below select query it should display in order of uno= 7,13,5 but i get in order of

uno=5,7,13.

How to get in order of uno= 7,13,5

Select EmailAddress,EmployeeName,UNo, MobileNumber
from UserDetails where (UNo=7 or UNo=13 or UNo=5 ) group by uno,emailaddress,employeename,uno,mobilenumber

Result I am getting as

EmailAddress EmployeeName UNo MobileNumber
-----------------------------------------------------------
aaa@xxx.com ravi 5 8989898989
bbb@xxx.comramesh 79898989898
ariv@gmail.com arivu 13 8989898989

View 3 Replies View Related

How To Get Order Values In Sql Query

Nov 24, 2006

Hi every body.
Can u tell me how to get the order values of the SQL query
Example.
My sqlstring ="Select * from tbl_Products"
And it returns 6 rows
And I want to get order values like this 1,2,3,4,5,6
I am a beginner.
Thanks a lots

View 1 Replies View Related

Slow Query When You Add An Order By

Feb 20, 2008

SELECT Column1,Column2,Column3 ....
FROM vwMyView
ORDER BY CreatedDT

View has about 10000 rows, If I remove order by query runs faster but adding an order by cause query to timeout..

All tables have clustered index based on the primary key of the table..

(a) Should I create an index view with CreatedDT as non clustered index?
(b) Or create a non clustered index on CreatedDT column on the underlying table?

I can provide DDL but if something obvious I am missing

Thanks

View 5 Replies View Related

SQL Query Help-- Order By Clause

Jul 20, 2005

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

View 7 Replies View Related

Order Of Conditions In A Query

Nov 6, 2006

I have a query with many (approximately, 30) conditions, such as:

select ....... from table1 join table2 on ( (table1.field1 = table2.field1 OR table1.filed1 IS NULL) AND (table1.field2 = table2.field2 OR table1.filed2 IS NULL) )

My question is:

In C++ or C#, when I write a condition like this, say, in an IF or WHILE, I know that I would be better off specifying the IS NULL (well, == null, to be precise) first, and use | instead of ||. In that case, the first condition (equality to null) is checked first, it's fast, and if it's not satisfied, the control flow goes to the next statement.

The question is, is there the same rule in T-SQL?

I mean, if I put the "... IS NULL" first, and then "OR ... = ...", will the query run faster than if I write it the other way around (that is, "... = ... OR ... IS NULL")?

This is very important to me, because most of those fields are VARCHAR, and due to some business rules, I can't change them to numerics etc, which would be compared much faster than text. So, even if I use full text search, I still need to find a way to optimize the query for performance...

By the way, I know that I can put those conditions in the WHERE clause, but as far as I know it won't make much of a difference for performance. So, my question is primarily about the order of conditions, in which SQL Server constructs its query plan.

[Edited:] In other words, what runs faster: comparing varchar to null or comparing varchars? And does it make a difference if I switch their places in my sql script?

We are using SQL Server 2000 SP4, Standard Edition. [Dev edition on the dev machine.]

Could someone kindly advise me on this, please?

Thank you ever so much.

View 4 Replies View Related

Select Into Parameters Grouped Data

May 20, 2007

Hi all,

This is probably one of the easier questions you get, but I have brain freeze and just can't do it and very rusty.

How can i assign the the values from sql below into variables e.g I want to get all new, pending and cancelled Leads from the rows returned which will come from the status id.


SELECT Count (leadStatusId) As NoOfLeads, leadStatusID, sum(value) As Value
FROM [dbo].[tLead] L
Inner Join dbo.tLeadStatus S on linkLeadStatus = LeadStatusID
Inner Join dbo.tClick C on linkClick = ClickID
WHERE L.DateDeleted Is NULL AND linkAffiliateUser = @UserID AND Month(L.DateCreated) = @month And Year (L.DateCreated) = @Year
Group by LeadStatusID
Order by LeadStatusID asc

Cheers

View 10 Replies View Related

Querying For Calendar, Grouped By Hour?

Jul 20, 2005

I've been scratching my head on this for quite awhile and it has me stumped.I hope to define a query which I can use to fill a "day planner" type ofcalendar. Although I've see a lot of these, only one has had what I thinkis a really nice feature - it collected into groups all events thatoverlapped into contiguous blocks of time. The net result of this is thatit becomes possible to output a calendar (html table) that is much lesscluttered. So I want to use this same idea for my own little project.The trick is that events may (or may not) start and end such that theyoverlap (completely or only at one end). I only am concerned with events ona given day.My "events" table contains eventtitle, date,starthour and endhour. Hoursare numbered from "0" to "23". I also have a lookup table of the "hours ofthe day" with which I did a JOIN to include the "missing" hours (where therewere no events - making a query that returned events for each hour and nullsfor each hour that had no event scheduled for it. But this makes too many"blank" rows, which is part of the clutter to which I referred.I've been able to construct queries that work in some cases, but not all.I've reread my copy of Celko's SQL For Smarties and came close, but nocigar. Where he discusses hotels and room-nights is part of the solution Ineeded, but my need goes beyond that quite a bit.Basically, I need to calculate one or more "spans" that contain contiguousgroups of start/end times. By knowing the number of hours spanned, I canthen use that for a <TD rowspan='n'> to collect my data like I want.I seem to keep hitting all around the solution. Maybe there isn't one (thatis purely a SQL solution). Or maybe I'm just looking at the problem thewrong way.So I thought I'd see if anyone here might point me in the right (or at least"new") direction. I've been looking at this for so long, I'm probablyoverlooking some simple and obvious trick to do this. Or maybe I'll getlucky and someone has seen or done exactly this already and can provide asolution?Incidentally, I've avoided utilizing a stored procedure or making a numberof temp tables to collect intermediate results, as I might need to port thisto a "dumb" database that does not provide such facilities. Maybe that'simpractical?thanks in advance,--

View 3 Replies View Related







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