I would like to know which of the following query is the fastest:
select * from customers C
where exists (select 0 from ORDERS O
where C.Name like 'A%' and O.Charged = 1 and O.Customers_Id = C.Id)
select * from customers C
where exists (select 0 from ORDERS O
where O.Charged = 1 and O.Customers_Id = C.Id) and C.Name like 'A%'
Because the condition C.Name like 'A%' is inside the sub query, I'm wondering if it will be evaluated for each record of the Orders table. Does anyone know if there is a difference of efficiency when this condition is inside or outside the sub query ?
I would like to know which of the following query is the fastest:
select * from customers C where exists (select 0 from ORDERS O where C.Name like 'A%' and O.Charged = 1)
select * from customers C where exists (select 0 from ORDERS O where O.Charged = 1) and C.Name like 'A%'
I don't want to use a JOIN clause. I just want to know if there is a difference of efficiency when the condition on C.Name is inside or outside the sub query.
Hallo everbody, I'm having a serious problem with my aspx pages. I developed few pages that allow users to retrieve books information from a database (MS SQL). The database table contains about 5000 records. My queries are very simple, nevertheless the time necessary to perform them is extremely long. I tried to set the time out of the data adapter to 0 and I removed the debug mode (debug="true") from the web.config file. I'm still not able to perform a query. What is wrong with it? Is it something related with the database?
Hi to everyone! I've just started to learn MS SQL Server 2005 and I hope you can give me some advices about what is the best design for the max performances between the two cases:
Case 1: Single table, but not very scalable Table name: GS salary_id (primary key, int) salary_description (varchar) salary_cumulative_1 (int) salary_cumulative_2 (int) .. salary_cumulative_9 (int)
Case 2: Two tables, this removes the limit of having only 9 salary_cumulative field, but will be performance worst? Keep in mind that this table(s) will be queried a lot the whole times when the user use the application.
I've written this stored proc, which have to collect records in one table in several databases. These tables contains very few records (1 to 10 max). In SQL Server standard edition, this stored proc is executed instantaneously. But in the Express, it could take 1 minute.
Is there a solution to this problem ?
Thanks in advance,
Best regards,
Guy
ALTER procedure [dbo].[SP_CHECK_USERS]
AS
select 'FIDUCIAIRE' as code,moment,nom,machine from MERCATORFIDUCIAIRE.dbo.sessions s1 where (s1.inactif=0) and (s1.nom<>'MercatorIshop')
union select 'TEST1 ' as code,moment,nom,machine from MERCATORTEST1.dbo.sessions s2 where (s2.inactif=0) and (s2.nom<>'MercatorIshop')
union select 'TEST10 ' as code,moment,nom,machine from MERCATORTEST10.dbo.sessions s3 where (s3.inactif=0) and (s3.nom<>'MercatorIshop')
union select 'TEST11 ' as code,moment,nom,machine from MERCATORTEST11.dbo.sessions s4 where (s4.inactif=0) and (s4.nom<>'MercatorIshop')
union select 'TEST12 ' as code,moment,nom,machine from MERCATORTEST12.dbo.sessions s5 where (s5.inactif=0) and (s5.nom<>'MercatorIshop')
union select 'TEST13 ' as code,moment,nom,machine from MERCATORTEST13.dbo.sessions s6 where (s6.inactif=0) and (s6.nom<>'MercatorIshop')
union select 'TEST14 ' as code,moment,nom,machine from MERCATORTEST14.dbo.sessions s7 where (s7.inactif=0) and (s7.nom<>'MercatorIshop')
union select 'TEST15 ' as code,moment,nom,machine from MERCATORTEST15.dbo.sessions s8 where (s8.inactif=0) and (s8.nom<>'MercatorIshop')
union select 'TEST16 ' as code,moment,nom,machine from MERCATORTEST16.dbo.sessions s9 where (s9.inactif=0) and (s9.nom<>'MercatorIshop')
union select 'TEST17 ' as code,moment,nom,machine from MERCATORTEST17.dbo.sessions s10 where (s10.inactif=0) and (s10.nom<>'MercatorIshop')
union select 'TEST18 ' as code,moment,nom,machine from MERCATORTEST18.dbo.sessions s11 where (s11.inactif=0) and (s11.nom<>'MercatorIshop')
union select 'TEST2 ' as code,moment,nom,machine from MERCATORTEST2.dbo.sessions s12 where (s12.inactif=0) and (s12.nom<>'MercatorIshop')
union select 'TEST20 ' as code,moment,nom,machine from MERCATORTEST20.dbo.sessions s13 where (s13.inactif=0) and (s13.nom<>'MercatorIshop')
union select 'TEST21 ' as code,moment,nom,machine from MERCATORTEST21.dbo.sessions s14 where (s14.inactif=0) and (s14.nom<>'MercatorIshop')
union select 'TEST23 ' as code,moment,nom,machine from MERCATORTEST23.dbo.sessions s15 where (s15.inactif=0) and (s15.nom<>'MercatorIshop')
union select 'TEST3 ' as code,moment,nom,machine from MERCATORTEST3.dbo.sessions s16 where (s16.inactif=0) and (s16.nom<>'MercatorIshop')
union select 'TEST4 ' as code,moment,nom,machine from MERCATORTEST4.dbo.sessions s17 where (s17.inactif=0) and (s17.nom<>'MercatorIshop')
union select 'TEST5 ' as code,moment,nom,machine from MERCATORTEST5.dbo.sessions s18 where (s18.inactif=0) and (s18.nom<>'MercatorIshop')
union select 'TEST6 ' as code,moment,nom,machine from MERCATORTEST6.dbo.sessions s19 where (s19.inactif=0) and (s19.nom<>'MercatorIshop')
union select 'TEST7 ' as code,moment,nom,machine from MERCATORTEST7.dbo.sessions s20 where (s20.inactif=0) and (s20.nom<>'MercatorIshop')
union select 'TEST8 ' as code,moment,nom,machine from MERCATORTEST8.dbo.sessions s21 where (s21.inactif=0) and (s21.nom<>'MercatorIshop')
union select 'TEST9 ' as code,moment,nom,machine from MERCATORTEST9.dbo.sessions s22 where (s22.inactif=0) and (s22.nom<>'MercatorIshop')
I am coding under Delphi a software which will be using a SQL Server 2000. I am using ADO components and have the latest MDAC: 2.8 SP1.
The software is using a lot of TADOQuery objects which are connected to the same TADOConnection. The TADOQuery having for options : - cursorlocation : useclient - cursortype : static - locktype : optimistic
On the first use of a TADOQuery in order to execute any type of request, the processing is fast. If I am using this same object for others requests, everything is fine and as fast as the first request. But as soon as I am using another TADOQuery, performances are going down.
In order to give some numbers, some requests can take as much as 17 seconds to be executed. The same request would take at most 100 milliseconds if it were executed with the first TADOQuery.
It is not a problem concerning indexes; if I try to use the request analyzer, all my requests are processed quickly.
I used the SQL Profiler to see the details and saw some interesting things : the first uses of TADOQuery are of type SQL:BatchCompleted but switching to another TADOquery make it use another type : RPC:Completed. Contents of this RPC can be a declaration or an execution of cursor.
More precisely, if I am using only one ADOQuery, I see one line in the Profiler for every block of code opening/reading contents/closing. But using multiples ADOQuery, I see one declaration of cursor for the opening and then every reading produces one cursorfetch. So, this declaration of cursor may take a long of time and every fetch too and if there is many lines to send to the client, the network is used for each line to send.
Better, using an TADOQuery to make a request and then simply initializing another one by changing the SQL property and then executing a second time the first TADOQuery makes this last execution used as a cursor serverside. The problem should then on the side of the client but I can not figure where.
I hope having been as clear as needed ! My wishes is to not have recode the whole database side of our software because it is huge and badly designed so it will be hard to test everything fine. So before recoding I wish to continue the analysis.
So does anyone knows why is happening this serverside thing ? And is there a simple way to make it not happen ?
Table #1 SELECT EID, DATEPART(wk,[Date]) AS Week, MAX([Date]) AS WeekEnding FROM Employee_Hours WHERE ([Date] Between '1/1/04' AND '12/31/04') GROUP BY EID, DATEPART(wk,[Date]) HAVING MAX([Date]) = '1/24/04' --Pay period
Table #2 SELECT EID, DisplayName FROM Employee WHERE (Active=1)
I tried subqueries and temp tables but can't get the results I need. The first query will return the employees who entered their time for the given pay period.
I have the following sql statement: INSERT INTO prg_lvl VALUES ( 'Data Recovery', 'Data Recovery', 7, 'ENG', 0, 16, 'Menu=w_data_recovery_stk;', ( select max(menu_id) + 1 from prg_lvl ), 'K'); that works for Sybase and I wanna make it works for SQL Server.
The problem is the use ot the subquery (select max(menu_id) + 1 from prg_lvl).
Could I use subqueries in SQL Server in general or is there is any other method to overcome this problem
I am very new to SQL Server, working with it in class. I am trying to do procedures involving subqueries using the Northwind database, and am having a rough time.
For instance, I have the following code, which lists all orders for the month of November, 1996:
SELECT Customers.CustomerID, Customers.CompanyName, CAST(Orders.OrderDate AS CHAR (11) )AS OrderDate FROM Customers, Orders WHERE Customers.CustomerID = Orders.CustomerID AND OrderDate BETWEEN '11/1/1996' AND '11/30/1996' ;
I have been asked to do the same thing, but using a subquery. I came up with the following:
SELECT CustomerID, CompanyName FROM Customers a WHERE EXISTS (SELECT OrderDate FROM Orders b WHERE a.CustomerID = b.CustomerID AND OrderDate BETWEEN '11/1/1996' AND '11/30/1996' ) ;
However, it does not list the Order Date, as I want it to, and the information is not correct (it is missing a few orders from November '97 that should show up. Can someone tell me what I am doing incorrectly?
Please note that I do not need anyone to give me the code, but simply give me an idea of what I am doing incorrectly, or let me know how it can be done, so that I may do it. =-)
Hi all,I've seen mention that you can use nested subqueries down to as manylevels as you like but whenever I run the following:select * from table1where tab1ID in(select tab1ID from table2 where tab2ID in(select tab2ID from Table3 where Tab3ID=N))I get the error "incorrect syntax near the keyword 'where'"Can anyone confirm that sub-subqueries are possible? If so is thesyntax I'm using correct?I'm running SQL 2000 through a Delphi 5 app.RegardsJon
Guys,Got this query...---------------------------SELECT TOP 5 Tbl_admin_hotels.HotelName,(SELECT COUNT(Tbl_marketing_history.HotelID)FROM Tbl_marketing_historyWHERE Tbl_marketing_history.HotelID = Tbl_admin_hotels.HotelID)AS CountTotal,(SELECT MAX(DateSent)FROM Tbl_marketing_historyWHERE Tbl_marketing_history.HotelID = Tbl_admin_hotels.HotelID)AS LastSentFROM Tbl_admin_hotelsWHERE NOT Tbl_admin_hotels.HotelID = 99ORDER BY CountTotal DESC---------------------------Within the table Tbl_marketing_history there is also a 'Subject' column thatI require, the row to grab this Subject column from should relate to the rowI'm selecting in the SubQuery to grab 'DateSent'.I've tried and tried to grab multiple columns but failed miserably? Cananyone help pleaseeee!Cheers, Ash
In this stored procedure, I want to grab all the information for Sales Representatives that made less then 6 visits. I have done that in the subquery. But I also want to be able to display their visits by Dates where any number of visits was made. Meaning, i want to be able to show Everyday where a visit was made, but i only want the records that are less then 6 visits. So I want nulls to show up for the dates where no visits were made. So I can track the people that didnt make visits, on days other made visits (which means they should have visits too)
So basically my report looks like this: 09-10-2007 09-11-2007 09-14-2007 Tom Smith 1 3 4 Janice Cooper 3 5 5 Troy Slater 5 4 2 Kelly Short 4 4 4
When i want it to look like this:
09-10-2007 09-11-2007 09-12-2007 09-13-2007 09-14-2007 Tom Smith 1 3 null null 4 Janice Cooper 3 5 null null 5 Troy Slater 5 4 null null 2 Kelly Short 4 4 null null 4
Its an exception report, so i want to show what was not done , on days that are supposed to have things done, i cant show this, if dates are not displayed before there were no visits less then 6. I want to display all relevant dates, where any number of visits was mad. But only show the visits that were less then 6.
Here's my stored procedure that already has the less then 6 visits showing. But doesnt always show the dates. What should i do?
Hey everyone, I'm running into an issue where I have a select statement that retrieves all employee records from a employee table. In this statement I'm displaying first and last name, titlte and the employees manager id(which is the employees id). What I want is a query that instead of displaying the manager's id, display the manager's name. The query that I'm using below doesn't work. I was hoping that someone could help me out: SELECT LastName, FirstName, Title, Extension, (SELECT FirstName, LastName FROM Employees WHERE (ReportsTo = EmployeeID)) AS Reports FROM Employees
Here's the data that I'm using: LastName, First Name Title Extension Reprots To
Davolio Nancy Sales Representative 5467 13
Fuller Andrew Vice President, Sales 3457 0
Leverling Janet Sales Representative 3355 12
When I run this query I get a error saying "Only one expression can be specified in the select list when the subquery is not introduced with Exists"
So I already no this can't be done... but I need a suitable alternative (if one exists) so I don't have to competely re-write this already too huge query. Anyways, in my select I have something like this: sum( case when code in (1,2,3,4) then 0 else 1 end ) as total which has now increase from four static values to a more dynamic format, that being a table with 47 values which may shrink or grow over time. Attempting the following fails: sum( case when code in (select code_id from ExcludedCodes) then 0 else 1 end ) as total because apparently you can't use selects or aggregates within an aggregate. So any ideas on how I can get this working... is there no Array or List type variable I could just substitute in? I've already tried using a Table Variable, but that failed as well. Please keep in mind, this is one line of a very large select containing many other fields and aggregates (on a fair amount of joins) which is used in at least four differerent reporting queries. If there is no quick and easy replacement trick I can do just let me know so I can start re-writing all of them (which is seriously going to make my head hurt).
Hi, I have searched through this forum and haven't found the answer to a problem I am having so I figured I will post it.
My SQL statement:
Select * FROM tblData WHERE LastName= (SELECT tblData.LastName FROM tblData GROUP BY tblData.LastName HAVING (Count(tblData.LastName)>1))"
What I am trying to do: I am trying to make an SQL filter that I can apply to my form in order to only show records with duplicate last names. The sub query returns names that are already in the table. I then compare what is found to be duplicate with the original table in order to just show only the duplicate records. Everything works fine as long as there is only one name thats duplicated.
When there are multiple duplicate names then I run into an error.
When the statement is put into a string and executed in VBA I get this error:
"Run-time error '3021': No current record."
When the statement is put into a query and run against the DB I get this error:
"At most one record can be returned by this subquery"
So yeah, any help would be greatly appreciated. Am I going about this all wrong or am I just forgetting something? Thanks for any help.
I have tried this insert comand and it errors out telling me that icannot use subqueries this way. INSERT INTO tblPartLocation(PartLocation, Part)VALUES (999,(SELECT PartID FROM tblParts WHEREPartName = 'test'))how would i insert a value from a query?thanks for any help
I need to build a view that has 4+ columns that are "counts" of relationships with other tables.
for example:
Code Snippet select Name, Description, (select count(*) from PetOwner PO where PO.OwnerId = O.Id) as PetCount from O Owner
I need to add a few more counts to this query, but I'm thinking that is a bad idea since the number of joins is going to get out of control if I need more counts.
I've created a view with all the counts and it works fine.
I want to index the view so the counts aren't calculated everytime the query is run, but I can't index if I use a subquery like this.
In the end I want the result set to have these columns.
I have a table with two columns: OID and Cumulative (witch is the same type as OID) Each OID can have one or more Cumulatives.
Example of data: OID Cumulative 167 292 167 294 167 296 168 292 169 302 169 304
The cumulation of each OID don't stop at one cumulation, but can be endless (theoretical). Example: 167->292->590 So the table would have on more row: OID Cumulative 295 505
I would like to represent this strucuture in a tree view and I'm looking for a query that could give me a table with this structure: OID Cumul1 Cumul2 Cuml3 Cuml4 .... Cumuln in the way I can read the row and have as many child nodes as I have values in the columns. The number of columns depends on the row with most cumulations.
How can I do the query? Is there a better way as my table with n columns?
Dear experts, Recently i got an error msg looks like this: you cannot use subqueries within a sqldatadpter except the subquery is introduced with EXISTS. Well, actually i was using IN. I know I can revise my query sting to use INNER JOIN or such stuff just to remove the nested queries. But i'm realllllly curious why it's not allowed?? Really appreciate it if some expert can tell me. Thanks in advance
Hi what i like to do is insert in one table 2 value from 2 different row. exp: table1: person id name 1 bob 2 john so id like to make an insert that will result in this table 2: person_knowed idperson1: 1 idperson2: 2 so the wuery should look something like this:
insert into person_knowed(idperson1, idperson2)(select id from personwhere name = 'bob',select id from personwhere name = 'john')); anybody have an idea of how to acheive this?
Hello, How can I do something like: Insert Into Displayed(snpshot_id, user_id, user_domain, ddisplay, iWidth, iHeight, disp_size, disp_format, watermark, frc_update, creditcost) Values ((Select snpsht_id from SiteIndex Where user_domain like '%domain'), 1000, (Select domain_id from UserDomains Where user_domain like 'domain'), GetDate(), 480, 360, 2, 1, 1, 0, 3) Im getting an error: Subqueries are not allowed in this context. Only scalar expressions are allowed.
I wonder if somebody could give me advice on SQL Server7-specific handling of subqueries and backreferences...
What is a) more efficient, and b) faster:
1. IF (DATEDIFF(minute, ( SELECT tLastHitTime FROM ( SELECT * FROM tblSession WHERE tSessionID = 'abcd1234' ) as sess), getDate()) < 30) SELECT * FROM sess
or:
2. IF (DATEDIFF(minute, ( SELECT tLastHitTime FROM tblSession WHERE tSessionID = 'abcd1234' ) as sess), getDate()) < 30) SELECT * FROM tblSession WHERE tSessionID = 'abcd1234'
In the first example, 2 SELECT statements (line 2 & line 8) refer to derived table by its alias 'sess'. In the 2nd example, both queries are independant, yet identical...
I wonder if SQLServer is "smart" enough to execute identical queries only once, and then reuse the resulset (e.g. derived table), or it requires explicit references (such as alias) in order to do so...
i have a problem, i have a query which does a search based on a parameter, thing is i want to order them according to how relevant the results are such as 5 for beingan exact match, 0 for being no match. using a series of liek statements.
so that the most relevnat results are displayed at the top.
how do i achieve this - im a bit confused about this.
hi there, I have a query that works on sybase and want to make it also works on SQL Server. The problem is that in this query I 'm using a subquery in an aggregate function. It seems that SQL Server unlike Sybase doesn't support the use of subquery in aggregate function. How can I overcome this problem.
To make a long story short, I'm trying to correlate the most inner query (two levels deep) with the most outer one, and it just doesn't work. Is it because the correlation must be back-to-back, without any levels that stand before the two?
If you have no idea what I'm talking about, below is the query that does work, but doesn't produce the right results ("QUOTES" gives the same number for all records):
---------------
select printersGlobal.company, (select count(*) from (select subBidding.bid_company from bidding as subBidding where subBidding.bid_company = 'Printing Company 1' group by subBidding.bid_company, subBidding.project) group by subBidding.bid_company) as QUOTES,
count(date_picked) as wins
from printers as printersGlobal
left outer join bidding as biddingGlobal on printersGlobal.company = biddingGlobal.bid_company group by printersGlobal.company order by printersGlobal.company asc
----------------------
When I replace 'Printing Company 1' with printersGlobal.company (to correlate and produce dynamic and correct results), I get errors.
I would appreciate if anybody can point me in the right direction.
Hopefully someone can suggest a better solution than what I'm currently hobbling along with.
Basically, I've got a table that gets rows inserted (with a timestamp) whenever there is a change to one of the values of a particular "item". So, what I want is to return a dataset of the latest values of each particular item.
I'm guessing that what I'm trying to acheive is doable in some elegant and performant fashion. Something maybe involving a ROLLUP or WITH CUBE or some FANCY item.
But for the time being, I've got a less-elegant query that returns the correct data, just using subqueries.
-- JUST DISPLAY THE TABLE FOR EXAMPLE SELECT * FROM @actionHistoryTable
-- THIS ROLLS-UP THE LATEST VALUE FOR EACH ACTION_TYPE FOR EACH ITEMID SELECT aht.itemID ,( SELECT TOP 1 aht2.actionValue FROM @actionHistoryTable aht2 WHERE aht.itemID = aht2.itemID AND aht2.actionType = '1' ORDER BY aht2.actionTime DESC ) as 'latest type 1 value' ,( SELECT TOP 1 aht2.actionValue FROM @actionHistoryTable aht2 WHERE aht.itemID = aht2.itemID AND aht2.actionType = '2' ORDER BY aht2.actionTime DESC ) as 'latest type 2 value' ,( SELECT TOP 1 aht2.actionValue FROM @actionHistoryTable aht2 WHERE aht.itemID = aht2.itemID AND aht2.actionType = '3' ORDER BY aht2.actionTime DESC ) as 'latest type 3 value' FROM @actionHistoryTable aht GROUP BY aht.itemID
I have an existing query, which runs pretty good. However, I need to create a new report, in which I would require to alter the existing query to return two values from each of the subqueries back to the main query.
The following is the current query:
SELECT tbLogTimeValues.DateTimeStamp as DateTimeStamp ,tbLogTimeValues.FloatVALUE AS Value FROM tbLogTimeValues
[Code] ....
Need putting together a query that returns two values from the first sub query (DateTimeStampTemperature and ValueTemperature) and from the second query return (DateTimeStampHumidity and ValueHumidity).
I would simply have to change the Path LIKE '%' + 'Temperature Interval%' within the humidity subquery to read:
Path LIKE '%' + 'Humidity Interval%'
Obviously, I would like to keep the DateTimeStamp comparisons as part of the main query, as the customer has access to this via parameters, and should be the same for both subqueries.
Inserting info into a table, where one of the columns meets a certain criteria.
insert into employee (/*emp_id,*/ fname, lname, start_date, dept_id, title, assigned_branch_id) values (/*null,*/ 'Michael', 'Smith', '2001-06-22', (select dept_id from department where name = 'Administration'), 'President', (select branch_id from branch where name = 'Headquarters'));
But I'm getting this error:
Msg 1046, Level 15, State 1, Line 5 Subqueries are not allowed in this context. Only scalar expressions are allowed.
right now am using sub queries for the below query.. but is this a good way or do i need to use joins.. however if you see the "downloads" column i need to get a count of how many download does each user did on the files/url.
SELECT UU_Title as Title, FileName_Url = (Case When UU_Type = 'U' Then UU_url else UU_Filename End), UU_UserID as UserID, B.User_FirstName + ' ' + B.User_LastName AS Author, UU_TimeStamp as DateCreated, UU_LastModified as DateModified, Downloads = (select count(*) from Vportaldevstats.[dbo].stats_download A where A.stat_AuID = UU_AssocAuID ), Presentation_Associations = (Select Presentation_Association = (Case When au_subject is Null or au_subject != '' then au_title else au_title end) from VPortalDev.[dbo].au A where a.Au_id = UU_AssocAuID), Community_Associations = (Select community_Association = (Case When au_subject is Null or au_subject != '' then au_title else au_title end) from VPortalDev.[dbo].au A where a.Au_id = UU_AssocCommunityID) From Vportaldev.[dbo].user_upload A , Vportaldev.[dbo].[User] B Where A.UU_UserID = B.User_ID Order by UU_LastModified Desc
and i tried re-modifying the above query as joins.. just wanna know is this the best way to do it. (and i don't know how to handle count(*) downloads .. pls.help.
SELECT UU_Title as Title, FileName_Url = (Case When UU_Type = 'U' Then UU_url else UU_Filename End), UU_UserID as UserID, B.User_FirstName + ' ' + B.User_LastName AS Author, UU_TimeStamp as DateCreated, UU_LastModified as DateModified, COUNT(*)
from Vportaldev.[dbo].user_upload uu Innerjoin Vportaldev.[dbo].[user] u ON UU.UU_USERID = U.USER_ID INNERJOIN Vportaldevstats.[dbo].stats_download SD ON UU.UU_ASSOCAUID = SD.STAT_AUID INNERJOIN VPortalDev.[dbo].au AU ON AU.Au_id = UU.UU_ASSOCAUID
Hi,Trying to get a grip on the "join" thing :)Up until now, I allways used this kinda method:"(select t1.a from t1 where t1.b in (select t2.ab from t2 where t2.b=0))"How can this be accomplished using joins? And if you have the time pleaseexplain the "bits" :)Thank you.--?TH
This works, but it's highly unefficient and generates a lot of IO. Is there another way to do it without the use of temp tables?
Code Block select eh.* from Equipment_History eh where Equipment_History_ID in (select top 2 Equipment_History_ID from Equipment_History eh1 where Equipment_ID in (select Equipment_ID from Equipment_History eh2 where Equipment_History_ID in (select min(Equipment_History_ID) from Equipment_History eh3 where eh2.Equipment_ID = eh3.Equipment_ID and eh2.Equipment_Status_Type in (1,2,3))) and eh1.Equipment_ID = eh.Equipment_ID order by Equipment_History_ID)
Equipment_History_ID is PK
Let me know what other information would be useful, I can barely understand my logic from looking at the code but it does in fact work.
Hi all, Recently saw some posts about how bad it is using subqueries (nested queries) and things like all the queries can be written with JOIN instead. However, for a query like the followings, I cannot figure out how to do it properly.
The data looks like the following, it contains 3 columns, id, which is the primary key of the table (unique), group, as which group this entry belongs to, and the article type, where 0 is not an article.
What the query is trying to achieve is for each group, get the latest (maximum) id, and the article type (bear in mind "0" is not one of the allowed type). so for data above, the result will look something like this...
id grp article 5 1 2 9 2 1 18 3 1
The following is the query I come up with, the problem is, I don't know how to get the same result without using subquery. I don't even see how it is possible. Guys, please share some light with me, and educate me on this.
select a.id, a.grp, b.article from ( SELECT max(id) as id, grp from list a where article != 0 group by grp ) a join list b on a.id = b.id