Case, Joins And NULL Trouble
Jul 23, 2005
Hi
Consider two tables
id1 code1
----------- -----
1 a
2 b
3 c
id2 code2 value
----------- ----- -----------
1 a 0
2 a 1
3 b 1
They are joined on the code field.
For each code, I want the maximum corresponding value. If the value
doesn't exist (corresponding code in second table doesn't exist), I want
a NULL field returned.
The result should look like this:
code2 value
----- -----------
a 1
b 1
c NULL
I can't get it to include the NULL row.
While there are uniqe ID's in this example, the real life example uses a
horrible four field compound key.
Any help would be appreciated.
Ger.
The above example can be recreated by the following script.
DROP table #temp1
DROP table #temp2
SELECT 1 AS 'id1', 'a' AS 'code1'
INTO #temp1
UNION
SELECT 2, 'b'
UNION
SELECT 3, 'c'
SELECT 1 AS 'id2', 'a' AS 'code2', 0 AS value
INTO #temp2
UNION
SELECT 2, 'a', 1
UNION
SELECT 3, 'b', 1
SELECT code2, value
FROM #temp1 t1
LEFT JOIN #temp2 t2 ON t1.code1 = t2.code2
WHERE CASE
WHEN t2.value IS NULL THEN 1
WHEN t2.value = 0 THEN 2
WHEN t2.value = 1 THEN 3
END = (
SELECT
MAX( CASE
WHEN value IS NULL THEN 1
WHEN value = 0 THEN 2
WHEN value = 1 THEN 3
END )
FROM
#temp2
WHERE
code2 = t2.code2
)
View 5 Replies
ADVERTISEMENT
Mar 2, 2007
I have a somewhat long question, and if anybody has the time and patience to read through it, I'd appreciate it.
I've been trying to write queries to extract infomation about a group of cases.
Each case goes through a set of processes. The first process is analysis, the second process is project work, the third process is review. When a case enters or leaves a process, the date is noted in the log as either "ProcStartDate" or "ProcEndDate." So, from the process table below, you can see that Case # 10 entered Process 1 on 02-28-2005, and left Process 1 on 06-17-2005. Likewise, it entered Process 2 on 06-18-2005 and left it on 07-21-2005.
Process
CaseIDProcessIDProcStartDateProcEndDate
10102-28-200506-17-2005
10206-18-200507-21-2005
10307-22-200510-11-2005
20103-21-200507-24-2005
20207-25-200508-10-2005
During each process, the company sends letters or makes phone calls to help move the process along. Each letter is recorded in the Letters table, while each phone call is recorded in the PhoneCalls table. In the letters table, you can see that Case # 10 had a letter sent on 04-15-2005. In the PhoneCalls table, you can see that the same case had a phone call made on 07-24-2005.
Letters
CaseIDLetterLogIDEntryDateAmtofLetters
1010104-15-20051
1010207-20-20051
1010309-16-20051
2020106-14-20051
2020206-19-20051
2020307-27-20051
2020407-29-20051
PhoneCalls
PhoneCalls
CaseIDPhoneLogIDEntryDateAmtofPhoneCalls
10410104-17-20051
10410207-24-20051
10410309-18-20051
10410409-23-20051
10410509-25-20051
20410606-18-20051
20410706-20-20051
20410807-28-20051
20410907-29-20051
I need to join these tables to show the number of letters and the number of phone calls that were made for each case during each process.
Since the two activity tables (Letters and PhoneCalls, respectively) don't have any Process information, I have to figure out what process the case was in at the time of the activity by looking at the EntryDate in the activity table and comparing it to the dates in the Process table. So, for example, Case # 10 had a letter sent on 09-16-2005, which means that it was in Process 3, since Process 3 (for Case # 10) lasted from 07-22-2005 to 10-11-2005.
For Case # 20, there was a letter on 07-27-2005 and another letter on 07-29-2005. By comparing these dates to the Process table, we can see that these two letters were sent during Process 2, which lasted from 07-25-2005 to 08-10-2005.
When I started trying to write this query, I began with just one of the activity tables - the Letters table. I made two subqueries in the "from" field using Process and Letters and left outer joined Letters on Letters.CaseID = Process.CaseID and Letters.EntryDate >= Process.ProcStartDate and Letters.EntryDate < Process.ProcEndDate. The second part of the "on" clause is an attempt at relating the activity entry dates to the process dates.
When I run the query using just the Process table and one of the activity tables, it works fine. When I try to left outer join the other activity table (so that I have Process, Letters, and PhoneCalls in there all at once), the numbers suddenly change and become incorrect, but I can't figure out why.
Does anyone have an idea as to how to join these tables so that the numbers come out right?
This is the result I'm looking for:
CaseIDProcessIDAmtofLettersAmtofPhoneCalls
10111
10210
10314
20122
20222
Thank you.
View 4 Replies
View Related
Mar 7, 2001
Here is what I am currently doing:
********************************************
SELECT Hours.Hours, Hours.Comments
FROM Hours INNER JOIN Employee
ON Employee.UserID = Hours.UserID
INNER JOIN Task
ON Hours.TaskID = Task.TaskID
INNER JOIN Project
ON Hours.ProjID = Project.ProjID
WHERE Hours.Date <= EndDate
AND Hours.Date >= StartDate
AND Hours.Date <= EndDate;
********************************************
Am I doing something wrong here?
Any help would be greatly appreciated!
View 2 Replies
View Related
Mar 27, 2007
I have the following in my WHERE clause for my Sql Server Reporting Services 2000 report (the user can use the parameter @MaxRevs to view all numbers (colNumber) or only the max of colNumbers when grouped by colParentNumber):
AND (tblMain.colNumber IN CASE @MaxRevs WHEN '' THEN '(SELECT colNumber FROM tblMain)' ELSE '(Select max(colNumber) From tblMain Group By [colParentNumber])' END))
I get the following error:
1. ADO error: Syntax error or ADO access error
I've used Case in the past, but it was for a "Like" portion in my WHERE clause.
The following doesn't seem to help me either in the SQL portion:
IF @MaxRevs = '' SELECT ....
ELSE
SELECT ....
With the above query, nothing is ever returned. I can even name the parameter to @MaxRevs55, which doesn't even exist, and the report just brings back a blank page w/o any errors.
Thanks!
View 2 Replies
View Related
Aug 2, 2006
I would like to populate a grid with data from 2 different tables.
Table1: [PK]id(int), name(nvarchar), areaID(int)
Table2: [PK][FK]areaID(int), areaDescription(nvarchar)
My cerrent query is:
SELECT Table1.id, Table1.name, Table2.areaDescription FROM Table1 INNER JOIN Table2 ON Table1.areaID = Table2.areaID
However, sometimes the areaID in Table1 will only be populated at a later stage and therefore will be NULL in Table1. Table2 is used as a lookup table when inserting into Table1. This query therefore ommits any records in Table1 which do not have an areaID. I would like to view ALL records(ones without an areaID as well) as they would be populated in the grid and selected to be updated on web forms because they are incomplete and then subsequently assigned an areaID.
Any help with this query would be much appreciated...
View 2 Replies
View Related
Aug 14, 2015
CREATE TABLE A (ID INT IDENTITY (1,1))
CREATE TABLE B (ID INT, EMPID VARCHAR(10))
INSERT INTO A DEFAULT VALUES
GO 5
INSERT INTO B VALUES (1,'E23')
INSERT INTO B VALUES (1,'E24')
INSERT INTO B VALUES (2,'E23')
from the above code i would like to get output like
ID EMPID
1 23
2 23
3 null
4 null
5 null
1 24
2 null
3 null
4 null
5 null
I'm trying like
select a.id, b.empid from (
select * from a cross join (
select distinct empid from b) b
) a
left outer join b on a.id = b.id but i get repetitive rows.
View 7 Replies
View Related
Sep 25, 2015
I have tried all possible combinations of changing this. But was not able to make the results tally.I am giving you a part of the query, there are others queries involving 4 tables which are based on this same temporary table query.
SELECT c.juris_id, b.jrnl_mo_yr
FROM a_trueup a,
#t_mths b, r_rj c
WHERE a.rlzd_mo_yr
=* b.jrnl_mo_yr
AND
a.juris_id
=* c.juris_id
[code]....
I tried using left outer join as mentioned in blogs but got a different result (14 rows).I also used set null off/on options but no luck ..
View 15 Replies
View Related
Nov 2, 2000
I am having trouble with the following:
SELECT CASE name
WHEN NULL THEN 'No name'
ELSE name
END
It is not working as I'd expect. The column displays <NULL> instead of 'No
name'. Any thoughts?
TIA
View 1 Replies
View Related
May 19, 2006
SELECT whatever_field, CASE LEN(DrAccount) WHEN 12 THEN DrAccount ELSE CASE (Note1) WHEN NULL THEN Location + DrAccount ELSE Note1 + DrAccount END END AS Account FROM Table1 The purpose of the CASE(Note1) is when Note1 column is null, return Location+DrAccount. The actual result is when Note1 column is null, it always returns null, Location+DrAccount is not executed. When Note1 column is not null, it returns correctly Note1+DrAccount. The problem seems to reside in validating the null value in WHEN NULL How to check for null in CASE(fieldname) WHEN ???
View 1 Replies
View Related
May 6, 2008
Hello again! I'm having yet another problem with my code.
CASE Kit WHEN 'Y' THEN '(Kit)' WHEN 'N' THEN '' END + ' ' +
CASE cream WHEN 'Y' THEN '(cream)' WHEN ' N' THEN '' END + ' ' +
CASE Phone WHEN 'Y' THEN '(Phone)' WHEN 'N' THEN '' END
The problem that I am running into is that if one of the values comes up as NULL the whole field is NULL. am i doing something wrong?
View 11 Replies
View Related
Oct 22, 2013
Code below:
SELECT
NAME,
CASE WHEN PHONE IS NULL THEN '-' ELSE PHONE END AS PHONE
FROM
PATIENT
WHERE PHONE = '-'
If I am switching the NULL values to hyphens (-), why am I not getting any records when I look for hyphens in the WHERE clause? The script is not as simple as this or else I would just check for NULL values. I really need to switch NULL values to something I can pass on to a variable and query on it from Reporting Services.
View 6 Replies
View Related
Mar 17, 2008
I am trying to setup a query that receives input variables one being a number which could be null (could receive as string).
What I want to happen is if a number is sent the data is filtered by that number but if it is empty no filtering is performed I think this involves using a case statement in a where clause but can't work out the syntax I am using sql 200 server.
I think the case statement is something like this:
(week_no = CASE @week WHEN null THEN '#' ELSE @week END)
or maybe I am way off
I considered using like @inNumber + '%' but this would cause the problem of if I inoput 2 it would also return 20's 200's ...
View 3 Replies
View Related
Nov 9, 2007
Here's what I have and it's not working.
Code Block
SELECT [userID],
CASE
WHEN [mdlName] = NULL AND [mdnName] = NULL THEN [lstName] + ', ' + [fstName]
WHEN [mdlName] <> NULL AND [mdnName] <> NULL THEN [lstName] + ', ' + [fstName] + ' ' + [mdlName] + ' ' + [mdnName]
WHEN [mdlName] <> NULL AND [mdnName] = NULL THEN [lstName] + ', ' + [fstName] + ' ' + [mdlName]
WHEN [mdnName] <> NULL AND [mdlName] = NULL THEN [lstName] + ', ' + [fstName] + ' ' + [mdnName]
END AS [Full Name]
FROM [grUser]
ORDER BY [Full Name] ASC
The [Full Name] is always null. Any idea why? What I'm trying to do is if mdlName (middle name) and mdnName (maiden name) is null then display the lstName (last name) and fstName (first name) only and so on.
Any help is much appreciated.
View 4 Replies
View Related
Jun 19, 2015
DECLARE @I1 VARCHAR(5),
@I2 VARCHAR(5)
;
WITH cte
AS (SELECT 1 AS i,
'val1' AS j UNION ALL
SELECT 2,
'val2')
[code]....
Why @i1 is null but not @i2 ? I'm trying to assign values after grouping by the column.
View 17 Replies
View Related
Jul 21, 2004
Can someone help me with this :
Case WHEN ISNULL (dbo.BLH.n1name,'NOTHING')= 'NOTHING' then dbo.BLH.coname else dbo.BLH.n1name End as CustName
as the strored proc is not returning value when the fileds is blank
cheers
View 2 Replies
View Related
Sep 21, 2015
I'm trying to get a result set without the NULLs. Here is the code I'm using. I'd like the results to look like:
17285204 90471 090471
17285204 90715 090715
17285204 99396 099396
17285204 99420 099420
17285204 90471 090471
17285204 NULL G0444
create table #Test
(
AppNum varchar(10),
CPT varchar(10),
src char(1)
)
insert into #Test(AppNum, CPT, src) values('17285204','090471','b')
[Code] ...
View 5 Replies
View Related
Jun 3, 2008
I am working on a Function that takes multiple parameters. I have a query that populates a temporary table, and then it processes some logic. My question is, if the parameter is passed as null, I dont want the query to be affected by this null value. Rather, I would like to not pass it at all to the query. So if the parameter is NULL, dont pass it through the query. I have the following but its not compiling right:
SELECT bom.pEngr_BOM_ID , bom.fEngr_Item_ID, det.pEngr_BOM_Detail_ID, 1, bom.Bill_Type, bom.Rev_Ltr, bom.Series_Ltr
FROM dbo.Engr_BOM_Control bom WITH (nolock)
INNER JOIN dbo.Engr_BOM_Detail det WITH (nolock)
ON det.fEngr_BOM_ID=bom.pEngr_BOM_ID
WHERE bom.pEngr_BOM_ID=@v_pEngr_BOM_ID
AND det.fEngr_BOM_ID=@v_pEngr_BOM_ID
CASE WHEN @v_Bill_Type IS NOT NULL THEN
AND bom.Bill_Type=@v_Bill_Type
END
View 3 Replies
View Related
Aug 5, 2015
I have a table that keeps track of all changes that were performed in an application. There is a column called "old value" and column called "new value". There are some values in the application that don't require data therefore the "old value" or "new value" values can be empty. These columns are an nvarchar data type because the value can be text or numbers or dates. An example is "ReceivedDate". There is a report that is generated based on this table.
What is happening is the query in the report dataset is adding dates when it should be displaying empty. They query is using "CASE/WHEN/THEN". What I need is "When the column is "RecievedDate" and it is not null then convert it to a date". This is for formatting purposes.
This is an example of the table:
UpdateColumn
Old Value
New Value
ReceivedDate
7/8/2015 5:00:00 AM
ReceivedDate
7/8/2015 12:00:00 AM
7/9/2015 5:00:00 AM
ReceivedDate
7/9/2015 12:00:00 AM
So, the first time it was updated there was no value but it was replaced with July 8, 2015 and so on.This is what the report is displaying
This is the query:
CASE UpdateColumn
... WHEN 'ReceivedDate' THEN (replace(convert(varchar(11),CONVERT ( date, oldvalue ), 106), ' ', '-') )
...
I tried adding
CASE UpdateColumn
...
WHEN 'ReceivedDate' IS NOT NULL
THEN (replace(convert(varchar(11),CONVERT ( date, oldvalue ), 106), ' ', '-') )
...
But it did not like the "IS NOT NULL".
View 9 Replies
View Related
Sep 15, 2015
The below code returns a NULL for all the Differential backups. I am trying to return the word Differential when there is a NULL because I can tell from when the NULLs occur that those are my differential backups. How can I get the result I want?
SELECT
CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server,
msdb.dbo.backupset.database_name,
msdb.dbo.backupset.backup_start_date,
msdb.dbo.backupset.backup_finish_date,
CASE
WHEN msdb..backupset.type = 'D' THEN 'Database'
[Code] .....
View 9 Replies
View Related
Jun 15, 2015
I'm running the following test query on a single table:
SELECT sph.datestamp, sph.stocksymbol, sph.closing, DATENAME(dw, sph.datestamp),
CASE DATENAME(dw, sph.datestamp)
WHEN 'Monday' then 'Monday'
ELSE (SELECT CAST(sph2.datestamp AS nvarchar) FROM BI_Test.dbo.StockDB AS sph2 WHERE sph2.DateStamp = DATEADD(d, -1, sph.datestamp) AND sph2.StockSymbol = 'NYA')
END AS TestCase,
[Code] ....
And here's an example of the output I'm getting:
Why the exact same subquery in the THEN of the second CASE statement is returning NULL when the first one completes as expected?
View 7 Replies
View Related
Nov 3, 2000
We find that a delete command on a table where the rows to be deleted involve an inner join between the table and a view formed with an outer join sometimes works, sometimes gives error 625.
If the delete is recoded to use the join key word instead of the = sign
then it alway gives error 4425.
625 21 0 Could not retrieve row from logical page %S_PGID by RID because the entry in the offset table (%d) for that RID (%d) is less than or equal to 0. 1033
4425 16 0 Cannot specify outer join operators in a query containing joined tables. View '%.*ls' contains outer join operators.
The delete with a correleted sub query instead of a join works.
Error 4425 text would imply that joins with view formed by outer joins should be avoided.
Any ideas on the principles involved here.
View 1 Replies
View Related
Aug 11, 2005
SQL Server 2000Howdy All.Is it going to be faster to join several tables together and thenselect what I need from the set or is it more efficient to select onlythose columns I need in each of the tables and then join them together?The joins are all Integer primary keys and the tables are all about thesame.I need the fastest most efficient method to extract the data as thisquery is one of the most used in the system.Thanks,Craig
View 3 Replies
View Related
Sep 20, 2006
Hey. I need to substitute a value from a table if the input var is null. This is fine if the value coming from table is not null. But, it the table value is also null, it doesn't work. The problem I'm getting is in the isnull line which is in Dark green color because @inFileVersion is set to null explicitly and when the isnull function evaluates, value returned from DR.FileVersion is also null which is correct. I want the null=null to return true which is why i set ansi_nulls off. But it doesn't return anything. And the select statement should return something but in my case it returns null. If I comment the isnull statements in the where clause, everything works fine. Please tell me what am I doing wrong. Is it possible to do this without setting the ansi_nulls to off??? Thank you
set ansi_nulls off
go
declare
@inFileName VARCHAR (100),
@inFileSize INT,
@Id int,
@inlanguageid INT,
@inFileVersion VARCHAR (100),
@ExeState int
set @inFileName = 'A0006337.EXE'
set @inFileSize = 28796
set @Id= 1
set @inlanguageid =null
set @inFileVersion =NULL
set @ExeState =0
select Dr.StateID from table1 dR
where
DR.[FileName] = @inFileName
AND DR.FileSize =@inFileSize
AND DR.FileVersion = isnull(@inFileVersion,DR.FileVersion)
AND DR.languageid = isnull(@inlanguageid,null)
AND DR.[ID]= @ID
)
go
set ansi_nulls on
View 3 Replies
View Related
Oct 12, 1999
Hi,
Why is it that SQL joins (*=) run a little faster as opposed to ANSI joins(LEFT JOIN...)? Aren't they supposed to be almost identical?
The issue is this: we are promoting using ANSI syntax for the obvious reason (future versions of SQL Server may not support SQL Server syntax; portability, etc.)
However, the problem is the speed. What have others done about this? Do you use ANSI syntax or SQL syntax? HOw true is it that future SQL Server versions may discontinue support for the '*=" and "=*' join operators.
Angel
View 1 Replies
View Related
Feb 29, 2008
I have four tables which I want to return results for an advanced search function, the tables contain different data, but can be quite easily joined,
Table A Contains a Main Image, this image is displayed in the results
Table B Contains an Icon, this image is displayed in the results
Table C doesn't have an image in it but has a child table with a number of images associated to the table, in the UNION ALL statement I would Like to do a Join to get say the top Image from this child and print it for the row associated with table C.
Select title, description, image from tableA
UNION ALL
Select title, description, icon as image from tableB
UNION ALL
title, description, ( inner Join SELECT top(1)
from imageTableC where imagetableC.FK = tableC.PK)
as image from tableC
Could someone show me the syntax to do this, I have all the information printing to the screen, bar this table C image.
View 14 Replies
View Related
Aug 31, 2015
How can I change my T-SQL text editor from text sensitive to text insensitive?
View 2 Replies
View Related
Sep 1, 2005
Hi All,
Im having a problem with a statement i cannot seem to get 2 left joins working at the same time 1 works fine but when i try the second join i get this error:-
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'children_tutorial.school_id=schools.idx LEFT JOIN regions ON children_tutorial.region_id=region.idx'.
My SQL statment is as follows :-
SELECT children_tutorial.*,schools.schoolname,regions.rname FROM children_tutorial LEFT JOIN schools ON children_tutorial.school_id=schools.idx LEFT JOIN regions ON children_tutorial.region_id=region.idx
I am using an Access database i have tried all sorts to get it working and its driving me mad!! any help would be really appreciated.
View 2 Replies
View Related
Jan 6, 2005
Hello:
I have created an SQL server table in the past on a server that was all case sensative. Over time I found out that switching to a server that is not case sensative still caused my data to become case sensative. I read an article that said you should rebuild your master database then re-create your tables. So after rebuilding the master database, a basic restore would not be sufficient? I would have to go and manually re-create every single table again?
Any suggestions?
View 4 Replies
View Related
May 4, 2007
Can someone point me to a tutorial on how to search against a SQL Server 2000 using a case insensitive search when SQL Server 2000 is a case sensitive installation?
thanks in advance.
View 3 Replies
View Related
Aug 17, 2005
We need to install CI database on CS server, and there are some issueswith stored procedures.Database works and have CI collation (Polish_CI_AS). Server hascoresponding CS collation (Polish_CS_AS). Most queries and proceduresworks but some does not :-(We have table Customer which contains field CustomerID.Query "SELECT CUSTOMERID FROM CUSTOMER" works OK regardless ofcharacter case (we have table Customer not CUSTOMER)Following TSQL generate error message that must declare variable @id(in lowercase)DECLARE @ID INT (here @ID in uppercase)SELECT @id=CustomerID FROM Customer WHERE .... (here @id in lowercase)I know @ID is not equal to @id in CS, but database is CI and tablenames Customer and CUSTOMER both works. This does not work forvariables.I suppose it is tempdb collation problem (CS like a server collationis). I tried a property "Identifier Case Sensitivity" for myconnection, but it is read only and have value 8 (Mixed) by default -this is OK I think.DO I MISS SOMETHING ????
View 4 Replies
View Related
May 29, 2008
I am working in a SQL server database that is configured to be case-insensetive but I would like to override that for a specific query. How can I make my query case-sensitive with respect to comparison operations?
Jacob
View 5 Replies
View Related
May 4, 2015
I have column with value of all upper case, for example, FIELD SERVICE, is there anyway, I can convert into Field Service?
View 7 Replies
View Related
Aug 19, 2007
I am curious with using replication in sql server 2005 one way from db A (source) replicating to db B(destination) in which db A has a collation of CS and db B has a collation of CI. Will there be any problems with this scenario? Thanks in advance!
View 2 Replies
View Related