I have to join two tables and i need to fetch All records from @tab2 and only max date record from @tab1 that ID is present in Tab2
1.) @Tab1 have multiple records for each ID
2.) @Tab2 also have multiple records for each ID
3.) Kind of Lef Outer join those tables with ID and take all records from @tab2 and only Max of date from @tab1 and order by ID and Date
Note: @Tab1 always have lesser dates than @tab2 for each ID
Tables looks like as follows
declare @tab1 table (id varchar(3), effDt Date, rate int) insert into @tab1 values ('101','2013-12-01',5) insert into @tab1 values ('101','2013-12-02',2) insert into @tab1 values ('101','2013-12-03',52)
[code]....
In the given ex, ID 103 should not come as it is not present in @tab2, ID 104 should come even it is not present in @tab1 as we ahve to use left outer join Result should like follows.
Table A: ID (unique-identifier) Table B: ID_A (unique-identifier to A.ID, relation)
DTime (datetime)
Rows (id1 and id2 are Id examples): A: id1 id2 B: id1 and 12:00:00 (date not important) id1 and 13:00:00 id2 and 12:00:00
Example: SELECT A.ID, B.DTIME FROM A LEFT JOIN B ON B.ID_A = A.ID WHERE B.DTime < '14:00:00' ORDER BY NEWID()
When I run this, I get the three rows of table B. But what I want is to get each table A row once, and get the nearest datetime of WHERE expression from the relation of table B. So, the result must been two rows, id1 and id2, and id1 with '13:00:00' row because this is the nearest value of '14:00:00'.
How can I do this? DISTINCT trying by A.ID of SELECT, but doesn't work. Also ORDER BY B.DTime will work, but not random by NEWID() anymore.
This is actually not asp.net, but I'm hoping someone can help me. I have a report that is pulling from a couple of different tables. I am trying to add a meal choice to the report. Let's say they have the option of choosing chicken, beef or fish. They check the checkbox next to the choice. My report is pulling the infor, but it is putting 3 rows for each person not taking into consideration what choice they chose. The checkbox's all write to the same column - ses. Here is the code for the stored procedure: CREATE PROCEDURE [dbo].[spGetCourseEmailList1]( @Code1 char(9)) AS SELECT DISTINCT dbo.[names].lname as LastName, dbo.[names].fname as FirstName,dbo.[evser].ses as MealChoice,dbo.[evldg].paid as AmountPaid, dbo.[names].gp as PreferredAddress, dbo.[names].mi as MiddleInitial, dbo.[names].nname as NickName, dbo.[names].xname as Suffix, dbo.[names].hphone as HomePhone, dbo.[names].email as EmailAddress, dbo.[names].addr1 as HomeAddress1, dbo.[names].addr2 as HomeAddress2, dbo.[names].city as City, dbo.[names].st as State, dbo.[names].zip as ZipCode, dbo.[firms].fname1 as FirmName1, dbo.[firms].fname2 as FirmName2, dbo.[firms].faddr1 as FirmAddress1, dbo.[firms].faddr2 as FirmAddress2, dbo.[firms].fcity as FirmCity, dbo.[firms].fst as FirmState, dbo.[firms].fzip as FirmZip, dbo.[firms].fphone as FirmPhone, dbo.[names].udflist1 FROM dbo.[firms] INNER JOIN dbo.[names] ON dbo.[firms].firm = dbo.[names].firm INNER JOIN dbo.evldgON dbo.[names].id = dbo.[evldg].id INNER JOIN dbo.evregON dbo.[evldg].id = dbo.[evreg].id Full OUTER JOIN dbo.evserON dbo.[evreg].code1 = dbo.[evser].code1 WHERE dbo.[evldg].code1 = @Code1 AND dbo.[evreg].code1 = @Code1 AND dbo.[evser].code1 = @Code1 AND dbo.[names].xwebflag <> 'Y'ORDER BY dbo.[names].lname, dbo.[names].fnameGO The items in bold are what I added.
I have this INNER JOIN that is fine to show all possible combinations. But I need to show only rows that have one or more Null values in tbIntersect.
Should I use nested LEFT JOINT? How?
This is the SQL statement: sSQL = "SELECT DISTINCT tbCar100.Car100_ID, tbCar100.Description100 AS [Caractéristique 100], " & _ "tbCar200.Car200_ID, tbCar200.Description200 AS [Caractéristique 200], " & _ "tbCar300.Car300_ID, tbCar300.Description300 AS [Caractéristique 300], " & _ "tbCar400.Car400_ID, tbCar400.Description400 AS [Caractéristique 400], " & _ "tbCar500.Car500_ID, tbCar500.Description500 AS [Caractéristique 500], " & _ "tbCar600.Car600_ID, tbCar600.Description600 AS [Caractéristique 600], " & _ "tbCar700.Car700_ID, tbCar700.Description700 AS [Caractéristique 700], " & _ "tbProducts.Prod_ID, tbProducts.PartNumber AS [Part Number] , tbProducts.Description AS [Description] , tbProducts.DateAdded AS [Date] " & _ "FROM tbProducts INNER JOIN (tbCar700 INNER JOIN (tbCar600 INNER JOIN (tbCar500 INNER JOIN (tbCar400 INNER JOIN (tbCar300 INNER JOIN (tbCar100 INNER JOIN " & _ "(tbCar200 INNER JOIN tbIntersect ON tbCar200.Car200_ID = tbIntersect.Car200_ID) " & _ "ON tbCar100.Car100_ID = tbIntersect.Car100_ID) ON tbCar300.Car300_ID = tbIntersect.Car300_ID) ON tbCar400.Car400_ID = tbIntersect.Car400_ID) ON tbCar500.Car500_ID = tbIntersect.Car500_ID) ON tbCar600.Car600_ID = tbIntersect.Car600_ID) ON tbCar700.Car700_ID = tbIntersect.Car700_ID) ON tbProducts.Prod_ID = tbIntersect.Prod_ID " & _ ";"
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.
i have a query when i run it shows data rows repeating like 5 times. I am not sure what am i doing wrong. hope someone can help me out. this is my query. SELECT "INVOICEDETAILS"."SeviceAmount", "RptSalesUser"."SalesPersonId", "RptSalesUser"."SalesPersonName", "RptSalesUser"."TemplateStatus", "INVOICE"."InvoiceDate" FROM ("imacstest"."dbo"."INVOICE" "INVOICE" INNER JOIN "imacstest"."dbo"."INVOICEDETAILS" "INVOICEDETAILS" ON "INVOICE"."InvoiceNo"="INVOICEDETAILS"."InvoiceNumber") INNER JOIN "imacstest"."dbo"."RptSalesUser" "RptSalesUser" ON ("INVOICE"."InvoiceNo"="RptSalesUser"."invoiceNumber") AND ("INVOICEDETAILS"."InvoiceNumber"="RptSalesUser"."invoiceNumber") WHERE "RptSalesUser"."TemplateStatus"='A' AND ("INVOICE"."InvoiceDate">={ts '2007-01-01 00:00:00'} AND "INVOICE"."InvoiceDate"<{ts '2007-12-13 00:00:00'}) AND "RptSalesUser"."SalesPersonId"=5 and "Invoice"."InvoiceNo"='1004447' ORDER BY "RptSalesUser"."SalesPersonId","Invoice"."InvoiceDate" when i execute this i get about 12 data rows which are fine but then the same 12 data lines repeats 4 more times. hope someone be able to help me quick.
Ok, so I've been racking my brains on this one for a while now and figured it was time to ask for some help...
I have a table named tblAppInfo that looks something like this:
Code Block user_name app_name app_ver
User1 MS Word 2000 User2 MS Word 2000 User3 MS Excel 2000 User4 MS Excel 2000 User5 MS Excel 2000 User6 MS Excel 2000 User7 MS Outlook 2000 User8 MS PowerPoint 2000 User9 Adobe Acrobat 5.0 User10 Adobe Acrobat 6.0 User11 Adobe Acrobat 7.0
What I want to do is remove any rows that repeat the app_name and app_ver more than twice. Basically in the example above, it would remove the lines that have MS Excel 2000 (as it's listed 4 times). MS Word 2000 would stay as it's only listed twice. As would Outlook and PowerPoint. All 3 Adobe's would also stay as their versions are different.
I've tried the following but it still repeats applications that occur more than twice:
Code BlockSELECT user_name, app_name, app_ver FROM tblAppInfo GROUP BY app_name, app_ver, user_name having count(distinct app_name + app_ver + tblAppInfo.host_name) < 3 ORDER BY app_name, app_ver
I've also tried using nested select statements and everything else in my arsenal to no avail. I hope someone here will be able to help me out as I'm afraid I'll go bald if I try anymore!
I'm trying not to use a temp table, but i may have to do so.. I'm using sql2005 for this case.
i have a derived table that makes the following results:
ID Status Name
2 1 "A"
2 2 "B"
I want to get the following:
ID Name1 Name2
2 "A" "B"
but like I said before, I can't repeat the query that gets the first 2 rows, as it's pretty invovled. a temp table is the best route I see right now, but I just wanted to be sure I'm not missing something. If I've aliased it as 'results', is there a way to alias results again as something else? or maybe a trick with CTEs? I will try that! It seems promising.
I'm trying not to use a temp table, but i may have to do so..
i have a derived table that makes the following results:
ID Status Name 2 1 "A" 2 2 "B"
I want to get the following: ID Name1 Name2 2 "A" "B"
but like I said before, I can't repeat the query that gets the first 2 rows, as it's pretty invovled. a temp table is the best route I see right now, but I just wanted to be sure I'm not missing something.
I have two tables. Table 1 contains a distinct ID(3,4,5). Table 2 contains multiple ID's(3,3,3,3,3,4,4,4,5,5,5). I want to be able to use a join. If an ID is found in table 2, remove all entries of it. Any ideas? Thanks...
delete b.id from table1 a join table2 b on a.id = b.id
Current ResultSet ------------------ ColA ColB TEST1 111 TEST1 222 TEST2 333 TEST3 444 TEST3 555
I am currently outer-joiing two tables to retrive some data in the above format. My intent is to modify the query so I can retrive the data in below fashion.
This is my sql string. It counts all the rows in Questions table but it should only count the rows where id in Quizzes matches the quiz column in Questions table.
"select Quizzes.name, Quizzes.id, count(Questions.quiz) as total from Quizzes inner join Questions on Quizzes.id=Questions.quiz"
Hi, I would appreciate help on the following query I got stuck with;
I've got 2 tables "AccountList" and "PeriodBalance"; I need to return all the accounts form "AccountList" and their balance form "PeriodBalance"; The user will select a period for which the balances should be returned, if there is no balance for the period... 0 should be returned. "PeriodBalance" would not have an entry if there is no balance for the period.
There is only 3 possible periods (1, 2 or 3) And there is only one balance per period per account;
This is what is what I need returned by the query, assuming we are selecting PerID 2: (WHERE PerID=2) AccNo PerID PerBal 100 2 1750 200 2 0 300 2 0
I've included ISNULL(PerID,4) = 4 in my WHERE clause...this worked for returning AccNo 200. My problem is AccNo 300 in not NULL....it has values, just not for the selected PerID...so how do I get AccNo 300 to be included in my Query result?
This is my SQL Query: SELECT AccountList.AccNo, PeriodBalance.PerID, PeriodBalance.PerBal FROM AccountList LEFT OUTER JOIN
PeriodBalance ON AccountList.AccNo = PeriodBalance.AccNo WHERE PeriodBalance.PerID = 2 OR ISNULL(PerID,4) = 4
I got the following query:SELECT TOP (8) ext.extID, ext.Quote, ext.sourceTitle, ext.extRating, gf_game.gameID, gf_game.catID, gf_game.URL, gf_game.TitleFROM gf_game_ext AS ext INNER JOIN gf_game ON gf_game.gameID = ext.gameIDWHERE (ext.Approved = 1)ORDER BY ext.extID DESC which is e.g. producing this output: 6000 -some text- Title 90 1960 2 tom-cl tom cl5999 -some text- title 90 1960 2 tom-clcl asdf5998 -some text- title 90 1959 2 tom-cl-cl asdfWhat I'd like to do now is to filter out the duplicate GameIDs (= 1960) so that just one unique row with the gameid 1960 is remaining. If I put in a SELECT DINSTINCT TOP(8) it just counts for the table ext, but I need it to count for gf_game.gameID - is that possible?Thanks a lot!
I am trying to build a association table (t2) to store a list of users have viewed an item in my records table (t1). My goal is to send the UserID parameter to the query and return to the user a read / not read marker from the query so I can handle the read ones differently in my .net code. The problem is that I cannot work out how to return anything but the read data to the client. So far my stored proc looks like this
DECLARE @UserID AS Int -- FOR TESTING SET @UserID = 219 -- FOR TESTING
SELECT t1.strTitle, t1.MemoID, Count(t2.UserID) AS ReadCount,t2.UserID
FROM t1 LEFT OUTER JOIN t2 ON t1.MemoID = t2.MemoID
WHERE t2.UserID = @UserID
GROUP BY t1.MemoID, t1.strTitle,t2.UserID
It works fine but only returns those records from t1 that are read. I need to return the records with null values also! I may have built the assoc table wrong and would really appreciate some pointers on what I am doing wrong. (assoc table has rID, MemoID and UserID columns)
SELECT [tblSections].[pageTitle], [tblSections].[sectionURL], [tblSectionContents].[articleID], [tblSectionContents].[fileID], [tblSectionContents].[linkID], [tblCopy].[copyText], [tblFiles].[fileName], [tblFiles].[fileCaption], [tblGroupings].[grouping], [tblLinks].[linkURL] FROM [tblSections] LEFT JOIN [tblSectionContents] ON [tblSectionContents].[sectionID] = [tblSections].[id] LEFT JOIN [tblCopy] ON [tblSectionContents].[articleID] = [tblCopy].[id] LEFT JOIN [tblFiles] ON [tblSectionContents].[fileID] = [tblFiles].[id] LEFT JOIN [tblGroupings] ON [tblFiles].[groupingID] = [tblGroupings].[id] LEFT JOIN [tblLinks] ON [tblSectionContents].[linkID] = [tblLinks].[id] WHERE [tblSections].[id]=2 ORDER BY [tblSectionContents].[articleID], [tblSectionContents].[fileID], [tblSectionContents].[linkID]
If I pass it the ID of a section that has files or copy or [stuff in other tables] attached, then I get a result set that makes sense.
But if I pass it a section ID that doesn't reference any other content tables (ie: the section just has a title and a link URL), I don't get anything back.
Shouldn't it should still get me the fields from the row in tblSections that matches the ID I'm passing it?
select sq.*, p.numero, p.nombre from paf p right outer join dbo.GetListOfSquaresForShippingLot(@lot) sq on sq.number = p.numero and sq.version = p.numero
The @lot parameter is declared at the top ( declare @lot int; set @lot = 1; ). GetListOfSquaresForShippingLot is a CLR TVF coded in C#. The TVF queries a XML field in the database and returns nodes as rows, and this is completed with information from a table.
If I run a query with the TVF only, it returns data; but if I try to join the TVF with a table, it returns empty, even when I'm expecting matches. I thought the problem was the data from the TVF was been streamed and that's why it could not be joined with the data from the table.
I tried to solve that problem by creating a T-SQL multiline TVF that is supposed to generate a temporary table. This didn't fix the problem.
What can I do? Does anybody know if I can force the TVF to render its data somewhere so the JOIN works? I was thinking a rowset function could help, but I just can't figure out how.
PLEASE HELP!!!!
Let me know if you want the code for the CLR TVF. This is the code for the T-SQL TVF:
CREATE FUNCTION [dbo].[GetTabListOfSquaresForShippingLot] ( @ShippingLot int ) RETURNS @result TABLE ( Number int, Version int, Position smallint, SubModel smallint, Quantity smallint, SquareId nvarchar(5), ParentSquareId nvarchar(5), IsSash smallint, IsGlazingBead smallint, Width float, Height float, GlassNumber smallint, GlassWidth float, GlassHeight float ) AS BEGIN INSERT INTO @result SELECT * FROM dbo.GetListOfSquaresForShippingLot(@ShippingLot)
I have a problem with a Merge Join providing no output (when it should have 1890 rows). My Data Flow Task has 4 OLE Data Sources, 3 Multicasts, and 1 OLE Data Destination. I am experiencing the problem near the end of my data flow where two Multicasts create two parallel flows of data (see Level 1 below). I have two Merge Joins which join one leg from each multicast with a leg from the other multicast (see Level 2 below). Then the two remaining legs use a Merge to get my destination output (see Level 3 below).
I am experiencing my problem with the Merge Join (input A2, B2) --> (output C2) transformation. The Merge Join providing output C1 appropriately outputs 1890 rows, but C2 outputs 0 rows. Both Merge Joins are identical. The data is identically sorted prior to entering the problematic Merge Join and a DataViewer (Grid) verified that the data is appropriately entering in. Merge Join (input A2, B2) --> (output C2) has 667 rows as input A2 and 1890 rows as input B2 (using an inner join, just like the other merge join), but C2 baffles me with 0 rows of output (when it too should have 1890). I receive no Ouput errors and the execution completes showing all green.
I read about mysterious behavior with Merge Joins and have attempted modifying my EngineThreads property to values between 2 and 10, with no luck. Any help/ideas would be appreciated.
Just trying to select a set of Articles from a SQL Server Database. The Articles all have a Category ID which is stored in another table (as an Article could be in more than one Category). I want to select the Top 3 Articles in a Category. At the moment I have as my SQL;
"SELECT TOP 3 f.ArticleID, f.Heading, f.Summary, f.WrittenDate, f.ArticleURL FROM feedTable f LEFT JOIN Categories c ON f.ArticleID = c.ArticleID WHERE c.CategoryID=" + CategoryID + " AND c.ArticleID<>" + id + " ORDER BY c.CategoryID"
Which seems to work to an extent in that I do get three articles in the same Category appearing. However, there are sometimes duplicates appearing, so I need to incorporate a DISTINCT clause to the above. I'm not sure where to put this in though. Any ideas?
Having one invoice table (ord) and one 'person' table (actor) I would like to include the name of the person who is responsible for an invoice: SELECT Ord.OrdNo, Ord.Selbuy, AC.Nm AS 'Responsible', AC.EmpNoFROM OrdLEFT OUTER JOIN Actor AS AC ON Ord.Selbuy = AC.EmpNoWHERE ord.ordno = 23505 This works perfectly fine if Ord.Selbuy has a corresponding value in Actor:|26914 |21|Yvonne| 21| or if there is no corresponding value in Actor:|26914 |21|NULL| NULL| But what if Ord.Selbuy=0? Then I end up with 3285 rows from Actor! This happens because Actor.EmpNo=0 is allowed. Persons which have never been employed or used to be employed gets Actor.EmpNo=0.Can I create a SELECT statement which only returns data from the INVOICE row if Ord.Selbuy=0?|26914 |21|NULL| NULL| p.s. I'm not able to change table structure/behavior of update procedures, because the tables/code belong to a "bought from the shelf"-business system.
I am using SLQ Server 2008 R2. The database was designed by another company.
I have two tables: Client and Client_Location. In the Client table the pk is Client_ID. There is also a unique key: sys_Client_ID. Both the Client_ID and the sys_Client_ID fields exist as a foreign keys in the Client_Location table. However, the fields are not noted as unique in the Client_Location table. There are two fields in the Client_Location table that determine when the address was effective. They are from_dt and end_dt.
Multiple records have been loaded into the Client_Location table to track old as well as current addresses of clients.
I'm trying to run a report that will pull clients with a plan_id constraint from the Client table and join the Client_Location table to retrieve the current address of these clients.
My SQL is:
select distinct (a.client_id), a.cli_last AS Last_Name, a.cli_first AS First_Name, a.cli_middle AS Mid_Init, b.city AS City, b.county AS County, b.state AS State from ECBH.dbo.tbl_Client a inner join ECBH.dbo.tbl_Client_Location b on a.client_id = b.client_id inner join ECBH.dbo.tbl_client_insurance c on a.client_id = c.client_id inner join ECBH_TEST.dbo.tbl_GEF_County d on b.county = d.COUNTY_NAME where c.plan_id = 4 order by a.cli_last, a.cli_first
Because multiple records exist in the Client_Location table, the result set has duplicates. How can I pull only the results where the from_dt is most recent?
SELECT R.name, R.age,R.DOB, ISNULL(D.Doc1,'NA') AS doc1, ISNULL(C.Doc2,'NA') AS doc2 FROM REQ R inner join RES S ON R.Request_Id=S.Request_Id inner join RES1 D ON D.Response_Id=S.Response_Id inner join REQ1 C ON C.Request_Id=R.Request_Id
select * from RES1 where Response_Id = 111 -- return 3 select * from REQ1 where Request_Id = 222 --- returns 2
So at last inner join retuns 3*2 = 6 records , which is wrong here and i want to show 3 records in doc1 row and 2 records in doc 2 rows ...
Please refer to the below query. I want to filter inner join rows based on outer query column value (refer to bold text).
SELECT M.MouldId, SI.StockCode, MI.Cavity, MI.ShotCounter, CQ.SumOfCastedQty as CastedQty, MI.CounterStartup FROM MouldItem MI JOIN (SELECT JD.MouldId, JC.StockCode, SUM(JS.CastedQty) AS SumOfCastedQty FROM JobCasting AS JS INNER JOIN JobCreationDet AS JD ON JS.JobDetId = JD.Uniid INNER JOIN JobCreation AS JC ON JD.JobIdx = JC.Uniid
I've met a curiouse thing when using full outer join, that I got some rows belong to neither tables @_@
The SQL statement is like this:
SELECT PreviousMonth.InvoiceID, PreviousMonth.CategoryName, PreviousMonth.ProdName, PreviousMonth.Qty, ISNULL(CurrentMonth.SellTotal, 0) AS SellTotal, ISNULL(PreviousMonth.SellTotal, 0) AS PriorSellTotal
FROM (SELECT SellTotal, InvoiceID, CategoryName, ProdName, Qty FROM viewProdSales AS viewProdSales_1 WHERE (DateCreated >= @pStartDate) AND (DateCreated <= @pEndDate)) AS CurrentMonth
FULL OUTER JOIN (SELECT SellTotal, InvoiceID, CategoryName, ProdName, Qty FROM viewProdSales WHERE (DateCreated >= @pPriorStartDate) AND (DateCreated < @pStartDate)) AS PreviousMonth
ON CurrentMonth.InvoiceID = PreviousMonth.InvoiceID
The result include some added rows, if I query the 2 sub table seperately, neither contains such rows.
For example, if I pass 01/09/2006, 01/10/2006 and 31/10/2006 as pPriorStartDate, pStartDate and pEndDate, to query the sales statistics in Sept and Oct, I would get some reords in June or even earlier... Anyone know about this? Thanks in advance.
I have 4 tables (SqlServer2000/2005). In the select query, I have FULL JOINED all the four tables A,B,C,D as I want all the data. The result is as sorted by DDATE desc:- AID BID BNAME DDATE DAUTHOR 1 1 abcxyz 2008-01-20 23:42:21.610 c@d.com 1 1 abcxyz 2008-01-20 23:41:52.970 a@b.com 1 2 xyzabc 2008-01-21 00:17:14.360 c@d.com 1 2 xyzabc 2008-01-20 23:43:17.110 a@b.com 1 2 xyzabc 2008-01-20 23:42:43.937 a@b.com 1 2 xyzabc NULL NULL 2 3 pqrlmn NULL NULL 2 4 cdefgh NULL NULL Now, I want unique rows from the above result set like :- AID BID BNAME DDATE DAUTHOR 1 1 abcxyz 2008-01-20 23:42:21.610 c@d.com 1 2 xyzabc 2008-01-21 00:17:14.360 c@d.com 2 3 pqrlmn NULL NULL 2 4 cdefgh NULL NULL I want to remove the duplicate rows and show only the unique rows but contains all the data from the first table A. I have to bind this result set to a nested GridView.
I am struggling with the below join block in my stored procedure. I can't seem to get the duplicate row problem to go away. It seems that SQL is treating each new instance of an email address as reason to create a new row despite the UNIONs. I understand that if I am using UNION, using DISTINCT is redundant and will not solve the duplicate row problem.
Primary Keys: none of the email address columns are primary keys. Each table has an incrementing ID column that serves as the primary key.
I am guessing I am encountering this problem because of how I have structured my Join statements? Is it possible to offer advice without a deeper understanding of my data model or do you need more information?
Thanks for any tips.
Code:
select emailAddress from Users union select user_name from PersonalPhotos union select email_address from EditProfile union select email_address from SavedSearches union select distinct email_address from UserPrecedence union select email_address from LastLogin) drv Left Join Users tab1 on (drv.emailAddress = tab1.emailAddress) Inner Join UserPrecedence tab5 on tab5.UserID=tab1.UserID Left Join PersonalPhotos tab2 on (drv.emailAddress = tab2.user_name) Left Join LastLogin tab4 on (drv.emailAddress = tab4.email_address) Left Join EditProfile tab3 on (drv.emailAddress = tab3.email_address) Left Join SavedSearches tab6 on (drv.emailAddress = tab6.email_address
SELECT PR.WBS1, PR.WBS2, ledgerar.invoice, SUM(CASE WHEN ledgerar.transtype = 'in' AND ledgerar.period = '200405' THEN ledgerar.amount * - 1 END) AS amount FROM PR LEFT OUTER JOIN LedgerAR ON LedgerAR.WBS1 = PR.WBS1 AND LedgerAR.WBS2 = PR.WBS2 AND LedgerAR.WBS3 = PR.WBS3 WHERE (LedgerAR.wbs1 = '001-333') AND ledgerar.period = '200405' GROUP BY pr.wbs1, pr.wbs2, ledgerar.invoice
But I don't know how to get the query to display all of wbs2 whether it is null or not. So, for each invoice number there should be five records according to the wbs2 codes (500, 100, 140, 150, 160)