Wierd Query Results When Comparing Field Values

May 8, 2008

Hi Guys, I am experiencing weird results

SELECT DSNew, DTTM, RQDT
FROM dbo.Feb
INNER JOIN DMSEFL
ON ACTR = DSNew
where cast(DSNew as varchar(20)) = cast(ACTR As varchar(20))
If I run the above query I get zero recs back.

If I substitute a Value then I get the desired results (ie. where DSNew = '93235500') or if I enter (ACTR = '93235500') or if I put (where DSNew = '93235500' AND ACTR = '93235500')

Can anyone suggest a reason why this is happening. I know the records exist on both tables I ran the query in Acess and got the desired resutls.

Thank you,
Trudye

View 4 Replies


ADVERTISEMENT

How To Insert Results Of A SQL Query Into The Field Of Another Table, As Comma Seperated Values.

Mar 7, 2008



I am currently working on an application that requires, insertion of the results of a SQL Query in to the field of another table, in the form of a comma separated values.

For example, to explain things in detail:

create table dbo.phone_details

(country varchar(20),
state varchar(30),
list_of_toll_free_numbers text)


insert into dbo,phone_details
values
( 'USA', 'CA', 'select Phone from phone_table where substring(phone, 1, 3) in ('800', '866', '877', '888')' )

The final output I desire is:

country state list_of_toll_free_numbers

---------- ------- -----------------------------------------
USA CA 8009877654, 8665764398, 8776543219

View 8 Replies View Related

Wierd Results With != Operator

May 19, 2006

Hi all,

I have a table - customer with a Column state_code varchar(5) and another valid( smallint)

select count(1)

from customer

where state_code != 'U' -- for unknown

and valid= 0 -- for valid

Returns different counts each time, even when the data in the table is NOT Changing.



something with != operator ?



Thanks for your help !

Sri

View 5 Replies View Related

Wierd XML Results From 'Exec SQL Task

Sep 15, 2006

Hi All, we got a problem that I hope you guys can help us with.

We are trying to extract data from a SQL database in XML format to a variable (string) using an 'Execute SQL Task'

In the task we are using an ADO.NET connection to the database which is fine and via direct input we are using this query.

SELECT
title,
initials,
surname,
username,
gender,
emailaddress,
addressline1,
addressline2,
addressline3,
town,
postcode,
country,
emailcontact,
postalcontact,
telephone
FROM
CRMCustRecords
FOR XML path('customer'), root('CRMData'), ELEMENTS XSINIL

In SSMS this is fine and returns an ok (to my eyes anyway!) XML resultset.

<CRMData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<customer>
<title>xxx</title>
<initials>xxxxxxx</initials>
<surname>xxxxxx</surname>
<username>xxxxxx</username>
<gender>x</gender>
<emailaddress>xxxx@xxxxxxx.xx.xx</emailaddress>
<addressline1>xxxxx</addressline1>
<addressline2 xsi:nil="true" />
<addressline3 xsi:nil="true" />
<town>xxxx</town>
<postcode>xxxxxxxxx</postcode>
<country>xx</country>
<emailcontact>x</emailcontact>
<postalcontact>x</postalcontact>
<telephone>99999999999</telephone>
</customer>
<customer>
</CRMData>

However the SSIS task (running exactly the same query) is returning

<ROOT>
<CRMData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<customer>
<title>xxx</title>
<initials>xxxxxxx</initials>
<surname>xxxxx</surname>
<username>xxxxxxxx</username>
<gender>x</gender>
<emailaddress>xxxxx@xxxxxxxxxx.xx.xx</emailaddress>
<addressline1>xxxxxxxxxx</addressline1>
<addressline2 xsi:nil="true" />
<addressline3 xsi:nil="true" />
<town>xxxxx</town>
<postcode>xxxxxxxx</postcode>
<country>xx</country>
<emailcontact>x</emailcontact>
<postalcontact>x</postalcontact>
<telephone>9999999999</telephone>
</customer>
</CRMData>
</ROOT>

I setup the query as a stored procedure and changed the SSIS accordingly. Running the sp from within SSMS was fine but the task still returned the wierd results.

This is completely unexpected and giving us headaches. It doesn't even look like well-formed XML to my eyes and won't display in IE without showing problems! Where are the eroneous /'s and ROOT nodes coming from?

I can't imagine we are the only people to have run into this and I'm sure we aren't doing something quite right - just stuck as to what we're doing wrong.

Hopefully I've provided enough info. If not just ask.

Thanks for any and all input
Pat

View 3 Replies View Related

Wildcard Doesn't Match Using LIKE '%' On A Varchar Field, Wierd!

Jul 20, 2005

Right this has to be a Micro$oft mess-up surely...?I'm running SQL 2k standard with SP3. I have a table which I'm tryingto query using a LIKE operator on a varchar field as follows....WHERE dbo.tbl_pm_projects.SeniorManagerID LIKE '%'....In actual fact the % is passed in by the application when the userselects "All managers" from the drop down list used to select theManager to filter by. If they select a manager's name from the listit becomes LIKE 'ajames' or whatever.BUT - the table currently contains 2972 records. If I take out theWHERE clause the SELECT returns all records - fine - but if I put thewhere clause in it returns only 1682!! I thought the % was meant tomatch, and I quote the SQL server Books Online files here; "Any stringof zero or more characters." Anyone explain to me whats going onhere?TIANiall

View 12 Replies View Related

Query Results - Not Getting Different Values Returned For Each Row

Jan 24, 2012

I am getting the following results from my query that contains a subquery, but I don't understand why the values in the [Total Volume M_Active_Previous] are being repeated with the same value. I should be getting different values returned for each row like in the [Total Volume M_Active] column.

Why the values are all the same and how I can fix this?

DayNoDayTotal Volume M_ActiveTotal Volume M_Active_Previous
6 Friday11161 72491
7 Saturday5687 72491
2 Monday14354 72491
1 Sunday3966 72491
4 Wednesday12340 72491
3 Tuesday12018 72491
5 Thursday11833 72491

Here is the SQL I'm using.

Code:
DECLARE @StartDate datetime, @EndDate datetime, @Prev_StartDate datetime, @Prev_EndDate datetime
SET @StartDate = '2011-03-13 00:00:00.000'
SET @EndDate = '2011-03-19 23:59:59.999'
SET @Prev_StartDate = '2011-03-06 00:00:00.000'
SET @Prev_EndDate = '2011-03-12 23:59:59.999'

[Code] ....

View 5 Replies View Related

Lookup / Merge Join / Script - Howto Look Up Values By Comparing To A Range Of Values?

Jun 4, 2007

Hello all,

I am trying to think my way through a solution which I believe others have probably come across... I am trying to implement a matching routine wherein I need to match an address against a high value and a low value (or, for that matter an input date vs. a start and end date) to return the desired row ... i.e. if I were to use a straight vb program I would just use the following lookup:



"SELECT DISTINCT fire_id, police_ID, fire_opt_in_out, police_opt_in_out FROM ipt_tbl " & _

" WHERE zip_code = @zip_code AND addr_prim_lo <= @street_number AND addr_prim_hi >= @street_number " & _

" AND addr_prim_oe = @addr_prim_oe AND street_pre = @street_pre AND street_name = @street_name " & _

" AND street_suff = @street_suff AND street_post = @street_post " & _

" AND (expiry_date = '' OR expiry_date = '00000000' OR expiry_date > @expiry_date)" & _

" GROUP BY fire_ID, police_ID, fire_opt_in_out, police_opt_in_out"



My question, then, is how would you perform this type of query using a lookup / merge join or script? I have not found a way to implement a way to set the input columns? I can set the straight matches without a problem, i.e. lookup zip code = input zip code, but can't think of the correct way to set comparisons, i.e. lookup value 1 <= input value AND lookup value 2 >= input value



Any suggestions?



thanks for your time...

View 5 Replies View Related

Wierd Query

Dec 6, 2004

I'm writing a report for a survey application. There is a subscriber table, a question table, and an answer table. The subscriber table holds info like the name, address, etc of the publication's subscribers. The Question table holds the questions on the survey (ie, How many widgets do you own? What is your age? How many do you think you will purchase in the coming year?). The Answer table holds answers to each question (18-21, 25-50%, 20+, etc). I am forced to work within a very non-standard database application running on MS SQL Server 2000 that also uses a separate Relationships table, so to determine which answers go with which questions the relationships table will have a record linking a question to an answer (and vice versa). To determine how each subscriber answered the question the subscibers have a record in the relationships table linking them with specific answers (and vice versa). Both types of entries are in the same table. There are several questions that will include a note to "check all that apply" (you may get several widgets from the company). The report runs through each question, shows how many subscribers answered the question, and how many selected each answer as a percentage of the total for that question. It is nearly finished, I can run it on the test data for any date, but there is one special case I'm having trouble with. For one question, they want to know additionally how many people chose one possible answer, but no others. I can do it using simple SQL to get the list of the subscribers that chose the answer in question, and then loop through each one in vb and run another query that will tell me how many answers related to that question they selected. This works okay for the test data, but in production there are more than 100,000 subscribers, which means running 100.000+ individual querys. I know it's possible to do this in one (all I want is the final count), but the SQL for this is horrid. Any help appreciated.

View 3 Replies View Related

How To Retrieve Query Results With Now Field Names, Dotted Line Or Footer

Oct 5, 2006

Hi folks,I'm trying to write a simple SELECT statement that will execute inquery analyser but will just have the data with no column names, or thedotted line between them and the data. I also want to avoid thestatement at the end which says nnn rows affected. any ideas? I want todo this because I intend to write the results to a flat file.Thanks for your helpDanny....

View 2 Replies View Related

Comparing Set Of Results

Nov 20, 2007

Is there a way to create a query which compares two result sets of results?
for example the result set of my first select statement is 7,1,8 and the second result set is 7,1,9..is there a query wherein i can compare the two results? i just wanted to reveal that there is a diffrence between the two..

thank you..

Funnyfrog

View 5 Replies View Related

IRR Function - Comparing Results Between Systems

Jan 13, 2012

I'm working on an income deferral problem and we are using IRR to end up calculating periodic income.

As an example, I have the following inputs:

Number of periods = 9
Initial Loan = 21.46
Instalment amount =15.30
Future value=0
Guess=0.1 (10%)

Using a compiled function from Visual Studio in SQL Server 2008 we get a result of 70.71656373

Using a Microsoft Access function we get NaN

Using Microsoft Excel we get NaN

Using a web calculator we get 70 (ish, the calculator rounds the numbers)

I know that the numbers are odd, some of our data is dirty so we do expect that. I was expecting the SQL process to kick out an error (therefore converting the result into 0), but it doesn't.

View 1 Replies View Related

SQL 2012 :: Query To Return Values From XML Field

Jun 5, 2014

Query to return values from XML field

create table #temp
(
id int identity (1,1)
,FieldSet XML
)

INSERT INTO #temp
VALUES ('<Fields> <Field Key="Column1" value="value1" > </Field> <Field Key="Column2" value="value2"> </Field> </Fields>')
,('<Fields> <Field Key="Column3" value="value3" > </Field> <Field Key="Column4" value="value4"> </Field> </Fields>')

SELECT * FROM #temp

Expected Output :

Id Column1Column2Column3Column4
1value1value2nullnull
2nullnullvalue3value4

View 4 Replies View Related

Utilities For Comparing Stored Procedure Results?

Dec 11, 2007

I have large stored procedures in SQL Server 2005 that often get updated. Sometimes it is very difficult to recognize how one change could impact the overall results. I would like to have some sample input that I could test during changes and see it compare the data results before & after my changes. This would help me quickly identify if the results are fine to pass through.

So basically I would like an easy way to compare the results of 2 stored procedures. Any suggestions or utilites that would help me do this?

View 3 Replies View Related

Query Which Calculates A Field Value Based On Previous Row's Values

Jan 18, 2007

I need to write a t-sql query that will take the value of the previousrecord into consideration before calculating the current row's newcolumn value...Here's the situation...I have a query which return the following table structure...Full_Name Points----------------- ------------Name1 855Name2 805Name3 800Name4 775Name5 775Name6 741etc.... etc...I need to create a calculated column that tells me where the personranks in point position. The problem i run into is that in thesituation where two or more people have the same point value i need thecalculated rank column to display the same rank number (i.e. 4th orjust "4") I'm not sure how to to take into consideration the previousrow's point value to determine if it is the same as the current onebeing evaluated. If i new they were the same i could assign the samerank value (i.e. 4th or just "4").If any one has any insight that would be great.ThanksJeremy

View 2 Replies View Related

Compare Utilities For Comparing Stored Procedure Results?

Dec 10, 2007

I have large stored procedures in SQL Server 2005 that often get updated. Sometimes it is very difficult to recognize how one change could impact the overall results. I would like to have some sample input that I could test during changes and see it compare the data results before & after my changes. This would help me quickly identify if the results are fine to pass through.

So basically I would like an easy way to compare the results of 2 stored procedures. Any suggestions or utilites that would help me do this?

View 6 Replies View Related

Comparing Two Row Values

Jan 15, 2007

whats the best way to compare two row values and concatenate those two

For example

Table1
-------
Col1 Col2
----------
A 1
A 4
B 2
C 3
A 5

I need a query to return something like
"where (A=1 or A=4 or A=5) and (b=2) and (c=3)"

Thanks in advance

View 11 Replies View Related

Comparing Values

Feb 23, 2006

Hi All

I have 2 tables
dbo.aus

dbo.us

aus has column ausid

us has column usersid

how do i ran a query to filter out all matching values in the 2 tables
basically i want a list of values that are the same in both tables

thanks

View 3 Replies View Related

Comparing NULL Values

Nov 2, 2006

I have two tables with the same structure / different data. I run a query between the tables to find the different records for the out put. When the values of the records or NULL, I do not get the output.


Code:

SELECT dbo.Closest3StoresB_RBT.CustomerPost, dbo.Closest3StoresB_RBT.ClosestStore1,
dbo.Closest3StoresB_RBT.ClosestStore2,
dbo.Closest3StoresB_RBT.ClosestStore3
FROM dbo.Closest3StoresB_RBT INNER JOIN
dbo.Closest3StoresB_OLD_RBT ON dbo.Closest3StoresB_OLD_RBT.CustomerPost =
dbo.Closest3StoresB_RBT.CustomerPost

WHERE
(dbo.Closest3StoresB_OLD_RBT.ClosestStore1 <> dbo.Closest3StoresB_RBT.ClosestStore1) OR
(dbo.Closest3StoresB_OLD_RBT.ClosestStore2 <> dbo.Closest3StoresB_RBT.ClosestStore2) OR

(dbo.Closest3StoresB_OLD_RBT.ClosestStore3 <> dbo.Closest3StoresB_RBT.ClosestStore3)




CustomerPost | ClosestStore1 | ClosestStore2 | ClosestStore3

I want to avoid seting the NULL values to '0' . Any suggestions?

View 3 Replies View Related

Comparing Values Within Same Table

May 1, 2014

I would like to compare some values in two columns which are in the same table. I want to check that there are no differences between the values if the ID is Test1 and Test2

Example table

IDValue1Value 2
TEST1HouseTango
TEST2HouseTango
with test as (
select * from ExampleTable where ID= 'TEST'
),

[Code] ....

View 4 Replies View Related

Comparing Values Within Database

Sep 10, 2007

Hi,

There are two tables in my Database, tb1 and tb2 which both have the same attribute ID. I would like to ensure that there is nothing in ID in tb1 which is not listed in ID in tb2, can anyone help?

Thanks for any info.

Albert.

View 10 Replies View Related

Comparing Time Values

Aug 25, 2005

I have a table called WorkItem. It models a chunk of work done duringa working day.It has two columns that I'm interested in:Start (smalldatetime) - the TIME the work block is begunDuration (int) - the duration in minutes of the work block.In another table called OvertimeRates I have information about ratemultipliers and a column that tells me the TIME that the ratemultiplier kicks in.e.g.OTRateBegins (smalldatetime)In terms of calculating whether a particular work block starts afterthe OTRateBegins, I could (I presume) do something like:If CONVERT(smalldatetime, Start, 108) > CONVERT(smalldatetime,OTRateBegins, 108)However, would I be better off using DATEPART functions to get the hourand minute parts of both the Start and OTRateBegins, and using theminstead? For some reason, (probably paranoia!), I am suspicious of theCONVERT function.Apologies for not posting DDL, but I felt that the situation didn'treally warrant it.ThanksEdward

View 6 Replies View Related

Conditionalize Field Values Based On Other Field Values

Apr 17, 2007

Here's a portion of the current statement.

UPDATE EngagementAuditAreas

SET numDeterminationLevelTypeId = parent.numDeterminationLevelTypeId,

numInherentRiskID = parent.numInherentRiskID,

numControlRiskID = parent.numControlRiskID,

numCombinedRiskID = parent.numCombinedRiskID,

numApproachTypeId = parent.numApproachTypeId,

bInherentRiskIsAffirmed = 0,

bControlRiskIsAffirmed = 0,

bCombinedRiskIsAffirmed = 0,

bApproachTypeIsAffirmed = 0,

bCommentsIsAffirmed = 0

FROM EngagementAuditAreas WITH(NOLOCK) ...

And what I need is to conditionalize the values of the "IsAffirmed" fields by looking at their corresponding "num" fields. Something like this (which doesn't work).

UPDATE EngagementAuditAreas

SET numDeterminationLevelTypeId = parent.numDeterminationLevelTypeId,

numInherentRiskID = parent.numInherentRiskID,

numControlRiskID = parent.numControlRiskID,

numCombinedRiskID = parent.numCombinedRiskID,

numApproachTypeId = parent.numApproachTypeId,

bInherentRiskIsAffirmed = (numInherentRiskID IS NULL),

bControlRiskIsAffirmed = (numControlRiskID IS NULL),

bCombinedRiskIsAffirmed = (numCombinedRiskID IS NULL),

bApproachTypeIsAffirmed = (numApproachTypeID IS NULL),

bCommentsIsAffirmed = (parent.txtComments IS NULL)

FROM EngagementAuditAreas WITH(NOLOCK)

Thanks.

View 1 Replies View Related

Comparing A Varchar And A Datetime Field

Feb 22, 2008



Hi,
I have a varchar field named FinancialYTDCode containing data in the format 2007F or 2008F. I want to only select the rows with the FinancialYTDCode that is the same as the current year.

Could someone please show me how I write this in my script.
Thanks

View 9 Replies View Related

Comparing VarCHAR FIELD With NULL

Apr 20, 2006

Hi, I have the following query

SELECT *
FROM PABX
INNER JOIN LOGIN ON (PABX.COD_CLIENTE = LOGIN.COD_CLIENTE)
AND LEFT(LOGIN.TELEFONE1,3) = LEFT(PABX.NRTELEFONE,3)
LEFT JOIN AUXILIAR ON (AUXILIAR.ORIGEM=LOGIN.LOCALIDADE)
WHERE
pabx.COD_cliente = 224 and
SUBSTRING(PABX.NRTELEFONE,4,1) NOT IN ('9', '8', '7')
AND LOGIN.UF = RIGHT(PABX.LOCALIDADE,2)
AND LOGIN.LOCALIDADE <> PABX.LOCALIDADE
AND PABX.CLASSIFICA IS NULL
AND PABX.LOCALIDADE <> AUXILIAR.DESTINO
AND (BLOQUEADO = 0 OR BLOQUEADO IS NULL)



But It has a problem because when AUXILIAR.DESTINO returns null (it means there is no registry) the condition AND PABX.LOCALIDADE <> AUXILIAR.DESTINO doesn't work, like 'SAO PAULO' is different from 'NULL' but for my query no it's not even equal, and this condition ommit the results....how can I solve it ?

PS: Both auxiliar.destino and pabx.localidade is varchar(255)

Thanks

View 5 Replies View Related

Comparing Date With NULL Values

May 8, 2001

Hi , I need to compare two date fields in two different tables.One of the field is varchar(8) and other is dateime.When there is a date in one field and NULL in other field , how do I compare these two vales?

View 4 Replies View Related

Comparing Column Values Among 2 Or More Rows

Jun 29, 2012

I've been working with T-SQL in a MSSQL Server Management Studio (2005) for about a week now. I've been trying to convert some horribly written VB code from a MS Access DB over to SQL so it can be automated on a SQL backend.

Most of the learning process and coding has gone surprisingly well. The problem is with comparing some data to determine which one needs to be flagged.

Three tables to note in bold, with notable fields in italics below them:

EmployeeData
HRID (identity)

ResourceAllocation
ID (identity)
[Last Name] (linked to HRID)
Project
[Resource Start Date]
[Resource End Date]
[Percent Utilization]

tblHCvalues
RAID (linked to ResourceAllocation.ID)
a monthyear and quarteryear for every month and quarter from 2012-2014. IE january12, february12, 1q12, 2q13, etc...

And yes, there are probably a thousand ways to optimize that tblHCvalues, but I'll ask about that later. Just work with the structure I have

Here's how it works: Each employee's data and unique HRID is in the EmployeeData tableAn employee can be on one or multiple projects at any timeThose projects are stored per project in the ResourceAllocation table with a link to the Employee's HRID, and all the other information listed aboveEven though an employee might be on two projects, they can only count for headcount on one project.

We use rules that compare the percent of work being done on a project, and the start and end dates of the employee (resource) on that project to determine which project should be counted for Headcount. The code uses a cursor to go through each HRID, and then pull up all the ResourceAllocation records associated with it.Run the rules to determine which ResourceAllocation record counts toward headcountA stored procedure then runs that fills out the tblHCvalues in the way we want for the project we want

All of it works, except for the rules that compare the things, so that's what I want to focus on in this thread. How do I write these rules:

Here are the rules, and they should work for any number of multiple resource allocations for one employee:

Choose the ResourceAllocation with the greatest [Percent Utilization]If the top ResourceAllocations have equal [Percent Utilization], choose the ResourceAllocation with the earliest [Resource Start Date]If the [Percent Utilization] and the [Resource Start Date] are equal, choose the latest [Resource End Date]If all three fields are equal, choose the first ResourceAllocation (aka, screw it and pick one at random)

I'm sure I could use a bunch of IF statements to compare it all, but even that is complicated to think about. There has to be an easier way, right?

View 6 Replies View Related

Comparing Result Set Values Of 2 Queries ??

Apr 20, 2004

Any assistance would be so helpful !!

We have 2 tables.. lets call them INV and COST

Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below...

ID | AMOUNT | VAT ( INV TABLE )
1 |20.125 |2.896
2 |10.524 |1.425

ID | AMOUNT | VAT ( COST TABLE )
1 |20.125 |4.821 .... different to ID 1 in INV Table
2 |10.524 |1.425

If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946)

Thats it ???

Please could someone out there offer some ideas ?

THANKS

JON

View 4 Replies View Related

Comparing Result Set Values Of 2 Queries ??

Apr 20, 2004

Any assistance would be so helpful !!

We have 2 tables.. lets call them INV and COST

Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below...

ID | AMOUNT | VAT ( INV TABLE )
1 |20.125 |2.896
2 |10.524 |1.425

ID | AMOUNT | VAT ( COST TABLE )
1 |20.125 |4.821 .... different to ID 1 in INV Table
2 |10.524 |1.425

If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946)

Thats it ???

Please could someone out there offer some ideas ?

THANKS

JON

View 1 Replies View Related

Comparing Result Set Values Of 2 Queries ??

Apr 20, 2004

Any assistance would be so helpful !!

We have 2 tables.. lets call them INV and COST

Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below...

ID | AMOUNT | VAT ( INV TABLE )
1 |20.125 |2.896
2 |10.524 |1.425

ID | AMOUNT | VAT ( COST TABLE )
1 |20.125 |4.821 .... different to ID 1 in INV Table
2 |10.524 |1.425

If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946)

Thats it ???

Please could someone out there offer some ideas ?

THANKS

JON

View 4 Replies View Related

Comparing Values And Inserting A Record

Apr 25, 2007

SELECTIndustry,
100.0 * SUM(CASE when ceoischairman = 'yes' then 1 else 0 end) / COUNT(DISTINCT CompID) AS [YesPercent],
100.0 * SUM(CASE when ceoischairman = 'no' then 1 else 0 end) / COUNT(DISTINCT CompID) AS [NoPercent]
FROMTCompanies
GROUP BYIndustry
ORDER BYIndustry

This code above is working as I need it but I need to insert some additional functionality. Thanks

I need to add something like this:

IF YesPercent > NoPercent
UPDATE tableX SET CEOIsChairman='Yes' WHERE Industry='<the industry value being evaluated>'
Else If NoPercent > YesPercent
UPDATE tableX SET CEOIsChairman='No' WHERE Industry='<the industry value being evaluated>'
Else
UPDATE tableX SET CEOIsChairman='Equal' WHERE Industry='<the industry value being evaluated>'
End

View 1 Replies View Related

COMPARING WITH COLUM WITH SPECIFIC VALUES IN SQL

Feb 6, 2008

Im Working with stored procedure. How can i compare Columns with specific values. I want to get the greater values of those column and inserted it to other columns. i want something like these
CASE
WHEN a> b,c,d THEN a
WHEN b> a,c,d THEN b
WHEN c> a,b,d THEN c
WHEN d> a,d,c THEN d

is there any ways to implement this? i got an error..
thanks please help..

View 7 Replies View Related

Comparing GPS Lat/Lon Values From Database Within An Area

Apr 2, 2008

Hi,

I would be very grateful if someone could help me. I have very little SQL knowledge and would like a push in the right direction:

I have a application that receives GPS lattitude and longitude values. I was originally using file base system where I would load all the points from the file into memory and do the calculations in the software but I now would like to use SQL Server Express.

I have created the tables:

[Table 1] GPS Points:
id int Primary key
latitude real
longitude real
desc nvarchar(128)

[Table 2] GPS Locations (comprises of one or more GPS Points from [1] above) to form a boundary:
GPS Locations database structure is:
locationId int primary key
gpspoint1 int
gpspoint2 int
gpspoint3 int
gpspoint4 int
desc nvarchar(128)

Table 2 contains up to 4 gps points ids from table 1 and GpsPoints1-4 can be null.

I have created the tables and I have inserted GPS values into both tables.

My problem:
I am trying to compare the current Lat/Lon (which are passed into the SQL fuction as two real datatype value) and I want to return all Table 2 locationId's where the current Lat/Lon are withing GPSPoints1-4 area.
gpspoint1, gpspoint2, gpspoint3, gpspoint4 reference an id from Table 1. I am not sure how I can do this?

I have implemetned a SQL function that returns all points from Table 1 that are within the predefined radius of 1.5 miles from the current Lat/Lon values passed in.

select desc,latitude,longitude, acos(SIN( PI()* @LatDec /180 )*SIN( PI()*latitude/180 )
)+(cos(PI()* @LatDec /180)*COS( PI()*latitude/180) *COS(PI()*longitude/180-PI()* @LonDec /180)
)* 3963.191 AS distance
FROM GpsPoints
WHERE 1=1
AND 3963.191 * ACOS( (SIN(PI()* @LatDec /180)*SIN(PI() * latitude/180)) +
(COS(PI()* @LatDec /180)*cos(PI()*latitude/180)*COS(PI() * longitude/180-PI()* @LonDec /180))
) < = Radius
ORDER BY 3963.191 * ACOS(
(SIN(PI()* @LatDec /180)*SIN(PI()*latitude/180)) +
(COS(PI()* @LatDec /180)*cos(PI()*latitude/180)*COS(PI() * longitude/180-PI()* @LonDec /180))
)

where 3963.191 is earths radius in miles,
radius is 1.5,
@LatDec is the current latitude and
@LonDec is the current longitude

Uses a lot of Trig and (for me) is quite complicated. This works very well and is very accurate. It also only uses a single table. I want to be able to now look for the current position within a boundary of 3 or more positions from Table 1 and this is where I am struggling?

Also, any suggestions on how I could do this better would be very much appreciated?

I look forward to your reply and help.

Thank you in advanced.

View 2 Replies View Related

Comparing 2 Columns Containing Null Values

Sep 28, 2006

Hi All.

     I'm having some issues with what seems to be a simple update statement but is giving me grief when one or both of the columns I'm comparing are null. My statement (simplified) is as follows:-

 

UPDATE
 TAB_A
SET
 TAB_A.TRADCODE = TAB_B.TRADCODE
FROM
 TADS_STAGE.DBO.UNCLBRAMDEPT TAB_B
JOIN
 TADS.DBO.UNCLBRAMDEPT TAB_A
ON
 TAB_B.BRANCODE = TAB_A.BRANCODE
AND
 TAB_B.MERDCODE = TAB_A.MERDCODE
AND
(
 TAB_B.TRADCODE <> TAB_A.TRADCODE
)

 

If either of the TRADCODE fields (or both) are null then the comparison fails to return the row to update. I've tried setting the ANSI_NULLS setting to off, this has no effect, presumably because it will only work when comparing a column to a variable or evaluating if the column is null itself.

I've considered using ISNULL, but if one of the columns happens to contain the value that I specify as the replacement value then the comparison will result true and not include the row.

 

I'd be grateful for any pointers!

 

Thanks in advance

 

View 4 Replies View Related







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