How To Write A Query To Return Null For Non-exist Record In An Outer Join.
Jun 2, 2004
I have two tables:
1. tblProducts
columns: ProductID, ProductName
2. tblProductCodes
columns: ProductID, CustomerID, ProductCode
The 2nd table is for storing product codes for customers, in other words, one product can have different ProductCode for different customers. But some customers do not have ProductCode for a ProductID.
I want to create a query to return all the Products and its ProductCode (null is valid) for a specific customer.
dbo.tblProductCodes ON dbo.tblProducts.ProductID = dbo.tblProductCodes.ProductID
WHERE dbo.tblProductCodes.CustomerID = 2
But the query left out all products that does not have ProductCode value in tblProductCodes table for CustomerID = 2. I want all the ProductName returned from query and render null or empty string for ProductCode value if the code does not exist in tblProductCodes table for the customer.
The Orders table contains orders placed on all the dates. I want to obtain a list of orders for a particular date, if there is no order for a product on the requested date, I want to return null values for the Quantity and Price fields.
I tried the following select statement:
select Products.ProductName, Orders.Quantity, Orders.Price from Products left join Orders on Products.ProductID = Orders.ProductID where Orders.OrderDate = '10/16/2004'
Where, there are a total of three products (A,B,C) in table Products. Product-C has no order on 10/16/2004, but I want it to return :
I have this View and want to also see Clubs that do not have current memberships.I have the IS NULL but not seeing the Clubs that do NOT have memberships. attribute.PersonMembership is a SQL table that has membership information.
The "PersonMembership" has all the membership records from 2015 through 2019 of membertypeid 1-4 for the sampling.Since the syntax used in Access do not carry over without modifications to SQL, SQL syntax to make it work in SQL.And if you know the proper SQL syntax for "Between Year(Date())+IIf(Month(Date())>=7,1,0) And Year(Date())+IIf(Month(Date())>=7,1,0)+4" instead of what I currently have in SQL, that would be wonderful.
I have this sql statement:select A.field1,B.field2from table1 A,table2 Bwhere A.field1=B.field2If there is no match, I still want to produce a line of output withfield2 showing a blank. Ordinarily I could simply do an outer join.But because I have more than two tables in my real query, it won't letme.So instead, I tried this approach:select A.field1,B.field2from table1 A,table2 Bwhere A.field1=B.field2or not exist(select 1 from table2 C where C.field2 = A.field1)But now I get this error:--------------Incorrect syntax near the keyword 'select'. Incorrect syntax near ')'.Statement(s) could not be prepared.--------------Any hints as to what I need to fix?Thanks.Dennis HancyEaton CorporationCleveland, OH
my table isCustomer Customer Id--------- ----------------Mary 1Jhon 2Anna 3OrderId CustomerId Product ProductDesc------- --------- --------- -----------1 1 video bla bla2 1 tv bla bala3 2 video bla bla4 2 cd bla blaI want to see-------marry tv bla blaJohn cd bla blaanna
I'd like to return the following result set: CompanyModules.CompanyID | Modules.Name | Present 1 | A | True 1 | B | True 1 | C | True 2 | A | True 2 | B | False 2 | C | False
What would be the query for this? Thanks.
Edit: This is the query I have tried:
select CompanyModules.CompanyID, Modules.Name, count(Modules.ID) as Present from
CompanyModules RIGHT outer Join Modules on CompanyModules.ModuleID = Modules.ID
group By CompanyModules.CompanyID, Modules.Name
Order by CompanyID
However, it only returns a partial result set:
CompanyModules.CompanyID | Modules.Name | Present 1 | A | 1 1 | B | 1 1 | C | 1 2 | A | 1
Hello, please, is there SO who can help me resolve my problem? I'm developing a simple ASP application.
I have 2 tables - T_Employees , P_Users T_Employees = all employees of a company, P_Users = users of the system, P_Users is sub-set of T_Employees, PERNR is link
I need result of: SELECT e.Name, u.Permitions FROM T_Employees AS e LEFT OUTER JOIN P_Users AS u ON e.PERNR = u.PERNR and (e.PERNR = 1) .
If an employee with PERNR = x is not a user (is not in P_Users) , I expect to recieve 1 row with u.Permitions=null
But what happens! If I put this query to Management studio, I recieve 1 row (as I expect). Than I run exactly the same query in ASP page and it doesn't return any row (recordcount=0).
And what is even more strange - it worked. Suddenly I met this problem in all my pages and I can't find where the problem consist in. I always take SQL query from ASP VB into query analyzer and it works. But not on my pages.
It looks like the ASP works with different settings or as QA corrects my query before execution.
I'm totaly confused by this. Have you ever met ST like this?
Thanks for your advice Petr petr DOT chary@gmail DOT c o m
Does SQL have a function that return "null" for records which don't exist? Per example in a FK relation ship, that not all records in the first table have a "child" in the second table, so it returns null records.
We have two tables that have somewhat of a parent-child relationship. We are trying to use a SQL-92 outer join that returns the same results as a TSQL *= outer join. The difficulty we are having is that some of the parent records do not have any corresponding child records, but we still want to see those parent records with 0 (zero) for the count. How can we accomplish this with a SQL-92 compliant join (if it is even possible)? In the query results below, we would like the first set of results.
Thanks in advance for any help. -David Edelman
Test script below, followed by results =========================================== create table parent (p_id int NOT NULL) go create table child (p_id int NOT NULL, c_type varchar(6) NULL) go insert parent values (1) insert parent values (2) insert parent values (3) insert parent values (4) insert parent values (5) insert parent values (6) insert parent values (7) insert parent values (8) insert parent values (9) insert parent values (10) go
I have a MSDE query that includes a "left outer join..." clause. It runs fine in MSDE Query (a 3rd party GUI tool) and produces 12 rows. column 3 has some NULL values (because of the outer join).
But when I use the same query in an ASP.NET page, and display the result in a datagrid, it only displays 7 rows - the rows with the NULL value in column 3 do not display.
Is there a parameter somewhere in datagrid or dataset that I should be setting?
Hi!I have a problem with a query:Two tables:CREATE TABLE Emp (empno INT, depno INT)CREATE TABLE Work (empno INT, depno INT, date DATETIME)I want a list of all employees that belongs to a department (from Emptable), together with ("union") all employeees WORKING on that department aspescial day (An employee can have been borrowed from another departmentwhich he does not belong)Sample dataINSERT INTO Emp (empno, depno) VALUES (1,10)INSERT INTO Emp (empno, depno) VALUES (2,10)INSERT INTO Emp (empno, depno) VALUES (3,20)INSERT INTO Work (empno, depno, date) VALUES (1,10,'2003-10-17')INSERT INTO Work (empno, depno, date) VALUES (3,10,'2003-10-17')INSERT INTO Work (empno, depno, date) VALUES (3,10,'2003-10-18')Note that Employee 3 works on a department to which he does not belong (heis borrowed to another department)The following querySELECT empno, depno, date FROM work WHERE depno = 10 AND date = '2003-10-17'gives me this result set:empno depno date1 10 2003-10-17 00:00:00.0003 10 2003-10-17 00:00:00.000But I want employee 2 to appear in the result set as well, because hebelongs to department 10 (eaven thoug he is not working this particular day)The result set should look like thisempno depno date1 10 2003-10-01 00:00:00.0002 10 NULL3 10 2003-10-01 00:00:00.000I have tried different approaches, but none of them is good.Could someone please help me?Thanks in advanceRegards,Gunnar VøyenliEDB-konsulent asNORWAY
If I try to run the code below, and even one of the values in the INNER JOIN statements is NULL, the DataReader ends up with zero rows. What I need is to see the results even if one or more of INNER JOIN statements has a NULL value. For example, if I want info on asset# 2104, and there's no value in the DriverID field, I need the rest of the data to display and just have the lblDriverName by blank. Is that possible?
<code> Sub BindSearchGrid() Dim searchUnitID As String Dim searchQuery As String searchUnitID = tbSearchUnitID.Text lblIDNum.Text = searchUnitID searchQuery = "SELECT * FROM Assets " & _ "INNER JOIN Condition ON Condition.ConditionID = Assets.ConditionID " & _ "INNER JOIN Drivers ON Drivers.DriverID = Assets.DriverID " & _ "INNER JOIN Departments ON Departments.DepartmentID = Assets.DepartmentID " & _ "INNER JOIN AssetCategories ON AssetCategories.AssetCategoryID = Assets.AssetCategoryID " & _ "INNER JOIN Store ON Store.[Store ID] = Assets.StoreID WHERE RTRIM(Assets.[Unit ID]) = '" & searchUnitID & "'"
Dim myReader As SqlDataReader myReader = Data.queryDB(searchQuery) While myReader.Read If Not IsDBNull(myReader("Store Name")) Then lblStrID.Text = myReader("Store Name") If Not IsDBNull(myReader("AssetCategory")) Then lblAsstCat.Text = myReader("AssetCategory") If Not IsDBNull(myReader("Condition Description")) Then lblCondID.Text = myReader("Condition Description") If Not IsDBNull(myReader("DepartmentName")) Then lblDepID.Text = myReader("DepartmentName") If Not IsDBNull(myReader("Unit ID")) Then lblUnID.Text = myReader("Unit ID") If Not IsDBNull(myReader("Year")) Then lblYr.Text = myReader("Year") If Not IsDBNull(myReader("Make")) Then lblMk.Text = myReader("Make") If Not IsDBNull(myReader("Model")) Then lblMod.Text = myReader("Model") If Not IsDBNull(myReader("Mileage")) Then lblMile.Text = myReader("Mileage") If Not IsDBNull(myReader("Vin Number")) Then lblVinNum.Text = myReader("Vin Number") If Not IsDBNull(myReader("License Number")) Then lblLicNum.Text = myReader("License Number") If Not IsDBNull(myReader("Name")) Then lblDriverName.Text = myReader("Name") If Not IsDBNull(myReader("DateAcquired")) Then lblDateAcq.Text = myReader("DateAcquired") If Not IsDBNull(myReader("DateSold")) Then lblDtSld.Text = myReader("DateSold") If Not IsDBNull(myReader("PurchasePrice")) Then lblPrPrice.Text = myReader("PurchasePrice") If Not IsDBNull(myReader("NextSchedMaint")) Then lblNSM.Text = myReader("NextSchedMaint") If Not IsDBNull(myReader("GVWR")) Then lblGrVWR.Text = myReader("GVWR") If Not IsDBNull(myReader("GVW")) Then lblGrVW.Text = myReader("GVW") If Not IsDBNull(myReader("Crane Capacity")) Then lblCrCap.Text = myReader("Crane Capacity") If Not IsDBNull(myReader("Crane Certification")) Then lblCrCert.Text = myReader("Crane Certification") If Not IsDBNull(myReader("Repair Cost")) Then lblRepCost.Text = myReader("Repair Cost") If Not IsDBNull(myReader("Estimate Replacement")) Then lblEstRep.Text = myReader("Estimate Replacement") If Not IsDBNull(myReader("SalvageValue")) Then lblSalVal.Text = myReader("SalvageValue") If Not IsDBNull(myReader("CurrentValue")) Then lblCurVal.Text = myReader("CurrentValue") If Not IsDBNull(myReader("Comments")) Then lblCom.Text = myReader("Comments") If Not IsDBNull(myReader("Description")) Then lblDesc.Text = myReader("Description")
Hi,I need your help to resolve this problem. I have written a right outerjoin query between 2 indipendent tables as follows.select b.Account_desc, b.Account, a.CSPL_CSPL from Actual_data_final aright outer join Actual_account_Tbl b on a.account_desc =b.account_desc where (a.source_type = 'TY02' or a.source_type isnull) and (a.month = '2ND HALF' or a.month is null) and (a.year = 2004or a.year is null) and (a.product = 'NP' or a.product is null) orderby b.SnoBut the problem is I have few records in table Actual_account_Tbl butdo not match the condition "a.account_desc = b.account_desc".As per right outer join, I suppose to get those records as a result ofthe above query with null values of a.CSPL_CSPL. But it is notdisplaying.Please help me to resolve this problem.Regards,Omav
I am reporting on a system with 32 devices, each of these devices can have certain events that happen to it that are logged and timestamped. I need a table to show the count of each events that have happened to it within a certain time period. This code snippet below works fine BUT if there are no events that happen to a certain device in the time period, then that device is 'missing' from the table. What I need is basically a row for every device, regardless of if it has had any events happen to it (I will just show '0' for the event count) Any thoughts? I'm a complete newbie at this by the way.
Thanks
Code Snippet
SELECT DeviceStatusWords.DeviceName, COUNT(DeviceEventDurationLog.StatusBit) AS BitCount, DeviceEventDurationLog.StatusBit AS Bit FROM DeviceEventDurationLog RIGHT OUTER JOIN DeviceStatusWords ON DeviceEventDurationLog.DeviceID = DeviceStatusWords.DeviceID WHERE (DeviceEventDurationLog.TimeIn > @StartDate) AND (DeviceEventDurationLog.TimeIn < @EndDate) GROUP BY DeviceStatusWords.DeviceName, DeviceEventDurationLog.StatusBit ORDER BY DeviceStatusWords.DeviceName
I am stuck in a bit of a mess, and i really don't know how to get out of it.
I am a dot.net developer, working with MS SQL server 2000.
I am trying to write a query which essentially gives the amount of stock available for a particular stock_code.
select Stock_code, description from stock
Now what i want to do is, for each one of the stock_code that apears in the table above i want to look into another table called pop_item, and get the closest delivery_date for that particular stock_code. So i have top 1 and order it by delivery_date desc.
Individually for a particular stock_code, i can do this no problem. And here is my code for stock_code='E0016/6'
select top 1 stock_code, delivery_date, order_number,qty_order-qty_delivered as onorder from pop_item where stock_code='E0016/6' and qty_order>qty_delivered order by delivery_date desc
But I can't seem to be able to do this for all the stock_code, and not a specific one, cause even though i try and left outer join it, i can't access the outer stock_code from the first query into the next...
i.e
select stock.Stock_code, description, tempp.stock_code, tempp.delivery_date, tempp.onorder from stock
left outer join
(select top 1 stock_code, delivery_date, order_number,qty_order-qty_delivered as onorder from pop_item where
--Can't say this(stock_code= stock.stock_code and ) qty_order>qty_delivered order by delivery_date desc) as tempp
on tempp.stock_code=stock.stock_code
Now my question is, is there anyway to access stock.stock_code within the second query? Casue the whole query on top returns only one value for delivery_date, only of the highest delivery date in the whole of pop_item. which make sense... but i don;t know how to get around this...
OOOOOOOOOOOOOOOOOOhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!
Hope someone can help me.
Regards,
Munira
ps- should i be using a cursor, can i call cursors from asp.net. every where i read about cursors they adivice us not to use them.
Here is the content of the tbIntersect table: Car100_ID Car200_ID Car300_ID Car400_ID Car500_ID Car600_ID Car700_ID Prod_ID ID 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 19 1 3 1 1 1 1 1 20
I need to return the rows that have null data, ex: second row because Prod_ID is NULL and third row because Car300_ID is NULL. In fact I need the data from the other joint tables that correspond to these ID fields.
What is the best way to use a left join in a SQL statement with multiple tables (more than 2)? I have a query that uses 7 tables, where most of the joins are inner joins, except for one, which needs to be a left join. The current SQL statement looks something like this:
FROM [table1],[table2],[table3],[table4],[table5],[table6],[table7] WHERE [table4].[field2]=[table1.field2]{this is an inner join} [table4].[field2]=[table2.field2]{this is an inner join} [table4].[field2]=[table3.field2]{this is an inner join} [table4].[field2]=[table5.field2]{this is an inner join} [table5].[field3]=[table6.field2]{this is an inner join} [table5].[field4]=[table7.field2]{this is needs to be a left join}
As it stands now, the last line in the WHERE clause is an INNER JOIN and limits the number of rows in my result. I need to select rows from [table7].[field2] whether or not a matching record exists in [table5].[field4]. The other INNER JOINS in the SQL statement must have matching records. Please advise.
Hi - I'm struggling with a query, which is as follows. (I have changed the context slightly for simplicity)
I have 4 tables: users, scores, trials, tests Each pair of users takes a series of upto 4 tests in 1 trial, getting a score for each test. There are a different numbers of trials for each pair of users.
Important: Users do not take all tests. EG TrialId 1 contains userA & userB with userA scoring 10 on test1, 20 on test2 and userB scoring 30 on test2, 40 on test3, 50 on test4 and is userA & userB's 1st attempt. TrialId 2 may be the same, but their 2nd attempt. TrialId 3 may be the 1st attempt for 2 different users etc.
Suppose the Tests table has 4 tests (1,test1),(2,test2),(3,test3),(4,test4)
There are always 2 users for each trial id.
I want a query which will return all scores for all users for all trials, BUT must include NULLs if a user did not take a test on that trial.
I thought it may involve a cross join between the Tests table and the Trials table.
I was trying to run the follwoing query.It is giving me error
"select woancestor.wonum,wplabor.laborcode, wplabor.quantity,wplabor.laborhrs from wplabor,workorder left outer join woancestor on workorder.wonum=woancestor.wonum and wplabor left outer join labtrans on wplabor.laborcode=labtrans.laborcode where woancestor.ancestor='572099' and workorder.istask=1 and workorder.wonum=wplabor.wonum"
Error is "Server: Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'left'."
But the following query works fine
"select woancestor.wonum,wplabor.laborcode, wplabor.quantity,wplabor.laborhrs from wplabor,workorder left outer join woancestor on workorder.wonum=woancestor.wonum where woancestor.ancestor='572099' and workorder.istask=1 and workorder.wonum=wplabor.wonum"
Hi, I have this oracle query with outer join situation. how can i convert it into sql server query.
SELECT distinct ae.dB_CONTRACT,CP.PC_CODE,BID_ITEM.ITEM_NO, 'N',BID_ITEM.PRICE_WORDS,OFF_ITEM.DESCPT, OFF_ITEM.UNITS,OFF_ITEM.TYPE_ITEM, PRES_ITEM.RET_PERC FROM BID_TOTAL,BID_ITEM,OFF_ITEM,PRES_ITEM, AE_CONTRACT AE, CONTRACT_PC CP WHERE RANK_NUMB = 1 AND BID_TOTAL.DB_CONTRACT = 37044 AND BID_TOTAL.DB_CONTRACT = BID_ITEM.DB_CONTRACT AND BID_TOTAL.BID_VENDOR = BID_ITEM.BID_VENDOR AND BID_ITEM.DB_CONTRACT = OFF_ITEM.DB_CONTRACT AND BID_ITEM.ITEM_NO = OFF_ITEM.ITEM_NO AND OFF_ITEM.ITEM_NO = PRES_ITEM.ITEM_NO (+) AND AE.DB_CONTRACT=BID_TOTAL.DB_cONTRACT AND CP.DB_CONTRACT = AE.DB_CONTRACT AND CP.pc_code = 1
I need to convert a OUTER APPLY hint in my query to LEFT JOIN.How it can be done?The code which is presently is this: OUTER APPLY Additional Fields. nodes('/AdditionalFields/AdditionalField') AS AF (C)
Hi all: for example: testDataContext db=new testDataContext();var res=db.tables.single(p=>p.columnName=="hi"); if there is a record in the database, it works well, but if there isn't , it will throw an exception, then , How could I know the record exists or not ? I don't think exception is a resonable way. and in my opinion, there should be--------even must be ------a resonable way , to evaluate the query result to a bool variable, then program could judge the bool variable like : if(bExist) show("yes, I find it");else show("sorry, the record doesn't exist in the database"); I can't imagine I got the bool variable via exception... thanks to all..
I want to do a Query in Table ZT_TransFmt9_Headerto join with other Table and then get the value of KeepMonth from ZT_DataBackupbut Table ZT_TransFmt9_Header is far from away ZT_DataBackupit seems have to run a complicated SQL Query to reach goal..
select BusinessCode from ZT_BillerInfo A, ZT_TransFmt9_Header ins where A.JihsunCode=ins.StoreCode -----------ZT_TransFmt9_Header to join with ZT_BillerInfo for get BusinessCode when I get BusinessCode , next I need put BusinessCode in where clause to select data from zt_billerinfo ( Table zt_billerinfo have a column named BusinessCode which can mapping with the BusinessCode I have just select from ZT_BillerInfo and ZT_TransFmt9_Header and then join with Table zt_biller get value of CompanyCode, and then use company code in Table Databackup to get the keepmonth * I know my descrition may cause you feel confused. I past a Table picture herehttp://picasaweb.google.com.tw/jovi.fat/TAbleRelation/photo#5092934117841944082
Can Somebody please show me how to acheive this, using the order details in Northwinddatabase or any other good example. as much details as possible. Many Thanks!
Cod_Lingua - Des_Lingua ------------------------------ ITA Italian GER German ENG English FRA French
and another table with product/description
ProductID - Cod_Lingua - Description ------------------------------------------- 1 ITA Mia Descrizione 1 ENG My Description
I've this SELECT:
SELECT Tab_Lingue.Cod_Lingua, Descrizioni_Lingua.Description FROM Descrizioni_Lingua RIGHT OUTER JOIN Tab_Lingue ON Tab_Lingue.Cod_Lingua=Descrizioni_Lingua.Cod_Lingua WHERE Descrizioni_Lingua.ProductID=1
I get these results: ITA - Mia Descrizione ENG - My Description
I don't want this. I'd like to have this: ITA - Mia Descrizione ENG - My Description GER - (null) FRA - (null)
i need to retrieve the most recent timestamped records with uniquenames (see working query below)what i'm having trouble with is returning the next-most-recent records(records w/ id 1 and 3 in this example)i also need to return the 3rd most recent, 4th, 5th and 6th most recent- i figure if i can get the 2nd working, 3rd, 4th, etc will be cakethanks,brett-- create and populate tabledrop table atestcreate table atest(id int not null, name char(10), value char(10),timestamp datetime)insert into atest values (1,'a','2','1/1/2003')insert into atest values (2,'a','1','1/1/2004')insert into atest values (3,'b','2','1/1/2003')insert into atest values (4,'b','3','1/1/2002')insert into atest values (5,'b','1','1/1/2004')-- select most recent records with distinct "name"sselect a.* from atest as awhere a.id = (select top 1 b.id from atest as bwhere b.name = a.nameorder by timestamp desc )/*query results for above query (works like a charm)2a 1 2004-01-01 00:00:00.0005b 1 2004-01-01 00:00:00.000*/
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)