Transact SQL :: Subquery Another Table?

Apr 27, 2015

I have a table which is called PneumoniaCareBundleDiagnosisCodes with the fields DiagnosisCode, DiagnosisDesc

I have a another table called dbo_OP_APPOINTMENT_PROCEDURE_PIVOT

With fields Procedure01, Procedure02, Procedure03, Procedure04, Procedure05, Procedure06, Procedure07, Procedure08, Procedure09, Procedure10, Procedure11, Procedure12.

(for info purposes the relationship here is DiagnosisCode = Procedure01, 02, 03 etc)

Is it possible to right a query that shows all records in dbo_OP_APPOINTMENT_PROCEDURE_PIVOT where the DiagnosisCode in table PneumoniaCareBundleDiagnosisCodes appear in any of the Procedure01, 02, 03 fields etc.

If I was using an IF statement the logic i would right it as follows:
IF dbo_OP_APPOINTMENT_PROCEDURE_PIVOT.Procedure01
IS IN PneumoniaCareBundleDiagnosisCodes.DiagnosisCode OR
IF dbo_OP_APPOINTMENT_PROCEDURE_PIVOT.Procedure02

[Code] ......

View 5 Replies


ADVERTISEMENT

Transact SQL :: Get Max Value Using Subquery?

Nov 23, 2015

I have the below data and want to only show records where Response Column has Max date for the commencement date and expiry date under questions column.. For example for tenantcode 52090 the highest Tab value is 2 but this is not correct as there is no associated value in response.

We need to compare all the commencement and lease expiry dates and show only the commencement and lease expiry with the recent dates. Null should be ignored Instead of using Max Tab or Max Modified date would the below logic work? Not sure how to script this.

1. Filter to find Questions containing "Expiry Date"

2. summarise to find the max expiry date per Tenant Code

3. find which records have that maximum expiry

4. join again to find the commencement date

5. union the records from (3) and (4)

6. cross tab

Declare @rent Table
(
TenantCode CHAR(6)
,HHMID CHAR(5)
,Tab CHAR(4)
,FieldNo CHAR(4)
,FieldRowCHAR(10)

[code]....

View 29 Replies View Related

Transact SQL :: Subquery In WHERE

Aug 18, 2015

I have the following stored proc that I need to pull InsuranceID specific rows when @InsuranceID > 0 is sent.  Below is the code and I think the issue is in the 2nd WHERE condition.

ALTER PROCEDURE [dbo].[ms_selJobSetupSelections]
(@ActiveOnlybit = 1,
@InsuranceIDint = 0)
AS
BEGIN
SELECT J.JobSetupID
,J.JobSetupText

[code]....

View 21 Replies View Related

Transact SQL :: Aggregate In Subquery

Oct 22, 2015

(select SUM(sales.Total) from sales where StudentHist.Curdate = max(sales.curdate))  AS 'Balance'Iam trying to write a subquery to  calculate the total amount of sales until the Curdate  in studenthist equals the Curdate in sales table..how to write this query??

View 11 Replies View Related

Transact SQL :: How To Reuse Subquery

Jul 29, 2015

with c1 As (
select 1 As '1' , 2  As '2' , 3 As '3'

, c2 As (
select 4  As '4', 5  As '5',  6 As '6'
union all
select 1 , 2 ,3 from c1  -- >>>>>  select from c1 here 
) select * from c2 
  union all
  select * from c1 -- >>>>>> and select from c1 here 

According to the query above , I try to reuse the subquery by put  the subquery into 'with cte'  name (c1)  then i select this  2 times .

if I do this way , how many time this subquery (c1) execute ?
if 1 time then this is the right way to reuse this subquery .
if 2 times  , it is not then what should i do to reuse this subquery ?

View 3 Replies View Related

Transact SQL :: Use Like Command With Subquery

Jun 10, 2015

I am writing below query to pull from customer table.

select * from Customer where SrNo in (Select distinct SrNo from Orders)

This is doing an exact match of SrNo in Orders table SrNo is part of string and can occur at any place in that string. I want to use the like command.

Please see below example.

select
*
from Customer
where SrNo
like('%89898989%','%928hhst%')

View 2 Replies View Related

Transact SQL :: Left Join With Subquery

Aug 24, 2015

SELECT A.EmpId,A.IncidentDate
FROM EmployeePoints1 as A
WHERE IncidentDate=
(SELECT MAX(IncidentDate)
FROM EmployeePoints1
WHERE EmpId = A.EmpId) AND (DATEADD(day,28,DATEADD(WEEK, DATEDIFF(WEEK, 0,A.IncidentDate), 0)) < DATEADD(WEEK, DATEDIFF(WEEK, 0,GetDate()), 0)) AND (A.IncidentCode = 'I' OR A.IncidentCode = 'A')
LEFT JOIN EmployeeTotalPoints1 ON EmployeeTotalPoints1.EmpId = A.EmpId

I am trying to left join another table but  I got

Incorrect syntax near the keyword 'LEFT'.

View 9 Replies View Related

Transact SQL :: Using Aggregate Function With Subquery?

Aug 6, 2015

SSMS does not like mine!  THis is the error that I receive:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

And this is my syntax:

Select
employeeID
,COUNT(case when rehirestatus IN (select rehirestatus from regionalemptable where rtrim(storename) = 'Location1') THEN userID ELSE 0 END) +
COUNT(case when rehirestatus IN (select rehirestatus from globalemptable where rtrim(storename) = 'Location1') Then userID ELSE 0 End)
FROM production
GROUP BY employeeID
ORDER BY employeeID

View 6 Replies View Related

Transact SQL :: Adding Subquery As A Column

May 19, 2015

I have a subquery i wanted to add a as a fourth column to my  Original Query(is the one below the subquery). How to combine the two queries to one statement?? I tried but was getting an error "Subquery returned more than 1 value "

select  
COUNT(*)FreeReduced
 from students s join Buildings b on
 s.Building_ID = b.Building_ID
 where s.Activeness =1 and (Eligibility = 3 or Eligibility =2) 
 group by building_number,Building_Name

[Code] ....

View 3 Replies View Related

Transact SQL :: Get Subquery To Eliminate Malformed Date?

Jun 30, 2015

I have the following query.

SELECT a.Line_Number as Line_Number,
Cast(a.election_effective_date as DATE) as election_effective_date,
Cast(a.Plan_Year_Effective as DATE) as Plan_year_Effective
FROM (SELECT aa.* FROM TEMP_Validation aa WHERE IsDate(aa.Plan_Year_Effective) = 1 AND IsDate(aa.election_effective_Date) = 1) a
Where Cast(a.election_effective_date as Date) Not Between Cast(a.plan_year_effective as Date)
and DATEADD(DD,-1,DATEADD(YY,1,Cast(a.plan_year_effective as Date)))

There is a malformed date in the Temp data, at line 4932.  This is why I created a subquery that checks if the plan year and election effective dates are dates using the "IsDate" function.  However, when I execute this I get the error "Conversion failed when converting date and/or time from character string".  If I eliminate line 4932 the error no longer occurs.  Somehow line 4932 is not being eliminated in the subquery, except if I run JUST the subquery it will not include line 4932.  What am I doing wrong on these queries and how can I correctly get the subquery to eliminate the malformed date?

View 5 Replies View Related

Transact SQL :: Query Works Even If Column Not Exists In Subquery

Jul 23, 2015

When I execute the below queries it works perfectly where as my expectation is, it should break.

Select * from ChildDepartment C where C.ParentId IN (Select Id from TestDepartment where DeptId = 1)
In TestDepartment table, I do not have ID column. However the select in sub query works as ID column exists in ChildDepartment.  If I do change the query to something below then definately it will break -
Select * from ChildDepartment C where C.ParentId IN (Select D.Id from TestDepartment D where D.DeptId = 1)

Shouldn't the default behavior be otherwise? It should throw error if column doesnt exists in sub query table and force me to define the correct source table or alias name.

create table TestDepartment
(
DeptId int identity(1,1) primary key,
name varchar(50)
)
create table ChildDepartment
(
Id int identity(1,1) primary key,

[Code] ....

View 3 Replies View Related

Transact SQL :: Update Unique Records Count For Subquery?

Sep 2, 2015

updating the # of Payer from below query to match with the # of rows for each payer record. See the Current and desired results below. The query is currently counting the # of rows for all payers together and updating 3 as # of payers. I need it to count # of rows for each payer like shown inDesired result below. It should be showing 1 for first payer and 2 for 2nd & 3rd based on # of times each payer is repeated..

SELECT b.FILING_IND, b.PYR_CD, b. PAYER_ID, b. PAYER_NAME,a.CLAIM_ICN,
(Select Count(*) From MMITCGTD.MMIT_CLAIM a, MMITCGTD.MMIT_TPL b , MMITCGTD.MMIT_ATTACHMENT_LINK c where a.CLAIM_ICN_NU =
c.CLAIM_ICN and b.TPL_TS = c.TPL_TS and a.CLAIM_TYPE_CD = 'X' 

[Code] ....

Current Result

FILING_IND
PYR_CD
PAYER_ID
PAYER_NAME
CLAIM_ICN
#_OF_PAYER

[code]....

View 4 Replies View Related

Transact SQL :: Pull Records From 3 Tables Using Joins Or Subquery?

Sep 14, 2015

I have 3 tables.

Table 1:
ID  Name  Description
1  ABc      xyz
2  ABC      XYZ

Table 2:
RoleID   Role
1         Admin
2         QA

Table 3:
ID   RoleID  Time
1     1         09:14
2     1         09:15
1     2         09:16

Now I want all the records which belongs to RoleID 1 but if same ID is belongs to RoleID 2 than i don't want that ID.From above tables ID 1 belongs to RoleID 1 and 2 so i don't want ID 1.

View 4 Replies View Related

Transact SQL :: Retrieve Another Column (exchange Rate) From Particular Date For Subquery?

May 25, 2015

Below is the query in which i want to retrieve another column (exchange rate) from a particular date for the sub query. 

Actually PurchaseOrderDet table get records related to purchaseorder but for each row in purchaseorderdet need info from the same table for all rows on a particular date.

how i can achieve this query without using RANK() and other functions.

"SELECT  Supplier.Uniid AS SupplierID, Supplier.Name, PurchaseOrder.Uniid AS PurchaseID, PurchaseOrder.OrderNo, PurchaseOrder.FormDate, StockItem.Uniid AS StockID, StockItem.StockCode + N' - ' + StockItem.Description1 AS StockItem,
PurchaseOrderDet.ExchangeRate, PurchaseOrderDet.UnitPrice, PurchaseOrderDet.Discount, SUM(PurchaseOrderDet.OrderQty) AS SumOfOrderQty,

[Code] ....

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

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

Subquery On Same Table?

Mar 20, 2007

Can i have a query on table "POC" with a sub query on the same "POC" table?  Much like the code i have below:
dAdapter = new SqlDataAdapter("SELECT * FROM [Poc_" + suffix + "] WHERE (SELECT DISTINCT [CustomerLastName], [CustomerFirstName], [CustomerEmail] FROM [Poc_" + suffix + "])", cnStr);
 
when i go to build/run i get this error: An expression of non-boolean type specified in a context where a condition is expected, near ')'.
I'm trying to select all the columns of a row, where there are unique combos of [CustomerLastName],[CustomerFirstName],[CustomerEmail].
thanks!

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

1 Table Subquery With Group

Feb 5, 2015

I have a table that has Finance transactions in it. I want to find the last time a transaction was put in and the balance that was recorded for that last entry for each account.

The Table looks like this

CustomerCode, AccountID,BillDate,Balance

1,1234,2014-11-31,1000.00
1,1234,2014-12-31,900.00
2,1234,2014-10-30,2000.00
2,1234,2014-11-30,1500.00
3,4567,2013-10-30,2200.00
3,4567,2013-11-30,2000.00

I am trying to write a query statement that can show me this.

1,1234,2014-12-31,900.00
2,1234,2014-11-30,1500.00
3,4567,2013-11-30,2000.00

Once I have this part working I actually need to make it a sub-query for more customer information from another table.

View 9 Replies View Related

SubQuery Or Temp Table?

Jul 23, 2005

We were trying to remove duplicates and came up with two solutions.One solution is similar to the one found in a book called "AdvancedTransact-SQL for SQL Server 2000" by Ben-Gan & Moreau. This solutionuses temp tables for removing duplicates. A co-worker created adifferent solution that also removes duplicates, but the other solutionuses subqueries instead of temp tables.Theorhetically, which solution would result in faster performance withlarge tables? Would using temp tables peform faster when the sourcetable has 100,000 records, for example, or would the subquery functionmore quickly in that situation?

View 3 Replies View Related

How To Get Rows Which Are Not In Another Table Using Subquery

Oct 13, 2015

i have two tables Student  and Daily Attendance with following structure ,as i want to extract students of a class order by roll number which are not in Daily Attendance table , i know it will be solved by subquery but I don't know how to solve it.

Student:-

CREATE TABLE [dbo].[Student](
[Student_Id] [bigint] IDENTITY(1,1) NOT NULL,
[Course_Id] [smallint] NULL,  //Foreign key
[Class_Id] [int] NULL,  //Foreign key
[Batch_Year] [varchar](20) NULL,
[Student_Initials] [varchar](20) NULL,

[code]....

View 2 Replies View Related

USIG SUBQUERY IN 3 TABLE

Jun 2, 2007

Hello, I need help because I may have either mental or Jennt


My question is that I have three tables CONTAIN OF

EMPLYEES TABLE:




EMP ID

EMP LAST NAME

ORDERS TABLE:



EMP ID

ORDER ID

ORDERS DITEALS:



ORDER ID

PRODUCT ID

UNIT PRICE

COUNTUTY

WHAT I NEED
The names of all the required staff who supervised every request so that the total quantity * price not greater than 1000


I NEED HELP IN THAT AS FAST AS ANY ONE READ MY Q
GREAT THANKS FOR ANY HELP

OH I FORGOT THIS IS WHAT I DID



elect EmployeeID,LastName

from dbo.

where Employees.EmployeeID IN

(select orderid,employeeid

from dbo.Orders as ord

where Employees.EmployeeID=ord.employeeid and ORD.orderid) in

(select orderid , sum(UnitPrice*Quantity) total

from dbo.[Order Details] as ords

group by orderid

having sum(UnitPrice*Quantity)>1000)



I KNOW THAT THERE IS SOMTHING NOT WRIGHT

View 4 Replies View Related

Retrieve Data From Another Table In Subquery

Apr 11, 2004

Hi there, here is my current query:

sqlTemp = "SELECT id,code,description FROM tbl_content " &_
"WHERE EXISTS " &_
"(SELECT * FROM tbl_published_content " &_
"WHERE tbl_content.id = tbl_published_content.id ORDER BY tbl_published_content.nCorrectOrder)"


I don't get results sorted by tbl_published_content.nCorrectOrder, and have also no iea how to retrieve that values.

Please can any one tell me how can I have access to tbl_published_content.nCorrectOrder and get it sorted by this field?

So I can use objRS.("tbl_published_content.nCorrectOrder") or some alias?

thanks a million!

View 2 Replies View Related

Subquery Max Disconnect Date Within Table

Sep 12, 2014

I've written a query calling for the max disconnect date within a table, but I would also like to make sure to only retrieve records with the most recent connect date. I'm unsure how to go about adding the additional max date function to my query. Here's what I have written:

select distinct T.PRIN_MON, T.AGNT_MON, T.SUB_ACCT_NO_MON, T.TRAN_DTE_MON, T.TRAN_CDE_MON,
T.TRAN_AMT_MON, EQ.eqp_stat_eqp,
case when h.acct_stage_ohi = 'v' then 'VOL_DISCO'
when h.ACCT_STAGE_OHI = 'n' then 'NON_PAY_DISCO'
ELSE '' END AS 'CUSTOMER_STATUS',

[Code] ....

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

How To Get And Use A Plausible Subquery To Retrieve Data Of Some Columnns Of Dbo.Table And Put Them In A New DboTable?

Jan 31, 2008

Hi all,

I have 2 Tables "dbo.Samples" and "dbo.TestResults" listed below:
dbo.Samples:
SampleID SampleName Matrix SampleType ChemGroup ProjectID




1
Blueriver01
Water
Primary
VOCs
1

2
Blueriver02
Water
Duplicate
VOCs
1

3
Blueriver03
Water
QA
VOCs
2

4
Blueriver11
Soil
Primary
VOCs
1

5
Blueriver12
Soil
Duplicate
VOCs
1

6
Blueriver13
Soil
QA
VOCs
3
where SampleID is Primary key in this table.


dbo.TestResults:
AnalyteID AnalyteName Result Unit SampleID



1
Acetone
120.800
ug/L
1

2
Benzene
25.600
ug/L
1

3
Trichloroethene
13.000
ug/L
1

4
Xylenes
0.000
ug/L
1

5
Acetone
90.700
ug/L
2

6
Benzene
31.400
ug/L
2

7
Trichloroethene
19.200
ug/L
2

8
Xylenes
2.000
ug/L
2

9
Acetone
140.300
ug/L
3

10
Benzene
21.500
ug/L
3

11
Trichloroethene
22.200
ug/L
3

12
Xylenes
0.000
ug/L
3

13
Acetone
222.100
ug/Kg
4

14
Benzene
10.300
ug/Kg
4

15
Trichloroethene
30.200
ug/Kg
4

16
Xylenes
50.700
ug/Kg
4

17
Acetone
211.900
ug/Kg
5

18
Benzene
16.400
ug/Kg
5

19
Trichloroethene
34.700
ug/Kg
5

20
Xylenes
60.000
ug/Kg
5

21
Acetone
220.300
ug/Kg
6

22
Benzene
13.200
ug/Kg
6

23
Trichloroethene
32.000
ug/Kg
6

24
Xylenes
55.500
ug/Kg
6

NULL
NULL
NULL
NULL
NULL

where AnalyteID is Primary key and SampleID is Foreign key in this table.

Note: The relationship between "dbo.Samples" and "dbo.TestResults" has been established.


============================================
I want to get a new T-SQL output "dbo.Report" like:

SampleID SampleName Unit Acetone Benzene Trichloroethene Xylenes
1 Blueriver01 ug/L 120.800 25.600 13.000 0.000
2 Blueriver02 ug/L 90.700 31.400 19.200 2.000
3 Blueriver03 ug/L 140.300 21.500 22.200 0.000
4 Blueriver11 ug/Kg 222.100 10.300 30.200 50.700
5 Blueriver12 ug/Kg 211.900 16.400 32.000 60.000
6 Blueriver13 ug/Kg 220.300 13.200 32.000 55.500

I want to get the first 2 columnns from the "dbo.Samples" table and the 3rd, 4th, 5th, 6th, and 7th columnns from the "dbo.TestResults" table. I think I can create a new "dbo.Report" table with the 7 Columnn Names, and retrieve the data of SampleID and SampleName from the "dbo.Samples" table and put them into the "dbo.Report" table. But I do not know how to retrieve the data of Unit, Acetone, Benzene, Trichloroethene, and Xylenes from the "dbo.TestResults" table and put them into the "dob.Report" table formatted and presented in the above blue-colored table. The following is my T-SQL programming plan:
-- Create a new table called "Report"
CREATE TABLE Report
(
SampleID int,
SampleName nvarchar(25),
Unit nvarchar(25),
Acetone decimal(9,3),
Benzene decimal(9,3),
Trichloroethene(9,3),
Xylenes decimal(9,3),
);

-- Insert the data of SampleID and SampleName from dbo.Samples --
SELECT SampleID, SampleName
FROM dbo.Samples

-- Insert the data of Unit, Acetone, Benzene, Trichloroethene, and Xylenes from dbo.TestResults --
I guess I may be able to use the following code:
INSERT INTO dbo.Reort(Unit, Acetone, Benzene, Trichloroethene, Xylenes)
SELECT x????
FROM y????
WHERE z????
(SELECT xxx??
FROM yyy??
WHILE zzz='##??")
GO

I do not know how I can get and use the above planned "subquery" correctly to get the data I want!!?? Please help and give me a delaied instructions or direction to achieve this task.

Thanks in advance,
Scott Chang

View 16 Replies View Related

Correlated Subquery - Column Prefix 'OJ' Does Not Match With A Table Name Or Alias Name Used In The Query.

Feb 2, 2007

I have data in a table (@Outer) that I am matching to a lookup table (@Inner) which contains multiple "matches" where nulls can match any value. By sorting the inner table and grabbing the top record, I find the "best" match. I know the sort and the null matches work but I don't understand why the correlated sub query below doesn't understand that the OJ prefix refers to the outer table.DECLARE @Outer TABLE (
OuterID int IDENTITY (1, 1) NOT NULL,
MethodID int NULL,
CompID int NULL,
FormID int NULL,
InnerID int NULL
)

INSERT @Outer VALUES (2, 2, 2, NULL) -- OuterID = 1
INSERT @Outer VALUES (3, 2, 1, NULL) -- OuterID = 2

DECLARE @Inner TABLE (
InnerID int IDENTITY (1, 1) NOT NULL,
MethodID int NULL,
CompID int NULL,
FormID int NULL
)

INSERT @Inner VALUES (2, null, null) -- InnerID 1
INSERT @Inner VALUES (2, null, 1) -- InnerID 2
INSERT @Inner VALUES (2, 2, null) -- InnerID 3

INSERT @Inner VALUES (3, null, null) -- InnerID 4
INSERT @Inner VALUES (3, 2, null) -- InnerID 5

INSERT @Inner VALUES (4, 2, 1) -- InnerID 6


-- UPDATE Outer Table with best match from Inner table
UPDATE @Outer SET
InnerID = IJ.InnerID
FROM @Outer OJ
INNER JOIN
(
SELECT TOP 1 I.*
FROM @Inner I
WHERE IsNull(I.MethodID, OJ.MethodID) = OJ.MethodID
AND IsNull(I.CompID, OJ.CompID) = OJ.CompID
AND IsNull(I.FormID, OJ.FormID) = OJ.FormID
ORDER BY I.MethodID DESC, I.CompID DESC, I.FormID DESC
) IJ ON OJ.MethodID = IsNull(IJ.MethodID, OJ.MethodID)
AND OJ.CompID = IsNull(IJ.CompID, OJ.CompID)
AND OJ.FormID = IsNull(IJ.FormID, OJ.FormID) SELECT * FROM @Outer
The result should be OuterID 1 matched to Inner ID 3 and OuterID 2 matched to Inner ID 5.
Can anyone help me? Thanks in advance.

View 6 Replies View Related

Random Selection From Table Variable In Subquery As A Column In Select Statement

Nov 7, 2007

Consider the below code: I am trying to find a way so that my select statement (which will actually be used to insert records) can randomly place values in the Source and Type columns that it selects from a list which in this case is records in a table variable. I dont really want to perform the insert inside a loop since the production version will work with millions of records. Anyone have any suggestions of how to change the subqueries that constitute these columns so that they are randomized?




SET NOCOUNT ON


Declare @RandomRecordCount as int, @Counter as int
Select @RandomRecordCount = 1000

Declare @Type table (Name nvarchar(200) NOT NULL)
Declare @Source table (Name nvarchar(200) NOT NULL)
Declare @Users table (Name nvarchar(200) NOT NULL)
Declare @NumericBase table (Number int not null)

Set @Counter = 0

while @Counter < @RandomRecordCount
begin
Insert into @NumericBase(Number)Values(@Counter)
set @Counter = @Counter + 1
end


Insert into @Type(Name)
Select 'Type: Buick' UNION ALL
Select 'Type: Cadillac' UNION ALL
Select 'Type: Chevrolet' UNION ALL
Select 'Type: GMC'

Insert into @Source(Name)
Select 'Source: Japan' UNION ALL
Select 'Source: China' UNION ALL
Select 'Source: Spain' UNION ALL
Select 'Source: India' UNION ALL
Select 'Source: USA'

Insert into @Users(Name)
Select 'keith' UNION ALL
Select 'kevin' UNION ALL
Select 'chris' UNION ALL
Select 'chad' UNION ALL
Select 'brian'


select
1 ProviderId, -- static value
'' Identifier,
'' ClassificationCode,
(select TOP 1 Name from @Source order by newid()) Source,
(select TOP 1 Name from @Type order by newid()) Type

from @NumericBase



SET NOCOUNT OFF

View 14 Replies View Related

Transact SQL :: How To Alter Existing Table Column As Identity Without Dropping Table

Nov 20, 2013

I have created a table as below mentioned. Then I want to alter the ID column as identity(1,1) without dropping the table as well as losing the data.

create table dbo.IdentityTest
(
id int not null,
descript varchar(255) null,
T_date datetime not null
)

View 7 Replies View Related

Transact SQL :: Verify Inserted Values From One Table (in CSV File) With Another Table (in Database)

Aug 4, 2015

I am looking for a Sql query to verify the inserted values from one table(in CSV file) with another table(in sql database)

For example: I have below Values column that is present in once CSV file, after my data migration the values get stored in Results table under Message column.

I need to very whether values(1X,1Y) are inserted in Message record "successfully inserted value 1X"

Values (CSV)
1X
1Y

Results Table(SQL)
CreatedDate                   Message
2015-08-04 08:45:29.203  successfully inserted value 1X
2015-08-04 08:44:29.103  TEst pass
2015-08-04 08:43:29.103  successfully inserted value 1X
2015-08-04 08:42:29.203  test point
2015-08-04 08:35:29.203  successfully inserted value 1Y
2015-08-04 08:30:29.203  Test Pass
2015-08-04 08:28:29.203  successfully inserted value 1Y

If all values are inserted:

Output:
All values from values table are inserted successfully
Total count of values inserted: 2
If only few values are inserted, example only 1X from Values table is inserted in Message

Example:
Results Table CreatedDate     Message
2015-08-04 08:45:29.203  successfully inserted value 1X
2015-08-04 08:44:29.103  TEst pass
2015-08-04 08:43:29.103  successfully inserted value 1X
2015-08-04 08:42:29.203  test point

Output:
All values from values are not inserted successfully in result table.
Total count of values inserted: 1
Missing Values not inserted in results table are: 1Y

View 3 Replies View Related

Transact SQL :: Update Table With Its Value And Data From Row In Temp Table For Matching Record?

Oct 25, 2015

I have a temp table like this

CREATE TABLE #Temp
 (
  ID int,
  Source varchar(50),
  Date datetime,
  CID varchar(50),
  Segments int,
  Air_Date datetime,

[code]....

Getting Error

Msg 102, Level 15, State 1, Procedure PublishToDestination, Line 34 Incorrect syntax near 'd'.

View 4 Replies View Related







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