Selection From Sorted Subquery Is Unsorted In SQL Server 2005

Jun 14, 2007

I have some relatively simple SQL that acts differently between SQL Server 2000 and 2005. Although it is easy to fix I'd like to know if this difference is expected (documented) or a bug, and if there is perhaps a setting/switch I can use to avoid a code review of hundreds of stored procs to look for similar scenarios.


Executed the following script in SQL Server 2005 –

CREATE TABLE #Floats
(
FloatID INT IDENTITY,
FloatNumber FLOAT NOT NULL
)

DECLARE @sngCounter float
SET @sngCounter = 20
WHILE @sngCounter >= 0
BEGIN
INSERT INTO #Floats ( FloatNumber ) VALUES( @sngCounter )
SET @sngCounter = @sngCounter - 1
END
SELECT * FROM (SELECT TOP 100 PERCENT * FROM #Floats ORDER BY FloatNumber) AS FloatNumbers

DROP TABLE #Floats
GO

Produces the following resultset –
FloatID FloatNumber
----------- -----------
1 20
2 19
3 18
4 17
5 16
6 15
7 14
8 13
9 12
10 11
11 10
12 9
13 8
14 7
15 6
16 5
17 4
18 3
19 2
20 1
21 0

In SQL Server 2000 resultset is this –
FloatID FloatNumber
----------- --------
21 0.0
20 1.0
19 2.0
18 3.0
17 4.0
16 5.0
15 6.0
14 7.0
13 8.0
12 9.0
11 10.0
10 11.0
9 12.0
8 13.0
7 14.0
6 15.0
5 16.0
4 17.0
3 18.0
2 19.0
1 20.0

View 4 Replies


ADVERTISEMENT

Unsorted Primary Key Column In SQL Server Database

Oct 25, 2007

Update: Changed original post as I figured it was not the problem I stated. 
Hi all,
Heres the problem. I have a table in SQL Server with two fields, PartSubCategory and PartCatID. PartSubCategory is the primary key. When I import an excel sheet with identical columns into this table, the primary key column in the table gets sorted automatically (alphabetically). I don't want this column  sorted but to import the rows from excel in the order as they were. Is this some indexing issue? Is there a fix?
Thanks a lot...Bullpit

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

Correlated Subquery - Sql Server 2000 Verses Sql Server 2005

Nov 14, 2006

Original code (works in Sql Server 2000 but has error in Sql Server 2005) --
AND A_ED.EFFDT <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10))

Error message in Sql Server 2005 --
Server: Msg 8180, Level 16, State 1, Line 38
Statement(s) could not be prepared.
Server: Msg 107, Level 16, State 1, Line 38
The column prefix 'Tbl1001' does not match with a table name or alias name used in the query.

Corrected code --

AND SUBSTRING(CONVERT(CHAR,A_ED.EFFDT,121), 1, 10) <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10))

View 10 Replies View Related

MS SQL Server 2000: Rows Get Sorted Automatically

Feb 6, 2008

Hi all,

I import MS Excel 2003 spread sheet in MS SQL Server 2000 through MS SQL Server 2000 Enterprise Manager (rightclick on the table to be filled with dataall taskimport data). My excel file have 2000 rows and 100 columns of data. All the data are imported in relevant attributes cells in good manner. But the rows are sorted automatically. I am trying to say that first row data is match with my excel file. But second row data have gone to 7th row and 7th row have gone to 5th row like that. I need the data sequence what I have in my excel file. What is the problem occurred? How can I solve this?
Can I export my MS Excel 2003 file to MS SQL Server database?
Please help me. I don't have more knowledge in MS SQL Server 2000.
If your answer has any query to run then please mention where should I run that query.
Thanks,

With Regards,
bala.

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

SQL 2005 SubQuery Help - TOP 1

May 5, 2008

I needed to pull the top/most recent record only for these fields below. So I created multiple subquerys with the TOP 1 and Order By DESC in them (please see full query below). I unfortunately still get my records back as if the subquery's never got created. I am stumped. Any ideas?

/* Sliding Fee*/
SFEffectiveDate = cpsfh.SFEffectiveDte,
FamilySize = cpsfh.FamilySize,
MonthlyIncome = Convert(Money,ISNULL(cpsfh.MonthlyIncome,0)),
AnnualIncome = Convert(Money,IsNull(cpsfh.MonthlyIncome*12,0)),
NoIncome = CASE WHEN cpsfh.NoIncome = 0 THEN 'No' ELSE 'Yes' END,
SlidingFeeClass = ISNULL(ccml.description,'None'),
SlidingFeeCarrier = ic2.Listname,
FormOfDeclaration = ISNULL(ccml2.description,'(None)'),
LastModifiedBy = cpsfh.lastmodifiedby,
LastModifiedDate = cpsfh.lastmodified,
/*End Sliding Fee*/


My Query:

/* Patient Insurance List */

SET NOCOUNT ON
SELECT dbo.FormatName(pp.Prefix, pp.First, pp.Middle, pp.Last, pp.Suffix) AS Name,
pp.Address1 AS [Patient Address 1],
pp.Address2 AS [Patient Address 2],
pp.City + ', ' + pp.State + ' ' + pp.Zip AS [Patient Address 3],
g.[Last] + ', ' + g.[First] AS [Guarantor Name],
g.Address1 AS [Guarantor Address 1],
g.Address2 AS [Guarantor Address 2], g.City + ', ' + g.State + ' ' + g.Zip AS [Guarantor Address 3],
pp.PatientSameAsGuarantor,
pi.OrderForClaims AS [Order For Claims],
ISNULL(pi.[Last] + ', ' + pi.[First], '0') AS [Other Name],
pi.Address1 AS [Other Address 1],
pi.Address2 AS [Other Address 2],
pi.City + ', ' + pi.State + ' ' + pi.Zip AS [Other Address 3],
ic.ListName AS [Insurance Carrier],
ISNULL(pi.InsuredId, ' ') AS [Insured ID],
/* Sliding Fee*/
SFEffectiveDate =(SELECT TOP 1 cpsfh.SFEffectiveDte ORDER BY cpsfh.SFEffectiveDte DESC),
FamilySize = (SELECT TOP 1 cpsfh.FamilySize ORDER BY cpsfh.FamilySize DESC),
MonthlyIncome = (SELECT TOP 1 Convert(Money,ISNULL(cpsfh.MonthlyIncome,0))ORDER BY cpsfh.MonthlyIncome DESC),
AnnualIncome = (SELECT TOP 1 Convert(Money,IsNull(cpsfh.MonthlyIncome*12,0))ORDER BY cpsfh.MonthlyIncome*12 DESC),
NoIncome = (SELECT TOP 1 CASE WHEN cpsfh.NoIncome = 0 THEN 'No' ELSE 'Yes' END ORDER BY cpsfh.NoIncome DESC),
SlidingFeeClass = (SELECT TOP 1 ISNULL(ccml.description,'None')ORDER BY ccml.description DESC),
SlidingFeeCarrier = (SELECT TOP 1 ic2.Listname ORDER BY ic2.Listname DESC),
FormOfDeclaration = (SELECT TOP 1 ISNULL(ccml2.description,'(None)')ORDER BY ccml2.description DESC),
LastModifiedBy = (SELECT TOP 1 cpsfh.lastmodifiedby ORDER BY cpsfh.lastmodifiedby DESC),
LastModifiedDate = (SELECT TOP 1 cpsfh.lastmodified ORDER BY cpsfh.lastmodified DESC),
/*End Sliding Fee*/
ISNULL(dbo.formatphone(pp.phone1,1),'') AS Phone,
ISNULL(pp.Phone1Type, ' ') AS [Phone Type],
ig.Name AS InsuranceGroup,
df.ListName AS Doctor,
dff.ListName AS Facility,
ml.Description AS FinancialClass

FROMPatientProfile pp
JOIN PatientInsurance pi ON pp.PatientProfileId = pi.PatientProfileId
JOIN Guarantor g ON pp.GuarantorId = g.GuarantorId
JOIN InsuranceCarriers ic ON pi.InsuranceCarriersId = ic.InsuranceCarriersId
LEFT JOIN InsuranceGroup ig ON ic.InsuranceGroupId = ig.InsuranceGroupId
LEFT JOIN MedLists ml ON pp.FinancialClassMId = ml.MedListsId
LEFT JOIN DoctorFacility dff ON pp.FacilityId = dff.DoctorFacilityId
LEFT JOIN DoctorFacility df ON pp.DoctorId = df.DoctorFacilityId
LEFT JOIN cusPatientSlidingFeeHst cpsfh ON pp.PatientProfileId = cpsfh.PatientProfileID
LEFT JOIN cusCRIMedLists ccml ON cpsfh.slidingfeeclass = ccml.medlistsid
LEFT JOIN InsuranceCarriers ic2 ON cpsfh.SFCarrierID = ic2.InsuranceCarriersId
LEFT JOIN cusCRIMedLists ccml2 ON cpsfh.SFFormOfDeclarationMID = ccml2.MedListsId

WHERE --Filter on doctor
(
(NULL IS NOT NULL AND pp.DoctorId IN (NULL)) OR
(NULL IS NULL)
)
AND
(
(NULL IS NOT NULL AND pp.FacilityId IN (NULL)) OR
(NULL IS NULL)
)
AND --Filter on Insurance Carrier
(
(NULL IS NOT NULL AND pi.InsuranceCarriersId IN (NULL)) OR
(NULL IS NULL)
)
AND --Filter on Insurance Group
(
(NULL IS NOT NULL AND ic.InsuranceGroupId IN (NULL)) OR
(NULL IS NULL)
)

ORDER BY dbo.FormatName(pp.Prefix, pp.First, pp.Middle, pp.Last, pp.Suffix)

View 8 Replies View Related

Subquery Help Needed. SQL 2005

Jan 20, 2008

I am getting the following error in SQL2005. I need some assistance with adding in a Subquery.

Msg 207, Level 16, State 1, Line 33
Invalid column name 'LastVisitDate'.
Msg 207, Level 16, State 1, Line 34
Invalid column name 'LastVisitDate'.

/* Patient List*/
SET NOCOUNT ON

DECLARE @Zip varchar(40)
SELECT @Zip = LTRIM(RTRIM('NULL')) + '%';
WITH cteMedlitsPatientStatus AS
(
SELECT * FROM Medlists WHERE TableName = 'PatientProfileStatus'
)

SELECT
PatientID, RespSameAsPatient=isnull(PatientSameAsGuarantor,0),
PatientName=CASE
WHEN RTRIM(pp.Last + ' ' + ISNULL(pp.Suffix,'')) <> '' THEN
RTRIM(RTRIM(pp.Last + ' ' + ISNULL(pp.Suffix,'')) + ', ' + ISNULL(pp.First,'') + ' ' + ISNULL(pp.Middle,''))
ELSE RTRIM(ISNULL(pp.First,'') + ' ' + ISNULL(pp.Middle,''))
END,
PatientAddr1=pp.Address1, PatientAddr2=pp.Address2,
PatientCity=pp.City, PatientState=pp.State, PatientZip=pp.Zip,
PatientRespName=CASE
WHEN RTRIM(pr.Last + ' ' + ISNULL(pr.Suffix,'')) <> '' THEN
RTRIM(RTRIM(pr.Last + ' ' + ISNULL(pr.Suffix,'')) + ', ' + ISNULL(pr.First,'') + ' ' + ISNULL(pr.Middle,''))
ELSE RTRIM(ISNULL(pr.First,'') + ' ' + ISNULL(pr.Middle,''))
END,
PatientRespAddr1=pr.Address1, PatientRespAddr2=pr.Address2, PatientRespCity=pr.City,
PatientRespState=pr.State, PatientRespZip=pr.Zip, FinancialClass=isnull(ml.Description,'none'),
Doctor=df.ListName,Facility=df1.OrgName,Balance=isnull(ppa.PatBalance,0)+isnull(ppa.InsBalance,0), pp.DeathDate,
Status = ml1.Description,
pp.BirthDate,
(select top 1 visit
from patientvisit pv
where
LastVisitDate >= ISNULL(NULL,'1/1/1900') and
LastVisitDate < dateadd(d, 1,ISNULL(NULL,'1/1/3000')) AND
pp.patientprofileid = pv.PatientProfileID
and datediff(day, getDate(), visit) < 0
order by visit desc) as LastVisitDate

FROM PatientProfile pp
LEFT JOIN PatientProfileAgg ppa ON pp.PatientProfileID = ppa.PatientProfileID
LEFT JOIN Guarantor pr ON pp.GuarantorID = pr.GuarantorID
LEFT JOIN MedLists ml ON pp.FinancialClassMID = ml.MedListsID
LEFT JOIN DoctorFacility df ON pp.DoctorID = df.DoctorFacilityID
LEFT JOIN DoctorFacility df1 ON pp.FacilityId = df1.DoctorFacilityID
LEFT JOIN cteMedlitsPatientStatus ml1 ON pp.PatientStatusMId = ml1.MedlistsId

WHERE ...... etc, etc, etc

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

Cant Get The Result Sorted

Apr 13, 2008

Hi guys,
The result of my query I am not able to get it sorted by months.Here is my query & the output.


declare @tbl as table(date datetime,amt int)
insert into @tbl
select '2-jan-2008',100 union all
select '15-jan -2008',200 union all
select '20-jan -2008',500 union all
select '12-jan-2008',300 union all
select '02-feb-2008',100 union all
select '09-feb-2008',250 union all
select '03-mar-2008',500 union all
select '05-mar-2008',800

select Months,SumAmt,MaxAmt,MinAmt from
(
select datename(mm,date)as Months,sum(amt)as SumAmt,min(amt)as MinAmt,max(amt)as MaxAmt,row_number()
over(partition by datename(mm,date) order by datename(mm,date))as rowid from @tbl
group by datename(mm,date)
)t

The result is

Months SumAmt MaxAmt MinAmt
------------------------------ ----------- ----------- -----------
February 350 250 100
January 1100 500 100
March 1300 800 500


I want to get it sorted month wise i.e Jan,Feb,March.But I cannot find a way

View 2 Replies View Related

How To Get The First Row Of A Sorted List

May 14, 2007

Hi,

I am a newbie so this might be a very basic question. I have a table that not sorted. So I write a query to sort the table like this

Select * from custInfo where custID <> '0' order by custID Desc

Now obviously I have a selection of the original table in desc order. Now I want to get the first custId from thid Desc selection. How do I do this.

So if the unsorted table looked like this

001 Martha
005 Steve
002 Mike
003 David

and the sorted selection looks like this

005 Steve
003 David
002 Mike
001 Martha

And then I want to select Steve's custID which is 005. how do i do this.

Thanks in advance.

View 2 Replies View Related

Sorted Input

Mar 17, 2006

If a component requires a sorted input it would seem reasonable that you can check the IsSorted property of the attached input, but this will always return false. I have tried this when connecting the output of the Sort transform to my component, and then check the IsSorted property for this input. It is always false. How can this be, and also how can I see if the path is indeed sorted?

If using a virtual input column in my UI, I get a SortKeyPosition on the columns, but when overriding SetUSageType in the component class I always get zero for the key. Why is the sort information not quite there for me?

View 8 Replies View Related

SQL Mgmt Server: Run Selection Vs Entire Tab

May 3, 2007

Has anyone here been having issues where SQL Server Management Server will sometimes ignore selected text and run all scripts on the current tab?

This has been happening most recently after a connection times out or is forced shut. From a disconnected tab, if I add "Use Master" at the bottom of a page full of script, it will often run ALL statements starting from the first line.

I have SP2 installed which rolls management server to 9.00.2047.00 - but this has been an issue for me even before SP1 & SP2.

I can find nothing in the knowledge base regarding this, but perhaps my search string wasn't very thorough.

I'd just like to know if others are experience this issue so I can report to MS.

Thanks.

View 3 Replies View Related

Keeping Tables Sorted

Nov 28, 2003

we have a simple table

Key, Name, Address, City, State, Zip ................ect

I would like to keep this table sorted by Name, theirfore I won't have to sort my results with every querry.

I think I need to add something to my insert to tell my table - "Hay take Jones", open up the prober place and stick him in the proper spot.

Ex: We have Appleby and Robertson in our table now. My insert would tell SQL Server to take Jones, figure our where he belongs (alpha), and stick him in, resulting in.

Appleby
Jones
Robertson

This way I wont have to as the querry to sort stuff every time I reference this table, this will save lots and lots of overhead. and help keep my clients happy with quick(er) response.

thanks in advance -arthur

View 3 Replies View Related

Retrieving Sorted Data

Jul 18, 2005

I have four tables that need to be loaded into an ASP.NET application. They need to be loaded together into one result set and sorted. Is it possible to load four tables together and sort them using an SQL statement?

To clarify, say I have the following data:

Table1: Anglesey, Cardiff, Ceredigion
Table2: London, Dorset, Lancashire
Table3: Antrim, Armagh
Table4: Glasgow, Berwick, Edinburgh

I'd want the data retrieved from all four tables and sorted so that the data retrieved would be:

Anglesey, Antrim, Armagh, Berwick, Cardiff, Ceredigion, Dorset, Edinburgh, Glasgow, Lancashire, London

I am aware of and am using the SELECT ... ORDER BY feature of MSSQL in my present ASP.NET application to retrieve from single database tables. I'm using merged datasets and a sort method to solve the above problem at the moment.

View 9 Replies View Related

Concatentate Sorted Strings

Aug 2, 2006

Hi All,

I'm new to SQL Server.

I have the following table in a database of SQL Server 2005 Express.

ColA ColB
----- -----
A 12
A 10
B 50
B 13

What I want to achieve is the following result :

Col A Aggr
----- ------
A 2,12
B 13, 50

I tried the following query :

SELECT ColA, dbo.Concatenate(ColB) as Aggr
FROM
(SELECT TOP(100) PERCENT ColA, ColB
FROM TABLE_A
ORDER BY ColB) AS Derived_A
GROUP BY ColA

where Concatenate is the CLR User-defined aggreate function written in C#.

What I want to do is to first sort the rows on ColB and then to execute aggregate function over the sorted rows so as to get the above-mentioned results. However, what I got is the following

Col A Aggr

----- ------

A 2,12

B 50,13 -- not sorted

I learnt from the SQL Server documentation that even though the ORDER BY clause is presented in the subquery, the query result is not guaranteed to be sorted. Only ORDER BY clause used in the outer query should work. So, how should this problem be solved? One way of which I'm thinking is to do the sorting in the aggregate function, but I'm worrying if this is harmful to the performance. Could anyone help me to solve the problem?

Thanks!

Regards,
Nathan





View 3 Replies View Related

Retrieving Logged In Name For Data Selection From SQL Server

Mar 27, 2007

I have a login name being displayed when a user logs in, like so: "Welcome: johndoe23"This is displayed through the use of the <asp:LoginName> tag.I want to do a query on the database that only selects data relevant to that userName and wish to assign that logged in username to a variable so we can use an SQL command similar to: "SELECT something WHERE userID=" + loggedInUserName; 

View 2 Replies View Related

Find Next Entries Value (as Sorted By Date)

Jul 29, 2015

In the database I am querying, there is a field called "group". I can find out when "group" changes with a time field that was logged whenever group changes. I am trying to find what the value was changed into.

Code:
SELECT
Assignment_Log.DBID,
Assignment_Log.Assigned_Group,
Assignment_Log.Submit_Date
FROM Assignment_Log

This will tell me:

The unique ID of the database
The group it was assigned FROM
The time the assignment took place

I need to find the assignment TO

so what I need to do for the last column is something along the lines of...

Find the next record after the current record by looking at the next Submit_Date and view the Assigned_Group.

If no "next record" can be found, leave the cell empty.

is this possible?

View 2 Replies View Related

Join Tables On Sorted Values

Nov 19, 2013

Is there a way to join tables that have multiple matches to each other (2 records in one table and 2 in another) so that you get 2 records returned instead of 4 with only 1 JOIN ON qualifier?

In our warehouse DB, there is a master location table, an inventory location table, and physical table for counting all product in the warehouse. The master location table has one record per location, but there could be multiple items in that location so my outer join from the master location to the inventory table returns something like:

select M.MASTER_LOC, C.AS ORIG_ITEM, C.ORIG_LOT, C.ORIG_QTY
from
M_LOC M LEFT OUTER JOIN
C_INVT C ON M.MASTER_LOC = C.INVT_LOC
order by M.LOC_CODE

LOCATION ITEM LOT QTY
01-01-A 100 abc 25
01-02-A NULL NULL NULL
01-03-A 200 def 50
01-03-A 200 ghi 50

My problem is adding the third counted inventory table because it could look like anything depending on what we find in the racks:

LOCATION ITEM LOT QTY
01-01-A 100 abc 25 (exact match)
01-02-A 150 cba 75 (Item found)
01-03-A 200 ghi 50 (LOT swapped)
01-03-A 300 def 50 (Item Changed)

My join is returning 4 rows for location 01-03-A which I understand, but I'm wondering if I can sort within the join or make some temp tables so that instead of:

select M.MASTER_LOC, C.AS ORIG_ITEM, C.ORIG_LOT, C.ORIG_QTY, E.AS CNTD_ITEM, E.CNTD_LOT, E.CNTD_QTY
from
M_LOC M LEFT OUTER JOIN
C_INVT C ON M.MASTER_LOC = C.INVT_LOC LEFT OUTER JOIN
E_PHYS_INVT E ON M.MASTER_LOC = E.LOC_CODE
order by M.LOC_CODE

LOC1 ITEM LOT QTY LOC2 ITEM LOT QTY
01-03-A 200 def 50 01-03-A 200 ghi 50
01-03-A 200 def 5001-03-A 300 def 50
01-03-A 200 ghi 5001-03-A 200 ghi 50
01-03-A 200 ghi 5001-03-A 300 def 50

I'd like to just end up with 2 lines sorted by location, item, lot, qty so I can see that there is a problem with that location.

LOC1 ITEM LOT QTY LOC2 ITEM LOT QTY
01-03-A 200 def 5001-03-A 200 ghi 50
01-03-A 200 ghi 5001-03-A 300 def 50

View 2 Replies View Related

Selecting Single Sorted Row From Many Column

Jul 23, 2005

HiBeen at this for 2 days now.Each business has several packages which they can sort usingsort_order.I'm trying to get one package for each business(that I can do), howeverI want it to be the one with the lowest sort_order valueAs you can see below the first record has sort_order=5 when it shouldbe 1.Most of the sort_order columns will be zero by defaultAny help so i can get on with my life!CheersGary------------Current select-------------------SELECT *FROM dbo.testAccommodation_Packages T1WHERE (NOT EXISTS(SELECT *FROM testAccommodation_PackagesWHERE business_id = T1.business_id AND Package_ID < T1.Package_ID))--------------results:-----------------------Package_IDbusiness_iditem_namesort_order123rd Night FREE ...5113Donegal Town ... 0204Executive ...0--------------To recreate----------------------CREATE TABLE [testAccommodation_Packages] ([Package_ID] [int] IDENTITY (1, 1) NOT NULL ,[business_id] [int] NULL ,[Item_Name] [nvarchar] (300) NOT NULL ,[sort_order] [int] NULL CONSTRAINT[DF_Accommodation_Packages_sort_order] DEFAULT (0),)-------------------------------------------------INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('1','2','3rd Night FREE when you stay 2 nights MIDWEEK (129 EuroPPS)','5')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('2','2','Selected Donegal Town Hotel Weekend Sale - 2 B&B and 1Dinner Only € 129 PPS','4')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('3','2','2 Night Specials -Jan, Feb & Mar 2 B&B and 1 Dinner 149Euro PPS','3')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('4','2','Easter Hotel Breaks in Donegal Town - 2 B&B + 1 D€169pps','2')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('5','2','2005 Bluestack Hillwalking, 2 nights B&B, 1 Dinner, 5course Lunch 159 Euros PPS (~109 Stg)','1')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('6','2','April Pamper Package - 2 Night Special ONLY€195pps','10')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('7','2','Discount Hotel Prices for 8th & 9th April Only € 119PPS','7')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('8','2','Golden Year Breaks in Donegal - 4B&B + 2 Dinner€229pps','8')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('9','2','Hotel Summer Breaks Sale in Donegal - 2B&B + 1 Dinner€169pps','9')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('10','2','STAY SUNDAY NIGHTS FOR €25PPS','6')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('11','3','Donegal Town Midweek Special 99 Euro PPS 3 Nights B&B','0')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('12','3','Bridge Weekend 2 nights B&B 79 Euro PPS (approx 55Stg) Double Room','0')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('13','3','Donegal Spring Weekend Specials 2 B&B 1 Dinner109.00euros pps','0')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('14','3','Valentines Weekend 2 nights B&B and 1 four coursegourmet dinner 99Euro PPS','0')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('19','3','Golden Years Break.40% OFF 4 nights B&B€129.00p.p.s.','0')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('20','4','Executive Celebration Offer 1 night B&B + Dinner €139 PPS','0')INSERTtestAccommodation_Packages(Package_ID,business_id, Item_Name,sort_order)VALUES('21','4','Watercolour Painting Break 3 B&B Full Board andTuition € 335 PPS','0')

View 1 Replies View Related

Getting Line Number Sorted Out In Matrix

Dec 27, 2007

Hi there,

I have a matrix report that shows a certain columns and rows. I need a row counter to show me the amount of rows in that matrix but it doesn't count properly by using the expression: =Int(RowNumber("matrix1") -1)
I actually don't have any idea on what this expression should be to fix the row count...to illustrate what I get in the report:

______________________________________________________________________________
Chkp | Row | Serial No | Call of Date |Colour| Pillar | AV | Sport | USA | SRA | TAPE |
2019 | 1 | 7006892 | 2003/02/11 | 3644 | 78222 | 3902 | 9182 | | | |
| 3 | 7000123 | 2003/02/11 | 3299 | 17283 | | 9238 | 2793 | | |
| 5 | 7302031 | 2004/01/11 | 3902 | 28932 | | 3233 | 2332 | | |
| 7 | 7273211 | 2004/02/08 | 6727 | 39232 | 8228 | 3293 | | | |
| 8 | 7382728 | 2004/11/11 | 7822 | 32342 | 3902 | | | | |
| 13 | 7342934 | 2004/12/03 | 8323 | 23422 | 2031 | 9212 | 2934 | 2934 | 2982 |
| 18 | 7329491 | 2004/13/02 | 8291 | 92423 | 7922 | 0231 | 2342 | 2355 | 2223 |
| 22 | 7328438 | 2004/12/22 | 8399 | 92311 | | 0289 | 8392 | | 3982 |


As you can see above, the row count numbers are not lining up at all, it starts at 1, then jumps 2 every count then all of a sudden jumps 5 per line...a pattern that is interesting but difficult to understand. The unique value in this matrix is that serial number but even though i group it by the serial number, it still gives me the funny Row count values.

What would be the approach to solving this?

Regards
Mike

View 3 Replies View Related

SQL Server 2008 :: Database Level Selection Settings?

Apr 23, 2015

I have following table structure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FAS_LEDGER](
[TID] [INT] IDENTITY(1,1) NOT NULL,
[TDATE] [DATETIME] NOT NULL,

[code].....

in this table I have 1571182 rows

the problem is someone did some changes in this LEDGER table

I can insert new rows in this table but when I try to fetch latest rows on the basis of following query then I did not get the latest row.

means

following query gives all the rows of this table

SELECT * FROM dbo.FAS_LEDGER ORDER BY TID DESC

and when I try to filter Master_code = '02-07-01-008-0001' and apply oder by TDATE I do not get latest rows

SELECT * FROM dbo.FAS_LEDGER WHERE MASTER_CODE = '02-07-01-008-0001'
ORDER BY TDATE DESC

View 4 Replies View Related

List All Tables Sizes, Sorted By Size

Jan 13, 1999

How do I get a list of table names and their sizes, sorted by sizes? The command sp_spaceused only lists one table at a time.
Thanks for your help.

Lan.

View 2 Replies View Related

Trying To Join Within A Table - Get Result Sorted By Primary ID

Aug 27, 2014

So if an item is a bottle, it will have a unique BottleKey and Null for CaseKey and if an item is a Case, it will have a unique CaseKey and Null for BottleKey. However, the PrimaryIDs are the same for both the bottle and case. I get the results to look like this:

Bottlekey CaseKey PrimaryID
4754 NULL ABC-234
NULL 5465 ABC-234
.... .... .......

Is there a way to get the result sorted by Primary ID?

So that the rows are halved from what we have in the table above and the results look like

PrimaryID CaseKey BottleKey
ABC-234 5465 4754

View 1 Replies View Related

Why Is There No Warning If An Input To An Aggregate Component Is Not Sorted

Nov 16, 2005

All in the subject.

View 11 Replies View Related

MS SQL Query, What's The Default Order The Rows Returned Are Sorted By?

Jan 12, 2005

i have a table and a column called req_id, i have it set as the primary key.. so if i just do SELECT * FROM table, shouldnt the rows returned be sorted by the order that the rows were inserted?

this database was improted from an access database.. when i did that in access it would return the rows in sorted order by the order the row was inserted.. but now in MS SQL, its not sorted in that order.. i can't really tell what type of order it's in

View 6 Replies View Related

Merge Join - Output Of Lookup As Sorted Field?

Nov 3, 2007



I'm doing a data conversion with one of my fields (SUMDWK) from one of the tables that will be used in a merge join. With the new, converted field, I do a look up. From this look up, I want to take a new field FiscalWeekOfYear, and replace the original field, SUMDWK. This is necessary because SUMDWK is one of the sorted fields. In the look up, it is not possible to change the Output Alias. Does anybody know a way around this? Thanks.

View 14 Replies View Related

Ensuring That Matrix Data Region Col Headers Are Sorted

Dec 25, 2007

i ran a preview of a matrix based report whose column headers are dates. The dates seem to be displaying in a somewhat (not completely) random order from left to right. How can I ensure that they display chronologically from left to right?

View 1 Replies View Related

Integration Services :: Why Merge Transformation Need To Sorted Inputs

Jul 16, 2015

Why Merge Transformation Need to Sorted Inputs?

View 4 Replies View Related







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