Re-write Nested Query With SQL

Feb 24, 2005

Hi folks,

I have a query which queries another query. I need to re-write the whole thing in SQL, but struggling with incorporating the nested query.

here's the main query:

SELECT tblProductSubCategory.SubCatDesc AS Products, qrySummaryStage3.[Early Cash Sales], qrySummaryStage3.[Late Cash Sales], qrySummaryStage3.[Cash Variance], qrySummaryStage3.[Cash Variance %], qrySummaryStage3.[Early Credit Sales], qrySummaryStage3.[Late Credit Sales], qrySummaryStage3.[Credit Variance], qrySummaryStage3.[Credit Variance %], qrySummaryStage3.[Early Total], qrySummaryStage3.[Late Total], qrySummaryStage3.[Variance Total], qrySummaryStage3.[Total Variance %], tblBudgetNew.Amount AS [Late Budget Amount], [Late Total]-[Late Budget Amount] AS [Budget Variance], qrySummaryStage3.[Early Cash Margin %], qrySummaryStage3.[Late Cash Margin %], qrySummaryStage3.[Early Credit Margin %], qrySummaryStage3.[Late Credit Margin %]
FROM (qrySummaryStage3 INNER JOIN tblBudgetNew ON qrySummaryStage3.SubCatID = tblBudgetNew.SubCatID) INNER JOIN tblProductSubCategory ON qrySummaryStage3.SubCatID = tblProductSubCategory.SubCatID
WHERE (((Month([date]))=1) AND ((Year([date]))=2005) AND ((tblBudgetNew.Site)=[Enter Site ID]) AND ((tblBudgetNew.Type)="Monthly Breakdown"));


and here's the nested query , called "qrySummaryStage3":

SELECT tblProductSubCategory.SubCatID, tblReportTemp1.[Early Cash Sales], tblReportTemp1.[Late Cash Sales], [Late Cash Sales]-[Early Cash Sales] AS [Cash Variance], IIf(nz([early cash sales],0)=0 Or [Early Cash Sales]=0,0,[Cash Variance]/[Early Cash Sales]) AS [Cash Variance %], tblReportTemp1.[Early Credit Sales], tblReportTemp1.[Late Credit Sales], [Late Credit Sales]-[Early Credit Sales] AS [Credit Variance], IIf(nz([Early Credit Sales],0)=0 Or [early Credit Sales]=0,0,[Credit Variance]/[Early Credit Sales]) AS [Credit Variance %], [Early Cash Sales]+[Early Credit Sales] AS [Early Total], [Late Cash Sales]+[Late Credit Sales] AS [Late Total], [Late Total]-[Early Total] AS [Variance Total], IIf([Early Total]=0,0,[Variance Total]/[Early Total]) AS [Total Variance %], IIf([Early Cash Sales]=0,0,([Early Cash Sales]-[Early Cash Cost])/[Early Cash Sales]) AS [Early Cash Margin %], IIf([Late Cash Sales]=0,0,([Late Cash Sales]-[Late Cash Cost])/[Late Cash Sales]) AS [Late Cash Margin %], IIf([Early Credit Sales]=0,0,([Early Credit Sales]-[Early Credit Cost])/[Early Credit Sales]) AS [Early Credit Margin %], IIf([Late Credit Sales]=0,0,([Late Credit Sales]-[Late Credit Cost])/[Late Credit Sales]) AS [Late Credit Margin %]
FROM tblReportTemp1 RIGHT JOIN tblProductSubCategory ON tblReportTemp1.ProductSubCatId = tblProductSubCategory.SubCatID;


Thanks in advance!

View Replies


ADVERTISEMENT

Modules & VBA :: Easy Way To Write Nested IF THEN ELSE IF Statements

Apr 12, 2015

How do you write complex nested IF THEN ELSE END IF statements..How do you know what IF statement to put first?Then how would you know where to put ELSE, or END IF?Before you start with the VBA, what are the foundations for making it work successfully, know where you are, know where to put END IF etc?

I've seen many times when using VBA people set up an initial foundation for writing code. For example when needing to put something in quotes, they do "" then enter the text in between, so they don't get errors on running (A very simple, crude example I know, but is there a similar basis for nested IFs).

View 6 Replies View Related

Nested Query Help Needed

Apr 26, 2006

Hello everyone,

I’m looking for some help with a “nested query”

I have four fields that typically have a quantity amount in them.

I also have a field with a date.

I would like to say something like this

If fielda = 0 and fieldb = 0 and field = 0 and fieldd = 0 and in the date field, the date is >30day from today’s date add a 1 to this field, otherwise leave it blank


Thanks a lot

Corey

View 2 Replies View Related

Nested Iif Statement! Not Sure Why This Query Will Not Run...help!

Aug 12, 2007

I'm wanting to run an update query but first I want to see the results by using a select query to make sure that I'm getting the correct results.

See the following query statement:

SELECT ([Goodrec - All] INNER JOIN WH_ACCTCOMMON ON [Goodrec - All].ACCTNO = WH_ACCTCOMMON.ACCTNBR) INNER JOIN [Trial-GL-Reference] ON WH_ACCTCOMMON.CURRMIACCTTYPCD = [Trial-GL-Reference].LOANTYPE SET [Goodrec - All].GLCODE = [TrialTotals].[glcode], [Goodrec - All].CURRBAL = IIf(Not IsNull([chgoffamt]) And Not IsNull([partsold]),CCur([grossbal])-CCur([chgoffamt])-CCur([partsold]),IIf(Not IsNull([CHGOFFAMT]),CCur([grossbal])-CCur([CHGOFFAMT]),IIf(Not IsNull([partsold]),CCur([grossbal])-CCur([partsold]),[grossbal]))), [Goodrec - All].PCTOWNED = IIf(Not IsNull([origamt]) And Not IsNull([partsold]), CCur([origamt])-CCur([partsold]/CCur([origamt]), IIf(IsNull([partsold]), [grossbal]));


This is the error that I receive each time I attempt to run it and I'm not sure what I'm missing.

Error message:

MICROSOFT OFFICE ACCESS
Syntax error(missing operator) in query expression '([Goorec-ALL] Inner Join WH_ACCTCOMMON ON [Goodrec-All].ACCTNO=WH_ACCTCOMMON.ACCTNBR) inner join [TRIAL-GL-Reference].LOANTYPE SET [Goodrec - All].GLCODE = [TrialTotals].[glcode]'


Any help with this issue would be greatly appreciated.

Thanks.

Govmate!

View 3 Replies View Related

Nested Query Confusion

Sep 23, 2007

Dear Access Expert

I have been doing some experimentation with Queries and I have discovered something unusual.

If I have one query and I use the totals feature (only using group by) I get all the records based on the inputed criteria

If I then use that same query as an underlying recordset for a second query and I use the totals feature (only using group by) in the second query... I only get the first record of each type. See query results below..

I am trying to achieve the results of the second query in the first query (DON'T WANT NESTED Queries) and I don't really understand why the results of the queries are different when everything else is the same other than one being nested.


Example below

First Query Results (using totals with group by)

1 a
1 a
1 a
2 a
2 a
2 a
3 a
3 a
3 a
4 a
4 a
5 a

Second Query Results with the First query as its recordset (using Group By)

1 a
2 a
3 a
4 a
5 a

View 3 Replies View Related

Inner Join Results From Nested Query.

Jul 29, 2007

Hi, I have a query that looks like:

SELECT * FROM ((TBL_Properties INNER JOIN TBL_Property_Landlords ON TBL_Properties.Property_ID=TBL_Property_Landlords. Property_ID) INNER JOIN TBL_Landlords ON TBL_Property_Landlords.Landlord_ID=TBL_Landlords.L andlord_ID) INNER JOIN TBL_Agents ON TBL_Properties.Agent_ID=TBL_Agents.Agent_ID;

so far. But I need to join the results from another query which will be calculating SUM(Pay). Is it possible to INNER JOIN to a: (SELECT ....) nested query?

Sorry if this is hard to understand.

Thanks.

View 3 Replies View Related

Update Query (with Nested Sql) Not Working

Sep 23, 2007

hi guys,
i have this sql that filters 2 tables to give me the highest number against a record and then i want to update the 1st table. but it dosnt seam to work it brings back the correct data but the sql has generated a non-updatable query.

any ideas?

UPDATE [SELECT ARCtblErrorInfo.Uber, Max(ARCtblHistory.Status) AS MaxOfStatus
FROM ARCtblErrorInfo LEFT JOIN ARCtblHistory ON ARCtblErrorInfo.Uber = ARCtblHistory.Uber
WHERE (((ARCtblErrorInfo.Status)=121))
GROUP BY ARCtblErrorInfo.Uber]. AS test INNER JOIN ARCtblErrorInfo ON test.Uber = ARCtblErrorInfo.Uber SET ARCtblErrorInfo.Status = [test].[MaxOfStatus];

View 1 Replies View Related

Queries :: How To Create Nested Query

Nov 14, 2013

I have done smoe baisc queries to sort, filter and report on data.How do I create a nested query where I don't repeat all the information across the query results line? Is there a way I can build a nested query to give all the SMCode codes associated with each appointment in one column separated by a coma?I have a table with appointments (APPTS):

RecID
ADate
ATime
Durantion
PVID
Desc
Case#

Then I have a table with Orders related to these appointments (ORDERS):

RecID
Case#
SMCode
SMDate

Here's my query:

SELECT DISTINCTROW Appts.RecID, Appts.ADate, Appts.ATime, Appts.Durantion, Appts.PVID, Appts.Desc, Orders.SMCode
FROM Appts INNER JOIN Orders ON Appts.[Case#] = Orders.[Case#];

My results look like this:

RecID ADate ATime Duration PVID Desc SMCode
RecID ADate ATime Duration PVID Desc SMCode
RecID ADate ATime Duration PVID Desc SMCode

I need my results to look like this:
RecID ADate ATime Duration PVID Desc SMCode,SMCode,SMCode...

View 3 Replies View Related

Queries :: Getting Parenthesis Error In Nested IIF Query

Apr 15, 2015

I have different product groups and they can have one of 3 rental rates(5,4,3%) I have written a nested query but I keep getting parenthesis errors, the last one I got told me I must enclose iif functions in parentheses. I know its probably a small thing but I just cant see it. By the way the server is German so ; need to be used instead of ,.

IIf([view_India]![Sub_Group] In (1730;1810;2870);5;iif Left([view_India]![Sub_Group];2) In (01;02;21;24;29)
;5;iif([view_India]![Sub_Group] In (3310;3330;3340;3360);3;4))))

View 2 Replies View Related

Modules & VBA :: How To Implement Variable In Nested Query

Jun 1, 2014

I have made this sql statement in VBA where rubriek = a variable but I dont know how to implement a variable in a nested query.

SELECT "rubriek, SUM(verkoopprijs) as prijzen
FROM voorwerp
(inner join VoorwerpInRubriek on voorwerp.voorwerpnummer = VoorwerpInRubriek.voorwerp)
inner join Rubriek on rubriek.rubrieknummer = VoorwerpInRubriek.rubriekOpLaagsteNiveau
where rubriek in (select rubrieknummer
from rubriek
where rubriek = variable name
)
group by rubriek"

Do I have to treat it as a normal select query or is there something speical that I have to do ?

View 5 Replies View Related

Using DSUM With A Query Name As Your Domain, And Having That Query Nested

Jul 6, 2005

The situation is I have two queries, one uses the other as a source, and the other uses DSUM with the source query as it's domain.

For example: I have one query called RetailCDState, this prompts the user for the name of a state (i.e. Texas), and then prompts for the name of the CD (i.e. Joshua Tree). The query returns the number of CD's sold for each retail store entered for that state.

I have another query called, TotalRetailState. This query uses RetailCDState as it's source. I pull some fields down into the QBE so that the CDname, state, artist name, etc will be shown. This works.

HERE IS THE PROBLEM. I have created 3 expression fields: TotalCDSOLD, TotalCDSHIP, and TotalCDRETURN. In these expression fields I have used DSUM, I want to use the query RetailCDState as the domain, which the help files said I can. However, it's giving me an expression error saying that it can't find the 'state' or 'CD Name', which is what should prompt the user when the whole thing is executed.

I get 3 error messages, one for each expression field, and then it prompts the user for the correct input, but then doesn't display the information. Here is an example of my DSUM line TotalCDSHIP: DSUM("[NumofCDSold]","RetailCDState")

I shouldn't need any criteria, because the results of the RetailCDState is what I want to total.

PLEASE HELP! :(

View 4 Replies View Related

How To Write Query

Aug 7, 2007

Hello, I need help writing a formula in a query

I have a database where I need to be able to pull different prices according to type.

For example, if it is a SH then I will need it to pull a certain price of an item under the SH level

if it is a DD, then I will need to pull a price of the item under the DD level

How can I write this formula in my query as an expression or do I need to write it as SQL dlookup.

If it is the dlookup, how do I write that.

Help!!!

View 1 Replies View Related

Please Help Write This Query

Feb 26, 2008

I having been going mad for a week trying to write a query, please help me.

I am trying to get the MaxServicedate for each Product (PIDFK) for every Location (LID), but then I also need the MaxServicedate regardless of Product use, for each Location that is smaller than the previosly obtained MaxServicedate.

I hope that makes sense.

I have tried this query
----------------------------------------------
SELECT T.LID,
T.PIDFK,
T.MaxOfServicedate,
Max(tblTakings.Servicedate) AS NextMax,
T.Installdate
FROM
(SELECT tblLocations.LID,
tblTakingsProductMM.PIDFK,
Max(tblTakings.Servicedate) AS MaxOfServicedate,
tblLocations.Installdate
FROM (tblLocations INNER JOIN tblTakings ON tblLocations.LID = tblTakings.FKLID)
INNER JOIN tblTakingsProductMM ON tblTakings.TID = tblTakingsProductMM.TIDFK
GROUP BY tblLocations.LID, tblTakingsProductMM.PIDFK, tblLocations.Installdate) AS T
LEFT JOIN tblTakings ON T.LID = tblTakings.FKLID
WHERE (((tblTakings.Servicedate)<[T].[MaxOfServicedate]))
GROUP BY T.LID,
T.PIDFK,
T.MaxOfServicedate,
T.Installdate
ORDER BY T.LID,
T.PIDFK
-------------------------------------
But I am missing some records!!

The subquery gives me all 90 records with the MaxServicedate for each PIDFK in each LID

The main query is missing the records that dont have a service date previous to the MaxServicedate in the subquery!

Any help appreciated.

Thanks

View 10 Replies View Related

Queries :: Make A Nested If Then Statement In A Query Field

Apr 27, 2014

I'm trying to make a nested if then statement in a query field, and I can't figure out why I can't get my formula to work:

Volume: IIf([MethodCode]="K",[total]*12.54*0.026873,IIf([MethodCode]="S",([length]*[width]*[depth])/2,IIf([MethodCode]="M" And [Location]="SH",[total]*5.08*0.026873,IIf([MethodCode]="M" And [Location]="C",[total]*18.58*0.026873," "))))

I keep getting the "data type mismatch in criteria expression" error. If I separate out all the individual if then statements individually, they work. But if I connect them all as a nested if then it doesn't work.

View 6 Replies View Related

Queries :: Nested IIF - Returning Calculated Results In A Query

Oct 30, 2013

What is the best approach to returning calculated results in a query. I have been using nested IIf statements that include DateAdd but I think that I am at a point where there must be a better way.

I want my query to calculate a date based on:
1) A Type field from my table
2) A calculated date based on other query fields.

My query has the following fields:
[Type] [Action 1] [Projected Action 1] [Projected Action 1 Revised] [Action 2]

I want to create a calculated field for [Projected Action 2] that says:

If [Type] is "A" then
if [Action 2] Is NotNull, Null
if [Action 1] is NotNull, [Action 1] + 10 workdays
if [Projected Action 1 Revised] is NotNull, [Projected Action 1 Revised] + 10 workdays
if [Projected Action 1] is NotNull, [Projected Action 1] + 10 workdays

[Code] ....

I would like to keep using nested IIf but I keep running into problems and I thought that there is probably a better way.

View 7 Replies View Related

General :: Add Query Controlled From Combo Box On Nested Form

Sep 5, 2013

I am having an issue with a database application I created. I needed to add another query that could be controlled from combo box on a nested form.

The combo box is for dates for entries in a table. Which then filters the query based on the combo box selection. Easy enough stuff.

The problem I am having is that when I try to use the combo box as a criteria for the query using;

[Forms]![MasterForm]![NavigationSubform].[Form].[comboBox]

Access closes and wont let me use the reference to the combo box.

What has happened? Corrupt database? How do I fix it?

View 9 Replies View Related

Creating A Query To Write A Value

Aug 12, 2005

I have a form (frmTraveler) in which a user is given a selection of levels for a type of trip from a drop down box (TripLevel). Basically, if a user picks level A, then I would like a value to be written to the corresponding record in another table (tblHotel). The PK is an autonumber (TravelID) and the tables have a one to many relationship. Hope that's enough information for some tips! :)

View 1 Replies View Related

Queries :: Complicated Query (nested Subqueries) For A Trend Graph

Apr 17, 2014

Some essential background first. I have a Balances table which records balances by date. I also have an Issues table where problems are logged. There is a one-to-many relationship between Balances and Issues (i.e. each Balance can have multiple Issues). I also have a Comments table where updates for each Issue are recorded. There is again a one-to-many relationship between Issues and Comments (i.e. each Issue can have multiple Comments)

There are two key date fields in the Issues table :FlagDate (the date an Issue was flagged by a user for investigation)

ResolveDate (the date said investigation was brought to a conclusion)

There is also a date field in the Comments table :UpdatedWhen (the date any given comment was added)

So the basic flow is that an Issue gets flagged (FlagDate), then various comments are added (multiple UpdatedWhen's) and finally the Issue gets resolved (ResolveDate)

I need to incorporate a trend graph which will show the counts ofNew (i.e. new issues flagged as of each day) Cleared (i.e. issues resolved each day)

Updated (i.e. issues not yet resolved but updated each day)

Unchanged (i.e. issues not yet resolved and not updated each day)

Outstanding (i.e. all unresolved issues as of each day)

This is the SQL I've put together to get that table of information on which to base my chart :

Code:
SELECT [tblBalances].[BalanceDate] AS AsOfDate,
(SELECT COUNT([tblIssues].[IssueID])
FROM [tblIssues]
WHERE [tblIssues].[Flag] = True
AND [tblIssues].[FlagDate] = [tblBalances].[BalanceDate]) AS New,

[Code] .....

The subqueries for 'New', 'Cleared' and 'Outstanding' work perfectly; the resultant dataset gives me one record for each date in the Balance table and correctly counts the number of issues falling into each of those buckets.

The problem I have is with the 'Updated' bucket. If a flagged issue happens to be updated twice on the same day (which is perfectly acceptable), it counts this twice as well. I don't want this as I just want to know how many issues were updated on any given day - not how many updates there were.

I tried using COUNT(DISTINCT) in the 'Updated' subquery but it gives me a syntax error - on further research, I don't think it's possible to use the DISTINCT keyword in a COUNT subquery (at least not easily)

I also tried grouping by IssueID within that 'Updated' subquery but it still gives me the duplicate count within the same IssueID (and returns nulls rather than zeroes for those days where no updates occured)

I think I need to add a subquery within the subquery () to only return the latest comment as of the date in question - something along the lines of :

Code:
(SELECT TOP 1 [tblComments].[UpdatedWhen]
FROM [tblComments]
WHERE [tblComments].[IssueID] = [tblIssues].[IssueID]
AND DateValue([tblComments].[UpdatedWhen]) <= [tblBalances].[BalanceDate]
ORDER BY [tblComments].[UpdatedWhen] DESC) AS UpdatedWhen

But how to do this, nor if it is even feasible in Access to begin with.

View 2 Replies View Related

Reports :: Record Source From Report Based On Nested Query?

Jul 24, 2015

I have a report that is based on nested (I think thats the phrase) query's.

Complicated Query based on another query (so I can't see a way to get at the the source SQL to change or use elsewhere)

This gives a list of say 20 records I generally want printed. I use the exact same query criteria with a separate update query to add the same to a table.

However I then wanted to just pick one with exact matching ID's I select on a form.

I could not see an easy way to apply this without making another set of nested querys which seems a little excessive

Anyway, an easy way for the printed report to do this is a simple filter added after, works great.

I can't see a way to do the same for an update query.

I was wondering if I could get the record source of this report and add to my table. I have tried with

' Dim db As DAO.Database
' Dim rs As DAO.Recordset
'Set db = CurrentDb
'Set rs = db.OpenRecordset(Me.RecordSource, dbOpenDynaset)
' Set rs = CurrentDb.OpenRecordset(Me.RecordSource)

And dozens of variations over some hours but a variety of errors mainly "too few parameters."

View 3 Replies View Related

How To Write Conditional Expression In Query?

Mar 16, 2005

Hi,

I have problem in creating conditional expression for query table. I want to add IF Else statement in the statement so that if the value is more than 50, a new field called grade will display the grade of "A" in the new field.

Can anyone teach me how to write conditional expression.

Thanks
Dawn

View 4 Replies View Related

Modules & VBA :: How To Write A Function That Does Query

Jul 22, 2013

I have a query string in the following code. I want to put the entire code into a function so I can use it somewhere else as well.

Code:

Private Sub Form_Load()
'To enable the AllowAddition property once the form is opened
Dim dbs As DAO.Database

[Code]......

View 5 Replies View Related

Queries :: Nested Query - Left Outer Join Not Returning All Records

Oct 1, 2014

I have a simple nested query that is not working as expected. My inner query returns 102 records but when I run with outer query I only get 96 records. Below is my query, I don't really want to pull the same fields from both tables but I was doing to test. The values that are missing are those that don't exist with the monthenddate 8/31/2014 - a left join should fix that but doesn't seem to be working ..

Code:

Select distinct a.entity, a.gl_account,a.profit_center,[Open Items_1].profit_center,[Open Items_1].gl_account,[Open Items_1].entity
from(
SELECT DISTINCT [Open Items].entity, [Open Items].gl_account, [Open Items].profit_center
FROM [Open Items]
)a
left outer JOIN [Open Items] AS [Open Items_1] ON
(a.profit_center = [Open Items_1].profit_center) AND (a.gl_account = [Open Items_1].gl_account) AND (a.entity = [Open Items_1].entity)
Where ([Open Items_1].MonthEndDate=#8/31/2014#)

View 1 Replies View Related

Write A Query That Will Return Records From Multiple Tables

Dec 19, 2012

I am trying to write a query that will return records from multiple tables. I currently get an error suggesting I create a subquery or else I get far too many records.

The query is EditAttendanceQuery (I left it in a bit of a state). The fields I need are shown in the query. The records I need are based on the Edit AttendanceQuery (Form). I can get the records I need without the CourseNumber and Section, but it all goes downhill when I include them.

View 14 Replies View Related

Write A Concatenate Query And Display Result In A Text Box On A Form

Jul 20, 2005

Here's the form I'm trying to Create:

VEH POS NAME
A21: TC: CPT Somebody
G: SGT Someoneelse
D: PVT Noone

A22: TC: SFC Smith
G: SGT Jones
D: PVT Doe

and so on and so forth.

The VEH and POS are just going to be Labels in a form....no prob. Each Soldier's Squad and Team (for mounted Vehicle and Position) are stored in the Personnel Table. The below query is for vehicle A7 (ACTUAL would be the same as TC above). The query works. I just need to know how to get the result to display in a text box. What I'm planning on doing is creating text boxes for each posistion with these small select queries, so when I update the SQD and Team in the Personnel Table it updates on this form. Or is there an easier way to do this?

Dim strSQL as string
strSQL="SELECT [tblPERSONNEL]![RANK] & " " & [tblPERSONNEL]![LAST_NAME] AS NAME
FROM tblPERSONNEL
WHERE (((tblPERSONNEL.SQD)="A7") AND ((tblPERSONNEL.TEAM)="ACTUAL"))"

View 3 Replies View Related

Queries :: Write Records From Field Of Query To Irrelevant Table?

Apr 28, 2014

I have a query with many fields. One of them is the combination of two fields and is called "Components Reference". What I try to do is, every time this query is updated, the records of only this field "Components Reference" to be written to the field of another table which also takes records from an another query. I wish I was clear enough.

View 13 Replies View Related

Queries :: Write A Query To Pull Out Dates With Current Year Only?

Jul 18, 2013

all using access 2010. I have a date field. I need to write a query to pull out dates with current year only. ex data: 1/1/10, 1/1/11, 2/1/12, 2/1/13. Need to pull all dates with current year which would be 2/1/13. Tried in query criteria of the date field: =Format(Now(),"yyyy") I received data mismatch. this is a date/time field.

View 4 Replies View Related







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