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


ADVERTISEMENT

Endless Loop

May 14, 2004

*** edited by: master4eva ***
Please enclose your code in </ code> tags (without the space between the "</" and "code"). This will make your code easier to read online; therefore, encouraging a response to be faster. It is to your own benefit for your question to be answered in future.

I have already done the editing to include the <code></ code> tags.
*********

I have a trigger that fires this stored procedure during an update event. But i think i am getting an endless loop. Any idea? Thanks in advance....
<code>
ALTER PROCEDURE TrigRetReqRecIDP1
@REID int

AS

Declare @RRID int
Declare @intREID varchar(20)
Declare @intIMID varchar(20)
Declare @RetValint
Declare cr cursor
for
select RRID from RequestRecords where REID=@REID and RRStatus = 'PE'
open cr

fetch next from cr
into
@RRID

while @@fetch_status = 0
Begin
select @intIMID = (select IMID from ImplementationGroup where ImGrpName = 'Help Desk')
insert into ImplementationTasks
(
IMID,
ITStatus,
ITStatusDate
)
VALUES
(
@intIMID,
'2',
GetDate()
)
SET @RetVal = @@IDENTITY
Update RequestRecords
set ITID = @RETVal, RRStatus = 'IA'
where REID = @REID and RRID = @RRID


end

close cr
deallocate cr


GO

View 6 Replies View Related

SQL 7 Endless Loop!

Feb 17, 2000

I have an SQL script that runs as part of a batch process in order to number line items in timecards. It basically consists of 2 nested cursors with a number increment and update inside the inner cursor. The problem is that it gets stuck (seemingly at random) in a loop (incrementing and updating within the inner cursor) until I get an arithmetic overflow and it just moves on to the next card. I'm new to my job as a dba and the boss is breathing down my neck.....any assistance would be GREATLY appreciated!!

Thanks..Nick

Here is the code for the script:

declare @SEQ int,
@NUM smallint,
@SUM smallint,
@TSQ int,
@TLI int

declare LINES_OUT_OF_SEQ_CSR cursor for
select TIMECARD_SEQ_NBR
from EMPL_TMCD_VER_DETL
where NEW = '1'
order by TIMECARD_SEQ_NBR

open LINES_OUT_OF_SEQ_CSR

fetch next from LINES_OUT_OF_SEQ_CSR into @SEQ

while @@fetch_status = 0
begin
declare LINES_TO_CHG_SEQ_CSR cursor for
select TIMECARD_SEQ_NBR,
LINE_ITEM_SEQ_NBR
from EMPL_TMCD_VER_DETL
where TIMECARD_SEQ_NBR = @SEQ
order by LINE_ITEM_SEQ_NBR

select @NUM = 0

open LINES_TO_CHG_SEQ_CSR

fetch next from LINES_TO_CHG_SEQ_CSR into @TSQ, @TLI

while @@fetch_status = 0
begin
select @SUM = @NUM +1

select @NUM = @SUM


update EMPL_TMCD_VER_DETL
set TIMECARD_VERSION_ITEM_NBR = @NUM
where LINE_ITEM_SEQ_NBR = @TLI
and TIMECARD_SEQ_NBR = @TSQ

fetch next from LINES_TO_CHG_SEQ_CSR into @TSQ, @TLI
end

deallocate LINES_TO_CHG_SEQ_CSR

fetch next from LINES_OUT_OF_SEQ_CSR into @SEQ
end

deallocate LINES_OUT_OF_SEQ_CSR
go

View 2 Replies View Related

Endless Looping Job!!!!

Jan 29, 2004

i have created a job that i have scheduled to run every 10 min everything is configured well since i have tested preety everything their is to be tested and found that it was my last step wich as a fetch in it so i imagine that this fetch is making it loop over and over again. the job goes trought all the steps and starts back at the first step and keep going like that till i disable it here is my fetch statement and if you have any clue any help would be widely apreciated.


PS: i suspected it to be that fetch statement causing the havoc ;)



DECLARE
@TransactionNb varchar(10),
@EqId varchar(10)

DECLARE TransactionNb_cursor CURSOR
FOR
SELECT TransactionNb, EqId
FROM DetCom
WHERE UpdCode = 'C'

OPEN TransactionNb_cursor

FETCH NEXT FROM TransactionNb_cursor
INTO @TransactionNb, @EqId

WHILE @@FETCH_STATUS <> -1
BEGIN
-- Vérifier s'il existe une transaction avec le UpdCode = 'C' dans EntCom
IF (SELECT UpdCode
FROM EntCom
WHERE TransactionNb = @TransactionNb and EqId = @EqId) = 'C'
BEGIN
CONTINUE
END
ELSE
BEGIN
RAISERROR (50006, 10, 0, @TransactionNb, @EqId)
END

FETCH NEXT FROM TransactionNb_cursor
INTO @TransactionNb, @EqId
END

CLOSE TransactionNb_cursor
DEALLOCATE TransactionNb_cursor

View 1 Replies View Related

How To Simplify My Endless Query. Thanks.

Jul 23, 2005

Hello group!I am having a problem with simplying my query...I would like to get customers' balance info based on how many monthssince they opened their accounts. The tricky part here is accountsstarting with '28' are treated differently than other accounts, theyare given 3 months grace period. In other words, for all otheraccounts, their month0 balance is the balance of their open_month, andmonth1 balance is the balance after the account is opened 1 month, andso on. But accounts starting with '28' month0 balance would be thebalance after the account is opened 3 months, and month1 balance wouldbe the balance after the account is opened 4 months, and so on.My query below works, but since some customers are more than 10 yearsold (more than 120 months), my query is endless! Does anyone know abetter way to do the same job? Many thanks!create table a(person_id int,account int,open_date datetime)insert into a values(1,200001,'11/15/2004')insert into a values(2,280001,'8/20/2004')create table b(account int,balance_date datetime,balance money)insert into b values(200001,'11/30/2004',700)insert into b values(200001,'12/31/2004',800)insert into b values(200001,'1/31/2005',900)insert into b values(200001,'2/28/2005',1000)insert into b values(280001,'8/30/2004',7000)insert into b values(280001,'9/30/2004',8000)insert into b values(280001,'10/31/2004',9000)insert into b values(280001,'11/30/2004',10000)insert into b values(280001,'12/31/2004',15000)insert into b values(280001,'1/31/2005',20000)insert into b values(280001,'2/28/2005',30000)--Ideal output--person_idacc_nomonth0_balancemonth1_balancemonth2_balancemonth3_balance1200000170080090010002280000110000150002000030000select a.person_id,a.account,month0_balance=casewhen a.account like '2%' and a.account not like '28%'thensum(case datediff(mm, a.open_date, balance_date) when 0then b.balance else 0 end)else sum(case datediff(mm, a.open_date, balance_date)when 3 then b.balance else 0 end)end,month1_balance =casewhen a.account like '2%' and a.account not like '28%'thensum(case datediff(mm, a.open_date, balance_date) when 1then b.balance else 0 end)else sum(case datediff(mm, a.open_date, balance_date)when 4 then b.balance else 0 end)endfrom a as ajoin b as bon a.account=b.accountgroup by a.person_id, a.account

View 3 Replies View Related

Foreach Endless Loop

Feb 28, 2007

I'm having a problem where I'm using a Execute SQL Task to retrieve a dataset and storing that in an object variable. Then on success of that execute sql task I use a foreach loop task to go through the dataset and do 2 tasks inside the foreach loop. When I execute this package I have ~12 records in the dataset however when I get to the foreach loop in the 2nd iteration it keeps repeating it. It acts like it is stuck on the second record (tuple) and never goes on. I'm using an ForEach ADO Enumerator in the foreach. I've even set a breakpoint on each iteration and no task fails in side the foreach loop. I'm completely perplexed why it will iterate to the 2nd record but get stuck there in an endless loop. I've tried this on 2 different computers (with different data values) and the same thing happens. Does anyone have any suggestions?

View 40 Replies View Related

Endless Running Package Using A Proxy

Jan 15, 2007

I have a package which runs fine, when I execute it with my account (e.g. double-click on the .dtsx file and run it).

Now I would like to establish a job, which starts the package. I created first a credential for my Account (which is a domain administrator account also for the box, where SQL Server is running on), then I defined a proxy to this credential.

In the job definition I changed the Run as... to this Proxy (it is a SSIS Proxy) and then I started the job.

Th job does NOT abend, it runs forever! So I have to stop it manually.

In the log I can see as last entry : "operation complete". It stops at a "Execute process task" where I call the bcp utility.



Does anyone has an idea, why a package can run forever?!?!

Regards

Norbert

View 1 Replies View Related

Endless Query With Custom Function - DATEADD

Apr 11, 2015

I created a function to use in a View, works similar to DATEADD but only with my company's Business days Monday-Thursday.

I am running a query but it never ends to run.

This is the function:

USE [RA_dev]
GO
/****** Object: UserDefinedFunction [Production].[GBDATEADD] Script Date: 4/11/2015 5:58:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[Code] ...

This is how I am trying to use it in the View:

Production.GBDATEADD(Production.Schedule.START_DATE, Production.Operations_Data_Pool.MFG_DAY - 1) AS SCH_DATE

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

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

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







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