Need Help Evaluating And Changing The Value Of A Subquery

Feb 1, 2008



Hello all,
I currently have a pain in the butt with a subquery that needs to be evaluated, and if the result gives me a null value, I want to re-evaluate the condition and fill the column with the proper information.
I'll try to explain it as best as I can:

The query retrieves information from 2 tables basically, but i do need some inner joins of diferent tables in order to follow the relations..
I got 2 conditions that need to be acomplished, the 'typeof' (intId_Tipo) has to be diferent from 6 and a keycode equals to 3.

For the "general query" i do filter this just fine, but in the subquery is where I get stucked:
Since the evaluation that I do in oder to find the initial point is just by substracting 1, there are some cases where the type called intId_Tipo is actually 6 and the subquery returns me a null value.
In this particular case I want to substract 2..if not I just want to substract 1.
I added a SQL CASE in oder to evaluate the null value, but it is not evaluating properly, why? I'm not sure, I need your help and recomendation guys



Here's the query that I currently have: (the comments were made in order to take the next screenshot)



Code Snippet
SELECT --h.dt_Lectura,
--h.int_Velocidad, rp.int_VelMaxima,
(SELECT intpunto FROM tblRecorrido_Puntos WHERE intPunto = case when (intPunto) is null then rp.intPunto - 2 else rp.intPunto -1 END AND rp.intId_Ruta_Ramal =intId_Ruta_Ramal AND intId_Tipo =rp.intId_Tipo) as PuntoInicial,
rp.intPunto as PuntoFinal
--rp.strDescripcion_Punto as DescripcionPuntoFinal,
--1 as Contador
--a.idRuta_Guid, a.idRamal_Guid,a.idUnidad_Guid, a.idOperador_Guid

FROM tblHistorico h
INNER JOIN tblAsignaciones a
ON a.id=h.intIdAsignaciones
INNER JOIN tblRutaRamal_Generado rrg
ON rrg.id_Ruta = a.intRuta_Asignada
INNER JOIN tblRecorrido_Puntos rp
ON (rp.intId_Ruta_Ramal =rrg.intId_Ruta_Ramal AND rp.intPunto=h.int_PtoDest)

WHERE (
h.int_ClaveTDE =3 and rp.intId_Tipo <> 6
)

ORDER BY rp.intPunto ASC

Here's the screenshot of the query result: http://img218.imageshack.us/my.php?image=consultahd0.jpg

Any help is appreciated!
Jaime,

View 8 Replies


ADVERTISEMENT

Subquery Returned More Than 1 Value. This Is Not Permitted When The Subquery Follows =, !=, &<, &<= , &>, &>= Or When The Subquery Is Used As An Expression.

Apr 26, 2008

hello friends.. I am newbie for sql server...I having a problem when executing this procedure .... ALTER PROCEDURE [dbo].[spgetvalues]    @Uid intASBEGIN    SET NOCOUNT ON;        select                                  DATEPART(year, c.fy)as fy,                                                (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1%      JRF' ) as survivorship,                (select contribeamount from wh_contribute where and contribename like  'Gross Earnings' and ) as ytdgross,                (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1.5%      JRP') as totalcontrib,                                                       from    wh_contribute c                       where    c.uid=@Uid                 Order by fy Asc .....what is the wrong here??  " Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."please reply asap... 

View 1 Replies View Related

Subquery Returned More Than 1 Value. This Is Not Permitted When The Subquery Follows =, !=, &<, &<= , &>, &>= Or When The Subquery Is Used As An Expression.

Jul 20, 2005

I am getting 2 resultsets depending on conditon, In the secondconditon i am getting the above error could anyone help me..........CREATE proc sp_count_AllNewsPapers@CustomerId intasdeclare @NewsId intset @NewsId = (select NewsDelId from NewsDelivery whereCustomerId=@CustomerId )if not exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count( NewsPapersId) from NewsPapersendif exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count(NewsDelId) from NewsDelivery whereCustomerid=@CustomeridendGO

View 3 Replies View Related

Subquery Returned More Than 1 Value. This Is Not Permitted When The Subquery Follows =, !=, &&<, &&<= , &&>, &&>= Or When The Subquery I

Mar 6, 2008

I am getting an error as

Msg 512, Level 16, State 1, Line 1

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

while running the following query.





SELECT DISTINCT EmployeeDetails.FirstName+' '+EmployeeDetails.LastName AS EmpName,

LUP_FIX_DeptDetails.DeptName AS CurrentDepartment,

LUP_FIX_DesigDetails.DesigName AS CurrentDesignation,

LUP_FIX_ProjectDetails.ProjectName AS CurrentProject,

ManagerName=(SELECT E.FirstName+' '+E.LastName

FROM EmployeeDetails E

INNER JOIN LUP_EmpProject

ON E.Empid=LUP_EmpProject.Empid

INNER JOIN LUP_FIX_ProjectDetails

ON LUP_EmpProject.Projectid = LUP_FIX_ProjectDetails.Projectid

WHERE LUP_FIX_ProjectDetails.Managerid = E.Empid)



FROM EmployeeDetails

INNER JOIN LUP_EmpDepartment

ON EmployeeDetails.Empid=LUP_EmpDepartment.Empid

INNER JOIN LUP_FIX_DeptDetails

ON LUP_EmpDepartment.Deptid=LUP_FIX_DeptDetails.Deptid

AND LUP_EmpDepartment.Date=(SELECT TOP 1 LUP_EmpDepartment.Date

FROM LUP_EmpDepartment

WHERE EmployeeDetails.Empid=LUP_EmpDepartment.Empid

ORDER BY LUP_EmpDepartment.Date DESC)

INNER JOIN LUP_EmpDesignation

ON EmployeeDetails.Empid=LUP_EmpDesignation.Empid

INNER JOIN LUP_FIX_DesigDetails

ON LUP_EmpDesignation.Desigid=LUP_FIX_DesigDetails.Desigid

AND LUP_EmpDesignation.Date=(SELECT TOP 1 LUP_EmpDesignation.Date

FROM LUP_EmpDesignation

WHERE EmployeeDetails.Empid=LUP_EmpDesignation.Empid

ORDER BY LUP_EmpDesignation.Date DESC)

INNER JOIN LUP_EmpProject

ON EmployeeDetails.Empid=LUP_EmpProject.Empid

AND LUP_EmpProject.StartDate=(SELECT TOP 1 LUP_EmpProject.StartDate

FROM LUP_EmpProject

WHERE EmployeeDetails.Empid=LUP_EmpProject.Empid

ORDER BY LUP_EmpProject.StartDate DESC)

INNER JOIN LUP_FIX_ProjectDetails

ON LUP_EmpProject.Projectid=LUP_FIX_ProjectDetails.Projectid



WHERE EmployeeDetails.Empid=1

PLEASE HELP.................

View 1 Replies View Related

Subquery Returned More Than 1 Value. This Is Not Permitted When The Subquery Follows =, !=, &&<, &&<= , &&>, &&>= Or When The Subquery I

May 14, 2008

Hi,

I've running the below query for months ans suddenly today started getting the following error :"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."

Any ideas as to why??

SELECT t0.DocNum, t0.Status, t0.ItemCode, t0.Warehouse, t0.OriginNum, t0.U_SOLineNo, ORDR.NumAtCard, ORDR.CardCode, OITM_1.U_Cultivar,
RDR1.U_Variety,
(SELECT OITM.U_Variety
FROM OWOR INNER JOIN
WOR1 ON OWOR.DocEntry = WOR1.DocEntry INNER JOIN
OITM INNER JOIN
OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod ON WOR1.ItemCode = OITM.ItemCode
WHERE (OITB.ItmsGrpNam = 'Basic Fruit') AND (OWOR.DocNum = t0.DocNum)) AS Expr1, OITM_1.U_Organisation, OITM_1.U_Commodity,
OITM_1.U_Pack, OITM_1.U_Grade, RDR1.U_SizeCount, OITM_1.U_InvCode, OITM_1.U_Brand, OITM_1.U_PalleBase, OITM_1.U_Crt_Pallet,
OITM_1.U_LabelType, RDR1.U_DEPOT, OITM_1.U_PLU, RDR1.U_Trgt_Mrkt, RDR1.U_Wrap_Type, ORDR.U_SCCode
FROM OWOR AS t0 INNER JOIN
ORDR ON t0.OriginNum = ORDR.DocNum INNER JOIN
RDR1 ON ORDR.DocEntry = RDR1.DocEntry AND t0.U_SOLineNo - 1 = RDR1.LineNum INNER JOIN
OITM AS OITM_1 ON t0.ItemCode = OITM_1.ItemCode
WHERE (t0.Status <> 'L')

Thanks

Jacquues

View 4 Replies View Related

Evaluating A Parameter's Value Dynamically

Jan 25, 2006

Hi, I'm creating a dynamic SQL statement in MS SQL Server that is similiar to this:
EXEC('IF @' + @current_column + ' (SELECT ' + + @current_column etc...
I'm basically looping through a large list of parameters that correspond to column names.  However, since SQL Server treats EXEC() as its own scope when it gets to what "@' + @current_column" evaluates to it says the parameter must be declared.
Is there a way to convert "@' + @current_column " into the actual value of the parameter?

View 2 Replies View Related

Evaluating Disk Space

May 9, 2000

We recently moved from v6.5 to v7.0. Now I have the databases and logs set to "autogrow". How can I monitor the disk space to ensure I do not run out of room (or is that preset as to how large it can grow ?). Can't find anything in the books online. Do I do this through the NT admin tool or through the SQL*Server Enterprise Manager and more importantly - how ???
Thanks so much for any help...
Nancy

View 3 Replies View Related

Evaluating Lumigent Entegra

Jul 23, 2005

Hi,I am evaluating Lumigent's Entegra for doing security and businessaudit of some of the critical database(s) in the company I work for. Iwould like to know what has been your experience in using this productfor doing similar audits in your company, if you have also done suchaudits.Thanks,Sanjeev

View 2 Replies View Related

Evaluating String Content

Jun 12, 2006

Our Business partners request me to read the field names from a SQL table dynamically so that my SSIS package will not get impacted if Web Service hosts make a change.

Is there a way to evaluate a string at runtime that contains a field name ?

Thanks,

Gulden 

View 6 Replies View Related

Error Evaluating Expression

May 22, 2006

Greetings my SQL friends.

Why do I get an error message saying that the following expression won't evaluate?

"Select * from Price_grp where price_grp_id >= " + (dt_str, 10, 1252) @[User::MIN_PRICE_GRP_ID] +
" and " + (dt_str, 10, 1252) @[User::MIN_PRICE_GRP_ID] + " > 0"

Thanks for your help in advance.

View 4 Replies View Related

Date Not Evaluating In An Expression

Dec 5, 2006



I have been looking all over for some info about other people having this problem, but haven't found anything.

I have a package that needs to download a dated file from an ftp site. I am using a couple script objects to set variables, and one of them is the filename based on the date. I use an expression to get the date:

@[User::varFileName] = (DT_WSTR,4) Year( GetDate()) + (DT_WSTR,2) Month( GetDate()) + Substring((DT_WSTR, 29) GETDATE(), 9, 2)

Everything works really well when I am debugging it locally. However once it is on the server or even once I come back to it in a day or two, I am still seeing the old date. I thought it might be because my variable needed to be set to evaluateexpression = true, however once I did this it hung me and prevented me from debugging and I had to end bus dev studio. Not sure if its because it is being evaluated in two places (as a global and then in a script) but when I took it out of my script it hung again. Its strange in order to get it to work when I am debugging it locally I have to go to each process and evaluate the expressions in there, then it seems to work. thanks!

View 4 Replies View Related

Question On Evaluating Expression

May 15, 2008


Hi all€”I'm new to expressions, and am trying to write one where I can evaluate if a field is null, to handle it by inserting a default value if a null value is found. Given this table definition:

CREATE TABLE [dbo].[Meter Readings_stage](
[Meter System ID] [varchar](8) NOT NULL,
[Reading Date/Time] [datetime] NOT NULL,
[Meter Status] [varchar](50) NULL,
[Totalizer] [float] NULL,
[Secondary Totalizer] [real] NULL CONSTRAINT [DF_Meter Readings_Secondary Totalizer2] DEFAULT (NULL),
[Demand] [real] NULL CONSTRAINT [DF_Meter Readings_Demand2] DEFAULT (NULL),
[Demand Date/Time] [datetime] NULL CONSTRAINT [DF_Meter Readings_Demand Date/Time2] DEFAULT (NULL),
[Reading Type] [varchar](30) NULL CONSTRAINT [DF_Meter Readings_Reading Type2] DEFAULT (NULL),
[Comments] [varchar](200) NULL CONSTRAINT [DF_Meter Readings_Comments2] DEFAULT ('None'),
[Checked?] [bit] NULL CONSTRAINT [DF_Meter Readings_Checked ?2] DEFAULT ((1)),
[Estimate Required] [bit] NULL CONSTRAINT [DF_Meter Readings_Estimate Required2] DEFAULT ((0)),
[Hold] [bit] NULL CONSTRAINT [DF_Meter Readings_Hold2] DEFAULT ((0)),
[Processed?] [bit] NOT NULL CONSTRAINT [DF_Meter Readings_Processed2] DEFAULT ((0))

I am importing data from a CSV file where any of the fields can be null. The format is as follows:

[Meter System ID],[Reading Date],[Reading Time],[Totalizer],[Demand],[Demand Date],[Demand Time], [Reading Type]

I need to handle it something like the following in a derived column transformation, where:

[Meter System ID]: string [DT_STR]
[Reading Date]: database date [DT_DBDATE]
[Reading Time]: database time [DT_DBTIME]
[Totalizer]: float [DT_R4]
[Demand]: float [DT_R4]
[Demand Date]: database date [DT_DBDATE]
[Demand Time]: database time [DT_DBTIME]
[Reading Type]: string [DT_STR]

This is what I have built so far:
NULL((DT_DBDATE)("Reading Date")) ? (DT_DBDATE)(GETDATE()) : (DT_DBDATE)("Reading Date")

I am getting an error on the cast conversion, however. Where is the error in the evaluation?

Thanks,
Jon

View 5 Replies View Related

Evaluating/Validating Paramaters In A SqlDataSource

Dec 21, 2007

I want to do some error checking on the parameters found in a SQLDataSource before I run the insert.  The problem is these are ControlParameters and I want to do this dynamically so I can't just call the Control.Text property and grab its value. So how can I get access to what the ControlParameter evaluates to?
Secondly, is there a way to access what the update parameters evaluate to in order to check them before they're inserted - if so how do I get access to these?
Here's an example of one of the data sources i'm using:<asp:SqlDataSource ID="sqlContact" runat="server" ConnectionString="<%$ ConnectionStrings:strConn %>"
SelectCommand="SELECT [ContactID], [FirstName], [LastName], , [Address], [Phone], [Grade], [Contacted], [ListServe] FROM [Contact]"
UpdateCommand="UPDATE Contact SET FirstName = @FirstName, LastName = @LastName, Email = @Email, Address = @Address, Phone = @Phone, Grade = @Grade WHERE ContactID = @ContactID"
DeleteCommand="DELETE FROM [Contact] WHERE ContactID = @ContactID"
InsertCommand="INSERT INTO [Contact] ([FirstName],[LastName],,[Address],[Phone],[Grade],[Contacted],[ListServe]) VALUES (@FirstName,@LastName,@Email,@Address,@Phone,@Grade,0,0)">
<UpdateParameters>
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Address" Type="String" />
<asp:Parameter Name="Phone" Type="String" />
<asp:Parameter Name="Grade" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:ControlParameter Name="FirstName" Type="String" ControlID="txtContactFirst" PropertyName="Text" />
<asp:ControlParameter Name="LastName" Type="String" ControlID="txtContactLast" PropertyName="Text" />
<asp:ControlParameter Name="Email" Type="String" ControlID="txtContactEmail" PropertyName="Text" />
<asp:ControlParameter Name="Address" Type="String" ControlID="txtContactAddress" PropertyName="Text" />
<asp:ControlParameter Name="Phone" Type="String" ControlID="txtContactPhone" PropertyName="Text" />
<asp:ControlParameter Name="Grade" Type="String" ControlID="ddlContactGrade" PropertyName="SelectedValue" />
</InsertParameters>
</asp:SqlDataSource>
 An Event is fired when I click add on a button which looks similar to this:
//Add btnAddContact_Clickprotected void btnAddContact_Click(object sender, EventArgs e)
{
InsertRow(sqlContact);
}The InsertRow() function is then what i'm using to evaluate the values...  So how can get the values those controlparameters actually are in order to evaluate them before I actually insert.  Or is there a better way to do it?

View 4 Replies View Related

Evaluating Derived Columns Within A Select

Sep 19, 2006

Hi
I'm updating an old Access application to SQL Server and am currently trying to decipher one of the reports on the old application. It appears to be evaluating a derived column from one query (qryStudentSuspGroup.Suspension) in the Select statement of another. I have tried to put the query that creates the derived column in as a nested query into the other query but can't get it to work. This is all a bit beyond my rudimentary SQL skills! Any help would be greatly appreciated!

The original Access SQL appears below:

SELECT [Enter the academic year (4 digits)] AS [input], ResearchStudent.Department, ResearchStudent.DateAwarded,
ResearchStudent.StudentNumber, Person.Forenames AS fore, Person.Surname AS Sur, ResearchStudent.Mode,
ResearchStudent.RegistrationDate, StudentExamination.Decision,
IIf(([Suspension]) Is Null Or [Suspension]=0,([DateAwarded]-[RegistrationDate])/365,(([DateAwarded]-[RegistrationDate])-([Suspension]))/365) AS CompDate,
ResearchStudent.EnrollmentCategory, qryStudentSuspGroup.Suspension
FROM ((ResearchStudent LEFT JOIN Person ON ResearchStudent.ResearchStudentID = Person.PersonID)
LEFT JOIN qryStudentSuspGroup ON ResearchStudent.ResearchStudentID = qryStudentSuspGroup.ResearchStudentID)
LEFT JOIN StudentExamination ON ResearchStudent.ResearchStudentID = StudentExamination.ResearchStudentID
WHERE (((Year([DateAwarded]))>=[Enter the academic year (4 digits)]
And (Year([DateAwarded]))<=([Enter the academic year (4 digits)]+1))
AND ((IIf(Year([DateAwarded])=[Enter the academic year (4 digits)],Month([DateAwarded])>8,Month([DateAwarded])<9))<>False))
ORDER BY ResearchStudent.Department, ResearchStudent.Mode, ([DateAwarded]-[RegistrationDate])/365

View 15 Replies View Related

Evaluating 2 Fields And Returning The Larger

May 22, 2007

I have two int fields in my database, CEOAnnualBonus and CEOBonus, and I want to return the value of whichever one has the larger value as CEOBonusCombined. I thought using COALESCE would do the trick like below but there are many cases where either CEOAnnualBonus or CEOBonus have a zero value instead of NULL and it doesn't work.

SELECT
COALESCE(CEOAnnualBonus, CEOBonus)
AS CEOBonusCombined
FROM tbenchmarktemp
WHERE Ticker='F'

Thanks for any help

View 3 Replies View Related

Evaluating Varchar String With Math

Mar 5, 2008

In reference to this thread:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50392

madhivanan asks for sample table data to avoid using a cursor. I could really use this, so here is the table



CREATE TABLE #T (
FORMULA VARCHAR(15),
ANSWER decimal(15,8)
)
INSERT INTO #T SELECT '1', NULL
INSERT INTO #T SELECT '1.0 + 2', NULL
INSERT INTO #T SELECT '1/2', NULL
INSERT INTO #T SELECT '1/2+2', NULL
INSERT INTO #T SELECT '1/(2+2)',NULL
INSERT INTO #T SELECT '3*7.5', NULL
INSERT INTO #T SELECT '3/2*.6-2', NULL
INSERT INTO #T SELECT '(1-1)', NULL

SELECT * FROM #T

-- RUN THE MATH FUNCTIONS, UPDATE THE TABLE'S ANSWER COLUMN WITH THE ANSWER

SELECT * FROM #T

DROP TABLE #T


I would expect this output:

FORMULA ANSWER
====================
1 NULL
1.0 + 2 NULL
1/2 NULL
1/2+2 NULL
1/(2+2) NULL
3*7.5 NULL
3/2*.6-2 NULL

FORMULA ANSWER
====================
1 1.00000000
1.0 + 2 3.00000000
1/2 0.50000000
1/2+2 2.50000000
1/(2+2) 0.25000000
3*7.5 22.50000000
3/2*.6-2 -1.10000000
(1-1) 0.00000000


Any help appreciated, thanks,

View 9 Replies View Related

Subquery Returned More Than 1 Value But Work FINE (field_xxx=subquery)

Jul 19, 2007

Hi guys,



A have a problem that I need understand.... I have 2 server with the same configuration...



SERVER01:

-----------------------------------------------------

Microsoft SQL Server 2000 - 8.00.2191 (Intel IA-64)

Mar 27 2006 11:51:52

Copyright (c) 1988-2003 Microsoft Corporation

Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)



sp_dboption 'BB_XXXXX'

The following options are set:

-----------------------------------

trunc. log on chkpt.

auto create statistics

auto update statistics

********************************

SERVER02:

-----------------------------------------------------

Microsoft SQL Server 2000 - 8.00.2191 (Intel IA-64)

Mar 27 2006 11:51:52

Copyright (c) 1988-2003 Microsoft Corporation

Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)



sp_dboption 'BB_XXXXX'

The following options are set:

-----------------------------------

trunc. log on chkpt.

auto create statistics

auto update statistics



OK, the problem is that if a run the below query in server01, i get error 512:



Msg 512, Level 16, State 1, Line 1

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.



But, if run the same query in the server02, the query work fine -.



I know that I can use IN, EXISTS, TOP, etc ... but I need understand this behavior.



Any idea WHY?



SELECT dbo.opf_saldo_ctb_opc_flx.dt_saldo,

dbo.opf_saldo_ctb_opc_flx.cd_indice_opf,

dbo.opf_saldo_ctb_opc_flx.cd_classificacao,

dbo.opf_movimento_operacao.ds_tipo_transacao ds_tipo_transacao_movimento ,

dbo.opf_header_operacao.ds_tipo_transacao ds_tipo_transacao_header,

'SD' ds_status_operacao,

dbo.opf_header_operacao.ds_tipo_opcao ,

dbo.opf_header_operacao.id_empresa,

dbo.opf_saldo_ctb_opc_flx.ic_empresa_cliente,

0 vl_entrada_compra_ctro ,0 vl_entrada_compra_premio,

0 vl_entrada_venda_ctro , 0 vl_entrada_venda_premio,

0 vl_saida_compra_ctro, 0 vl_saida_compra_premio,

0 vl_saida_venda_ctro, 0 vl_saida_venda_premio,

0 vl_lucro , 0 vl_prejuizo, 0 vl_naoexec_contrato,

0 vl_naoexec_premio,

sum(dbo.opf_saldo_ctb_opc_flx.vl_aprop_ganho) vl_aprop_ganho,

sum(dbo.opf_saldo_ctb_opc_flx.vl_aprop_perda) vl_aprop_perda,

sum(dbo.opf_saldo_ctb_opc_flx.vl_rever_ganho) vl_rever_ganho,

sum(dbo.opf_saldo_ctb_opc_flx.vl_rever_perda) vl_rever_perda,

sum(dbo.opf_saldo_ctb_opc_flx.vl_irrf) vl_irrf

FROM dbo.opf_saldo_ctb_opc_flx,

dbo.opf_header_operacao ,

dbo.opf_movimento_operacao

WHERE dbo.opf_saldo_ctb_opc_flx.dt_saldo = '6-29-2007 0:0:0.000'

and ( dbo.opf_header_operacao.no_contrato = dbo.opf_saldo_ctb_opc_flx.no_contrato )

and ( dbo.opf_header_operacao.no_contrato = dbo.opf_movimento_operacao.no_contrato )

and ( dbo.opf_movimento_operacao.dt_pregao = (select (o.dt_pregao) from dbo.opf_movimento_operacao o

where o.no_contrato = dbo.opf_movimento_operacao.no_contrato and o.dt_pregao <='6-28-2007 0:0:0.000' ) )

and (dbo.opf_saldo_ctb_opc_flx.ic_tipo_saldo = 'S')

group by dbo.opf_saldo_ctb_opc_flx.dt_saldo,

dbo.opf_saldo_ctb_opc_flx.cd_indice_opf,

dbo.opf_saldo_ctb_opc_flx.cd_classificacao,

dbo.opf_movimento_operacao.ds_tipo_transacao,

dbo.opf_header_operacao.ds_tipo_transacao ,

ds_status_operacao,

dbo.opf_header_operacao.ds_tipo_opcao ,

dbo.opf_header_operacao.id_empresa,

dbo.opf_saldo_ctb_opc_flx.ic_empresa_cliente



Thanks

Nilton Pinheiro

View 9 Replies View Related

Adding Product Of A Subquery To A Subquery Fails?

Jul 6, 2014

I am trying to add the results of both of these queries together:

The purpose of the first query is to find the number of nulls in the TimeZone column.

Query 1:

SELECT COUNT(*) - COUNT (TimeZone)
FROM tablename

The purpose of the second query is to find results in the AAST, AST, etc timezones.

Query 2:

SELECT COUNT (TimeZone)
FROM tablename
WHERE TimeZone NOT IN ('EST', 'MST', 'PST', 'CST')

Note: both queries produce a whole number with no decimals. Ran individually both queries produce accurate results. However, what I would like is one query which produced a single INT by adding both results together. For example, if Query 1 results to 5 and query 2 results to 10, I would like to see a single result of 15 as the output.

What I came up with (from research) is:

SELECT ((SELECT COUNT(*) - COUNT (TimeZone)
FROM tablename) + (SELECT COUNT (TimeZone)
FROM tablename
WHERE TimeZone NOT IN ('EST', 'MST', 'PST', 'CST'))

I get a msq 102, level 15, state 1 error.

I also tried

SELECT ((SELECT COUNT(*) - COUNT (TimeZone)
FROM tablename) + (SELECT COUNT (TimeZone)
FROM tablename
WHERE TimeZone NOT IN ('EST', 'MST', 'PST', 'CST')) as IVR_HI_n_AK_results

but I still get an error. For the exact details see:

[URL]

NOTE: the table in query 1 and query 2 are the same table. I am using T-SQL in SQL Server Management Studio 2008.

View 6 Replies View Related

SQL Server 2012 :: Evaluating Rows And Selecting Specific Records

Mar 18, 2015

I have a table with some examples below. I need to identify records where:

1. the person has 3 or more consecutive months ordered.
2. I then need to exclude the first and last month and capture only those Months in between.

PERSON ID MONTH ORDERED
JD12345 4
JD12345 7
JD12345 8 Note: JD12345 should be excluded entirely

[code]....

View 6 Replies View Related

SQL Server 2014 :: Case Syntax In Store Procedure Evaluating 2 Query Options

May 4, 2015

What will be the best way to write this code? I have the following code:

BEGIN
declare
status_sent as nvarchar(30)
SET NOCOUNT ON;
case status_sent =( select * from TableSignal

[Code] ...

then if Signal Sent.... do the following query:

Select * from package.....

if signal not sent don't do anything

How to evaluate the first query with the 2 options and based on that options write the next query.

View 2 Replies View Related

SQL And A Subquery

Jun 19, 2006

Hi and thanks in advance for the help.
Here's what I'm trying to do, I need to select all the rows from one table, and only 1 row from a related table.
Table setup
Table1:
Field 1 = PK Ident
Table2:
Field1 = FK ident
I need to select all the rows that exist in Table 1, and I need 1 row out of table2 where Field1 is equal to the Table1.Field1 value (multiple records in table2 will exist with that same value.)  I need the top row using a SELECT TOP 1
I was trying to do this with a subquery, but SQL is throwing an error asking me for EXISTS statments.
 

View 1 Replies View Related

T-SQL Subquery

Aug 11, 2006

I have the following as a subquery in a larger stored procedure:
SELECT P.ProductId, P.ProductName, P.Category , (SELECT MAX(O.Orderdate) FROM dbo.[Orders] AS O WHERE O.ProductId=P.ProductId) As MostRecentOrder, ROW_NUMBER() OVER (ORDER BY MostRecentOrder DESC) AS RowNumber FROM dbo.[Products] AS P WHERE P.Category=@category
@category is an input parameter
I am getting an error pointing to the Order By clause stating that "MostRecentOrder" is an invalid column name. If I sort by P.ProductId or P.ProductName, it works fine. Any ideas?
 
Thanks

View 16 Replies View Related

SubQuery Help!

Jan 13, 2007

Hi All, This Subquery is kicking my ***. Maybe you  can help. I want to query a query.I have the user enter a phrase from a textbox, then I want to group the results by element_label. This is what i have so far, but its not working.  SELECT Element_ID, Element_Label, Element_Name, Question_ID, Question_Label, Question_Level, Question_Text, RelatedSRR
FROM qryforaspx
WHERE ([Question_Text] LIKE '%' + ? + '%')
IN
SELECT Element_Label FROM Description
Group by
Element_label Thanks, 

View 2 Replies View Related

MS SubQuery Changes???

Jun 20, 2005

Has anyone seen where subqueries collapse into a sum???  I have code like the following, which has been running fine for over a year:UPDATE Reports..DataStats SET Vendors_Cnt = (SELECT COUNT(*) FROM vVendors__AllRecords), Vendors_Audit_Cnt = (SELECT COUNT(*) FROM vVendors_InvAudit), Vendors_Rpts_Cnt = (SELECT COUNT(*) FROM vVendors_Inv12mo), Vendors_InvUnused = (SELECT COUNT(*) FROM vVendors_InvUnused),Vendors_InvOne = (SELECT COUNT(*) FROM vVendors_InvOne), Vendors_InvMulti = (SELECT COUNT(*) FROM vVendors_InvMulti), Vendors_InvUnpaid = (SELECT COUNT(*) FROM vVendors_InvUnpaid), Vendors_InvNewer = (SELECT COUNT(*) FROM vVendors_InvNewer), Vendors_Inv12mo = (SELECT COUNT(*) FROM vVendors_Inv12mo), Vendors_InvPrior = (SELECT COUNT(*) FROM vVendors_InvPrior), Vendors_InvSkipYear = (SELECT COUNT(*) FROM vVendors_InvSkipYear), Vendors_Known = (SELECT COUNT(*) FROM vVendors_Known), Vendors_Orphaned = (SELECT COUNT(*) FROM vVendors_Orphaned), Vendors_Active = (SELECT COUNT(*) FROM vVendors_Active), Vendors_Inactive = (SELECT COUNT(*) FROM vVendors_Inactive), Vendors_Excluded = (SELECT COUNT(*) FROM vVendors_Excluded)WHERE (AuditName = @AuditName)But now it is generating overflows....and is not equivalent to (ignoring the obvious UPDATE vs. return differences for illustration):SELECT COUNT(*) FROM vVendors__AllRecordsSELECT COUNT(*) FROM vVendors_InvAuditSELECT COUNT(*) FROM vVendors_Inv12mo SELECT COUNT(*) FROM vVendors_InvUnusedSELECT COUNT(*) FROM vVendors_InvOneSELECT COUNT(*) FROM vVendors_InvMultiSELECT COUNT(*) FROM vVendors_InvUnpaid SELECT COUNT(*) FROM vVendors_InvNewer SELECT COUNT(*) FROM vVendors_Inv12mo SELECT COUNT(*) FROM vVendors_InvPrior SELECT COUNT(*) FROM vVendors_InvSkipYear SELECT COUNT(*) FROM vVendors_KnownSELECT COUNT(*) FROM vVendors_OrphanedSELECT COUNT(*) FROM vVendors_Active SELECT COUNT(*) FROM vVendors_Inactive SELECT COUNT(*) FROM vVendors_ExcludedThis appears to have started around the beginning of May.  Anyone else suffer after patches?

View 5 Replies View Related

Subquery Help

Jun 22, 1998

i have a table which i`m having difficulty setting up a subquery on.

cmpcode code grpcode
------------ --------- ------------
CORP 96020 01ADMIN
HON 96020 01ADMIN
LON 96020 04FOREIGN
LON 96020 01DIRECT
LON 96020 03ELLIOTT
LON 96020 02ACTIVE
NEW 96020 02INACTIVE
NEW 96020 01ADMIN
NEW 96020 03HOLECEK
SIN 96020 01ADMIN

what i would like to do is pull in only `codes` with a grpcode in (02active, 01direct). in the example above, i would only want the `lon` cmpcode to appear, since it`s both 01direct and 02active. since the grpcodes are on different lines, i`m not sure how to accomplish this. also, my key is cmpcode, code - not just code. here`s how i`ve been attempting to do it:

select
cmpcode,
code,
grpcode
from oas_grplist
where
elmlevel = 5 and
grpcode = `02ACTIVE` and
code in(select code from coda..oas_grplist where grpcode = `01direct`).

the problem with this is the subquery join is only based on joining code, and cmpcode needs to be included in the join.

any ideas?

thanks in advance, André

View 2 Replies View Related

I Need Help With A Subquery!

Sep 29, 2004

I have a SELECT statement with a subquery. I use an alias as I add the results of the subquery to the dataset. I then try to use the alias in the WHERE clause of the SELECT statement. I get an “Invalid column name “ message with this code:

select i.id as itemid,
(select top 1 ca2.itemid from itemassign ca2
inner join account a2 on ca2.accountid=a2.id
where a2.customerid=c.id and ca2.itemid=i.id)
as iaid
from item i
inner join customer c on i.customerid=c.id
where i.customerid=1 and iaid is null
order by i.id DESC


Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'iaid'.

If I run the statement without the and condition in the WHERE clause it returns a valid result.
Any input on this will be very appreciated!

Thank you,
IRead

View 1 Replies View Related

Need Help With Subquery

Jun 13, 2007

Sorry about my last post, it seemed to generate nothing but confusion. Hopefully I will explain the problem better this time.

Here are my tables with sample data:


Code:


abmtransmitter table:

Transmitter ID | Site_name | last_test_date | last_failed_test_date
A0001 Site01 2007-06-12 2007-06-10
A0002 Site02 2007-05-23 2007-06-06
A0003 Site03 2007-06-05 2007-06-12
A0004 Site04 2007-01-18 2007-05-18


AbmSignal Table:


Transmitter | Signal_id | Signal_date
A0001 trouble 2007-06-09
A0001 fail test 2007-06-10
A0001 test 2007-06-11
A0001 test 2007-06-12
A0002 test 2007-05-23
A0002 fail test 2007-05-30
A0002 fail test 2007-06-06
A0003 test 2007-06-05
A0003 fail test 2007-06-12
A0004 test 2007-01-18
A0004 fail test 2007-02-18
A0004 fail test 2007-03-18
A0004 fail test 2007-04-18
A0004 fail test 2007-05-18





I am trying to get a list of transmitters that have failed to send their scheduled communication test.
I only want a list of the transmitters who have failed two communications tests since the last successful test.
In the above data, the list would result with A0002 and A0004. A0001 passed it's most recent test, and A0003 has only failed one time since it's last successful test.
The following query does not look correct to me, but it does give me the results that *look* correct.
If it works, why does it work because I don't understand how the query on abmtransmitter is passing the value last_test_date to the subquery.
Or is this just a fluke and my result set looks correct but may not be?
'

Code:


Select Transmitter_id, Site_name from abmtransmitter where transmitter_id in
(select transmitter from abmsignal where signal_id = 'fail test' and signal_date > last_test_date
group by transmitter having count(transmitter) > 1) and last_failed_test_date > last_test_date Order by site_name

View 1 Replies View Related

Subquery

Aug 28, 2006

I have a subquery where I get 2 rows back which cause issues (since I can't return more then one). I am using this subquery in my function and I can't use a temp table in order to select the correct value. what other options do I have . My subquery returns 2 dates and I need to return from my function the max date.

View 1 Replies View Related

Doing LIKE On A Subquery

Apr 24, 2008

Hi

Im using sql server 2000 and I have sql statement that needs to do a LIKE statement from values from another table. An example would be the below

select Name, PostCode from Customers
where Post LIKE (select PartialPostCode + '%' from areas where area_arid = '123')

However if the above sub query returns more than one row then it will error. So I thought I would create a function to return a string such as the below and put it into vvariable

@strPostCodesLike = 'PostCode LIKE 'WS1 %' OR PostCode LIKE 'WS2 %'

And tried to execute the following SQL statement

select Name, PostCode from Customers WHERE @strPostCodesLike

However the above does not work, as I would need to use dynamic sql to get it to work. I cant use dynamic sql unfortunately.

Any help would be much appreciated

Many thanks in advance

View 2 Replies View Related

Sql Subquery

Aug 8, 2005

I am new to sql and i was reading about subquery and i think its the right tool for what i want to achieve
i have two tables
Products table, OrdersLine table
Products Table
ProdSku
ProdName
QOH
Cost
********
OrdersLine Table
OrderNum
ProdSku
Qty

I want to get the product Sku, Name, QOH, Cost and the Sum(Qty) from OrdersLine
this is what i have tried
SELECT dbo.Products.ProdSku AS Sku, dbo.OrdersLine.Qty AS Expr1
FROM dbo.Products INNER JOIN
dbo.OrdersLine ON dbo.Products.ProdSku = dbo.OrdersLine.ProdSku
WHERE (dbo.Products.ProdSku = '122345')
GROUP BY dbo.Products.ProdSku
please help!

View 9 Replies View Related

SubQuery

Mar 9, 2006

I am cofuse with subquery.HOW does subquery work. the inner or outer query exicute first. what are different type of sub query. plz give example. i am more confuse with exits subquery

View 3 Replies View Related

Subquery Help

Jul 20, 2006

I have this subquery that I'm trying to get info from the two seperate tables to show up, but I only get one or the other.

-- This report is for the DC. This report is to look at what items
-- come in a kit and what the inventory levels looks like at the
-- time the report is run. 07/18/06 mjg
SELECT I.ItemID, D.ShortDesc, KI.ItemID, KD.ShortDesc
FROM timKitCompList KL
INNER JOIN timItem I ON KL.CompItemKey = I.ItemKey
INNER JOIN timitemdescription D ON I.ItemKey = D.ItemKey
WHERE EXISTS
(SELECT KI.ItemID AS KitItemNo, KD.ShortDesc AS KitItemDesc
FROM timKit K
INNER JOIN timItem KI ON K.KitItemKey = KI.ItemKey
INNER JOIN timitemdescription KD ON KI.ItemKey = KD.ItemKey)

Here are the error messages that I get:
Server: Msg 107, Level 16, State 2, Line 4
The column prefix 'KI' does not match with a table name or alias name used in the query.
Server: Msg 107, Level 16, State 1, Line 4
The column prefix 'KD' does not match with a table name or alias name used in the query.

View 4 Replies View Related

Subquery? Or?

Jun 13, 2007

Hi guys!

I need help. I have two tables (customers & orders). I want to build a query that lists all the customers who haven't placed an order in over a year. Below are the simplified tables (i've removed other fields that I don't think are relevant to this query). Do I need to do a subquery or something? Please help!

TABLES:

CUSTOMERS
custid (unique autonumber)

ORDERS
custid (int)
orderdate (date)

View 3 Replies View Related







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