Joins Or Subqueries - Confused

Mar 25, 2008

Hi all,

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


any help is much appreciated.

View 6 Replies


ADVERTISEMENT

Howto Use Joins Instead Of Subqueries?

Jul 20, 2005

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

View 3 Replies View Related

Confused Joins

Mar 21, 2007

I am using this query to create a single transactions from data that is distributed over several databases. So essentially i have created several variable tables and now I have to join them together.
So what I wanted to have happen was display all rows from temptalbel and then join the other tables to create one transaction row. The problem that occurs is within the where statement and I dont understand why. In some cases, you can have two instances of x but y will be different. In that case the joins work perfectly. In the event that there are only a single instance of x associated with a single instance of y this join does not work. Can anyone help me understand why this is happening?

select somedata, somedata, somedata, somedata
From kpi..temptablel l
left outer join @temps s on l.x = s.x
left outer join @tempf f on l.x = f.x
left outer join kpi..temptablee e on l.x = e.x
left outer join @tempn n on l.x = n.x

where l.y = s.y and l.y = f.y and l.y = e.y and l.y = n.y


The Yak Village Idiot

View 4 Replies View Related

Querying Multi-tables? Joins? Subqueries?

Jul 20, 2005

Hi, all:This is probably a simple problem, but, as an SQL newbie, I'm having alittle trouble understanding multi-joins and subqueries.I have the following tables and columns:MemberTable-----MemberID (primary key)MemberNameAddressCountryFoodsTable------FoodID (primary key)FoodNameMusicTable-----MusicID (primary key)MusicNameMoviesTable-----MoviesID (primary key)MoviesName....and their linking tables...Members2FoodsTable-----MemberID (foreign key)FoodsID (foreign key)Members2MoviesTable-----MemberID (foreign key)MoviesID (foreign key)....and so forth.Now what I'm trying to do is retrieve a specific MemberID, his address info(from the Members table), and get a listing of his favorite Movies, Foods,Music, etc. I know I probably need to JOIN tables, but where do I JOIN thetables? Do I have to JOIN the various Music/Foods/Movies tables or is itthe Music/Members2Music and Foods/Members2Foods, etc. tables? And I assumeI would probably need to perform a subquery somewhere?I realize I'll need to first filter the Members, Members2Music,Members2Foods, etc. tables by the MemberID, and afterwards, retrieve alisting of the actual Music/Foods/Movies names. I'm just confused how to dothat. (By the way, I have a total of 10 other tables or in addition toMusic, Foods, etc. so it's a lot of table JOINing.)If someone could please help me out with the actual SQL coding, I'd reallyappreciate it!Thanks for the help!J

View 6 Replies View Related

Joins On Views That Are Formed With Outer Joins

Nov 3, 2000

We find that a delete command on a table where the rows to be deleted involve an inner join between the table and a view formed with an outer join sometimes works, sometimes gives error 625.

If the delete is recoded to use the join key word instead of the = sign
then it alway gives error 4425.


625 21 0 Could not retrieve row from logical page %S_PGID by RID because the entry in the offset table (%d) for that RID (%d) is less than or equal to 0. 1033
4425 16 0 Cannot specify outer join operators in a query containing joined tables. View '%.*ls' contains outer join operators.
The delete with a correleted sub query instead of a join works.

Error 4425 text would imply that joins with view formed by outer joins should be avoided.

Any ideas on the principles involved here.

View 1 Replies View Related

JOINS To Sub-Queries -vs- JOINS To Tables

Aug 11, 2005

SQL Server 2000Howdy All.Is it going to be faster to join several tables together and thenselect what I need from the set or is it more efficient to select onlythose columns I need in each of the tables and then join them together?The joins are all Integer primary keys and the tables are all about thesame.I need the fastest most efficient method to extract the data as thisquery is one of the most used in the system.Thanks,Craig

View 3 Replies View Related

Subqueries

Apr 28, 2004

Trying to find which Employees have NOT entered a record (timecard).

Table #1 Employee_Hours
Table #2 Employee (List active)

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.

Thanks

View 1 Replies View Related

Use Of Subqueries

Jun 15, 2004

Hi,

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

Thanks,
fady

View 3 Replies View Related

Subqueries

Oct 14, 2005

Hi,

I would like to know

What is Corelated SubQueries??

Thanks in Advance

View 3 Replies View Related

Subqueries

Jan 14, 2008

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. =-)

View 16 Replies View Related

Are Sub-subqueries Possible?

Apr 12, 2006

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

View 2 Replies View Related

Help With SubQueries?

Jul 20, 2005

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

View 12 Replies View Related

Should I Do Two Subqueries?

Sep 27, 2007

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?






Code Block
SELECT dbo.Qry_Visits.Status,
dbo.Qry_Visits.Customer_code,
Qry_Sales_Group.Name,
dbo.Qry_Sales_Group.SR_Name,
dbo.Qry_Date_Dim.Date_Dimension_Fiscal_Week,
dbo.Qry_Date_Dim.Date_Dimension_Date,
dbo.Qry_Date_Dim.Day_Of_Month,
dbo.Qry_Sales_Group.Region,
dbo.Qry_Visits.period_code,
dbo.Qry_Visits.cycle_day, dbo.Qry_Visits.Visits,
dbo.Qry_Visits.time_log, dbo.Qry_Visits.Mailing_Name,
dbo.Qry_Date_Dim.Date_Dimension_Year,
dbo.Qry_Date_Dim.Date_Dimension_Period,
CONVERT(varchar, dbo.Qry_Visits.time_log, 110) AS Date,
dbo.Qry_Sales_Group.Region_Key, dbo.Qry_Visits.[SR Code],
B.VisitsTotal

FROM dbo.Qry_Visits
INNER JOIN dbo.Qry_Sales_Group
ON dbo.Qry_Visits.[SR Code]
COLLATE SQL_Latin1_General_CP1_CI_AS = dbo.Qry_Sales_Group.SalesPerson_Purchaser_Code
AND dbo.Qry_Visits.[SR Code] = dbo.Qry_Sales_Group.SalesPerson_Purchaser_Code
COLLATE Latin1_General_CI_AS
INNER JOIN dbo.Qry_Date_Dim
ON CONVERT(varchar, dbo.Qry_Date_Dim.Date_Dimension_Date, 110) = CONVERT(varchar, dbo.Qry_Visits.time_log, 110)
INNER JOIN ( Select COUNT(Visits)as VisitsTotal,[Sales Responsible],CONVERT(VARCHAR,(Qry_Visits.time_log),110)TheDate,Qry_Visits.Status
FROM dbo.Qry_Visits
WHERE Qry_Visits.Status=2
GROUP by [Sales Responsible] , CONVERT(VARCHAR,(Qry_Visits.time_log),110),Qry_Visits.Status
HAVING SUM(Visits) < 6)B
ON dbo.Qry_Sales_Group.SR_Name COLLATE Latin1_General_CI_AS = B.[Sales Responsible] COLLATE Latin1_General_CI_AS AND
CONVERT(varchar, dbo.Qry_Date_Dim.Date_Dimension_Date, 110) = B.TheDate

WHERE Qry_Visits.Status=2
ORDER BY dbo.Qry_Sales_Group.SR_Name, CONVERT(varchar, dbo.Qry_Date_Dim.Date_Dimension_Date, 110)

View 5 Replies View Related

Using Subqueries

Dec 23, 2007



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"

Thanks in advance for your help.

View 5 Replies View Related

Aggregates Containing Subqueries...

Sep 20, 2007

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).

View 4 Replies View Related

Effectively Using Subqueries

Dec 23, 2005

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.

View 2 Replies View Related

Subqueries Performances

Jun 15, 2008

Hello,

Lets consider two tables : CUSTOMERS and ORDERS.

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.

Thank you in advance for any advices,

regards,

mathmax

View 2 Replies View Related

Subqueries Performances

Jun 16, 2008

Hello,

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 ?

Thank you in advance for any advices,

regards,

mathmax

View 1 Replies View Related

Insert Subqueries

Jul 6, 2006

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

View 2 Replies View Related

View With Many Subqueries

Apr 20, 2008

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.



Code Snippet
Column1, Column2, Count1, Count2, Count3




And I want it to be quick.

What's the best way to do this?

View 1 Replies View Related

Endless Subqueries

Aug 16, 2007

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?

Thanks for suggestions

View 1 Replies View Related

Could Anybody Explain To Me Why Sqldatadpater Does Not Allow Subqueries?

Aug 17, 2007

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

View 1 Replies View Related

Insert With Multiple Subqueries

Sep 17, 2007

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?
 

View 1 Replies View Related

Subqueries In Insert Statment

Feb 26, 2008

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.
 
Thanks!

View 4 Replies View Related

Optimization: Subqueries And Backreferences?

May 17, 2000

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...

TIA,
Alex

View 2 Replies View Related

Multiple Colum Subqueries

Feb 16, 2007

hi guys,

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.

appreciate any and all help guys

thanks

andy

View 7 Replies View Related

Use Of Subqueries In An Aggregate Function

Jun 15, 2004

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.

Thanks,
Fady

View 3 Replies View Related

Subqueries In Access/MSSQL

Jun 7, 2006

Hi,

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.

Thanks.

View 14 Replies View Related

Using Subqueries To Get Latest Value Per Type?

May 7, 2008

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.

Here's the T-SQL to run my scenario:


DECLARE @actionHistoryTable TABLE (
itemID int
,actionType int
,actionValue nvarchar(50) NULL
,actionTime datetime )
INSERT @actionHistoryTable VALUES( 1000, 1, 'fork', '1/1/2008')
INSERT @actionHistoryTable VALUES( 1000, 2, '27', '1/2/2008')
INSERT @actionHistoryTable VALUES( 1000, 3, '200', '1/12/2008')
INSERT @actionHistoryTable VALUES( 1000, 2, '1', '1/1/2008')
INSERT @actionHistoryTable VALUES( 1000, 3, '204', '1/1/2008')
INSERT @actionHistoryTable VALUES( 1000, 1, 'ball', '1/3/2008')
INSERT @actionHistoryTable VALUES( 1026, 2, '20', '1/10/2008')
INSERT @actionHistoryTable VALUES( 1026, 2, NULL, '1/5/2008')
INSERT @actionHistoryTable VALUES( 1026, 1, 'hotdog', '1/6/2008')
INSERT @actionHistoryTable VALUES( 1026, 3, '2511', '1/8/2008')
INSERT @actionHistoryTable VALUES( 1026, 3, '375', '1/7/2008')
INSERT @actionHistoryTable VALUES( 1026, 1, 'mustard', '1/5/2008')
INSERT @actionHistoryTable VALUES( 1013, 1, 'rock', '1/2/2008')
INSERT @actionHistoryTable VALUES( 1013, 1, 'paper', '1/21/2008')
INSERT @actionHistoryTable VALUES( 1013, 3, '10', '1/20/2008')

-- 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



Is there a better way?
-Steve

View 8 Replies View Related

Multiple Values From Two Subqueries

Apr 7, 2015

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.

View 3 Replies View Related

Subqueries Are Not Allowed In This Context. Only S

Feb 20, 2007

Um, still trying to transpose MySQL into T-SQL.

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.

Any help would be greatly appreciated.

View 2 Replies View Related

Rewrite This? Nested Subqueries...

Jan 17, 2008

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.

View 4 Replies View Related

Convert Subqueries To Join

Aug 27, 2007

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.

id grp article
1 1 0
2 1 0
3 1 0
4 1 3
5 1 2
6 1 0
7 2 0
8 2 3
9 2 1
10 2 0
11 2 0
12 2 0
13 3 5
14 3 2
15 3 0
16 3 0
17 3 1
18 3 1

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


thanks in advance!!!

View 6 Replies View Related







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