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.
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)
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 ***
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
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.
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.
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
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.
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.
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?
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
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?
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>
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.)
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.
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
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
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
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?
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.
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!
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?
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?
Address1 Address2Address3Address4 ---------------------------------------------------------------------------------------- Queen Elizabeth's Hunting LodgeRangers RoadChingfordLondon E4 7 QH - All Saints' ChurchShrub End RoadColchester ---Audley End House
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
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
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
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
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.]
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
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,--