Microsoft Access: Query by Form with Multiple Criteria and Possible Blanks in SQL View - sql

I have started to create a Query by Form using the Form QueryHelp and the Query called DEALLOG3. My goal is for the user to be able to filter by Submarket, Building Type, and a sale date range. With the criteria I have now, it works fine in most scenarios where all of the comboboxes have values. However, when one of the comboboxes is blank, I want to be able to still have the other two criteria working, while showing all of the records for the blank field. (ex: Tampa Submarket, [Blank] Building Type, and a sale date from 01/01/2000 to 01/01/2016).
I've been scouring this sight for the past two days and can't find anything that will work. I think I might be looking for a dynamic query, but I am unsure. Here is what I have currently, please let me know if you can help:
SELECT DEALLOG3.PROPERTY, DEALLOG3.CODE, DEALLOG3.CLOSED, DEALLOG3.Submarket, DEALLOG3.NRA, DEALLOG3.PRICE, DEALLOG3.OCCUPANCY, DEALLOG3.[5 YR IRR], DEALLOG3.PURCHASER, DEALLOG3.SELLER, [PRICE]/[NRA]
AS PSF, [DEALLOG3]![NOI]/[PRICE]
AS [Cap Rate], DEALLOG3.[Building Type]
FROM DEALLOG3
WHERE (((DEALLOG3.CLOSED)
Between [Forms]![QueryHelp]![closeyear1]
And [Forms]![QueryHelp]![closeyear2])
AND ((DEALLOG3.Submarket)=IIf(IsNull([Forms]![QueryHelp]![Submarket]), " * " ,[Forms]![QueryHelp]![Submarket]))
AND ((DEALLOG3.[Building Type])=IIf(IsNull([Forms]![QueryHelp]![BuildingType]),"*",[Forms]![QueryHelp]![BuildingType])))
;

Try again after changing your WHERE clause in
WHERE DEALLOG3.CLOSED Between [Forms]![QueryHelp]![closeyear1]
AND [Forms]![QueryHelp]![closeyear2]
AND (
DEALLOG3.Submarket)=[Forms]![QueryHelp]![Submarket])
OR [Forms]![QueryHelp]![Submarket] Is Null
)
AND (
DEALLOG3.[Building Type])=[Forms]![QueryHelp]![BuildingType]
OR [Forms]![QueryHelp]![BuildingType] Is Null
)

Related

Calculated Field in subreport

TL:DR I want a whole column of SQL equivalent of excel's COUNTIFS() Function.
I'm still quite new to MS Access, but I'm quite proficient with Excel. I've inherited an Access Database that tracks reasons for delays in a large logistics group, and am trying to build a report showing which reasons come up most.
So, I can output an SQL report showing all the reasons (they're in a table called 'Reasons', so that bit's easy). What I want is a calculated field next to that column, showing how many times each reason has been cited on the [Master Data] Table (field called 'Lateness Reason') in a given date range. And for double extra bonus points, the percentage they come up would be extremely handy.
I've looked online and found COUNTIFS equivalents for a single set of criteria, but in this case I want it calculating on each row of a report. I've also tried a few things myself, but the closest I could figure was:
SELECT Reasons.Reason, Count([Master Data].[ID]) AS Num
FROM Reasons INNER JOIN [Master Data] ON Reasons.[ID] = [Master Data].[Lateness Reason]
WHERE ((([Master Data].[Lateness Reason])=[Reasons].[Reason]));
which has incorrect syntax and possibly a few other problems (that WHERE clause has to apply equally to all lines, doesn't it?). My only other option might be to do a separate calculation for each line and 'union' them together, but that is likely to cause other problems in the future if more reasons get added (and there are quite a lot already).
Firstly, Is it Possible?
Secondly, If so, How??
Many Thanks in advance
EDIT: In response to comments, table structure is as follows;
Table "Reasons" has two columns; "Reason" and "ID"
Table "Master Data" has many columns, the ones I'd be bothered about are "Date", "ID" and "Lateness Reason" (Lateness reason is equivalent to an ID from table 'Reasons')
Table Reasons
ID Reason
___________________
1 | Stock Shortage
2 | Courier Problems
etc | etc
Master Data
ID Date Reason
__________________
1 | 01/01/1980 | 2
2 | 03/05/2020 | 2
etc
This is how I think your query should look like based on the information you provided.
SELECT Reasons.Reason, Count([Master Data].ID) AS Num
FROM Reasons INNER JOIN [Master Data] ON Reasons.ID = [Master Data].[Lateness Reason]
WHERE ((([Master Data].Date) Between [BeginDate] And [EndDate]))
GROUP BY Reasons.Reason;
Replace [BeginDate] and [EndDate] if you're using form control references.
As for the percentages based on the total, you can use text boxes as #June7 has suggested:
Use a total count in the header or footer of the report =Count(*) and then in the detail add a text box with the following control source: =[Num]/Count(*), where Num is the name of the textbox in your report which holds the counted values per reason. In this case, the control source for Num will be Num based on the query given.
Just a side note, naming your field Date is not advised since it's a reserved keyword in MS Access. It can cause unintended issues along the road.

SQL sum, multiple Group By's and Date criteria

I'm looking to perform a sum calculation on a SQL table to find the quantity of a particular stock item held against a particular salesperson up to and including a specific date.
I'm able to perform the sum function to find the quantities on a Salesperson/item basis whenever I do not factor in the date range criteria, but as soon as i add that aspect, it all goes a bit pear shaped! Here is my code so far:
SELECT Salesperson, Item No, Sum(Quantity) AS 'Quantity'
FROM dbo
WHERE (Location Code='VAN')
GROUP BY Salesperson, Item No,
HAVING (Registering Date<={ts '2017-05-03 00:00:00'})
The location code = VAN filter is required to ensure it ignores Warehouse quantities.My SQL knowledge is limited to the few instances I run into it at work and my interaction is largely based through Microsoft Query in Excel. When looking at the above code, i figured that the 'Registering date' criteria should be in the 'WHERE' section, however when i add the criteria using the options available in Microsoft Query, it creates the 'HAVING' line.
If anyone could provide any pointers, it would be much appreciated!
Cheers
Peter
I would imagine a query like this:
SELECT Salesperson, [Item No], Sum(Quantity) AS Quantity
--------------------^ escape the non-standard column name
FROM dbo.??
---------^ table name goes here
WHERE Location Code = 'VAN' AND
[Registering Date] <= '2017-05-03'
------^ put the filtering condition in the correct clause
GROUP BY Salesperson, Item No
-----------------------------^ remove the comma
Your code, as written, has multiple errors. I am guessing that most are transcription errors rather than in the original query (queries don't run if no table is given in the FROM for instance). The "major" error would then be filtering in the HAVING clause rather than the WHERE clause.

Access VBA using SQL for importing multiple tables and then ensuring that they are union

Okay I am getting stuck with my code.
What I am trying to do is use specific data from multiple tables, but I want to use basically the UNION ALL and INNER JOIN functions, however, this is not supported with the Visual Basic of Access and I require it to go to a table so that I can proceed to my next step.
The whole interface work from a form that has buttons to press for normal users, basically setting up a whole interface for importing the reports.
My original import followed the advise that I received from here for the tables:
strSQL = "INSERT INTO [Clicks Returns] " & _
"(SKU, [Item Description], [Jan 2016 FIN YTD TY % Returns]) " & _
"SELECT Sku, [Item Description], [Jan 2016 FIN YTD TY % Returns] FROM [Jan 2016 Clicks Returns];"
DoCmd.RunSQL strSQL
This works perfectly for appending the data to one table, however when importing the data from multiple tables into one table it follows this pattern:
Result Example
However, I require this to be the result:
Required Result
The issue is that Both SKU numbers would be similar and the Item Desc. would be the same.
And with the normal append method it just keep duplicating and I want it to follow a join type action, and I do not know how to approach this exactly with Visual Basics on Access.
Thank you for taking the time to review this and also providing assistance.
with getting the information from the second table, you require the table to be updated. (so insert into won't work for the second time you need to get data...)
I would however reconsider your data structure, to have 1 data column in the table, and have 1 column indicating which month. Then when reporting you can pivot that information...
so basically this table format:
1) SKU
2) Item Description
3) Month
4) Month YTD information.
In the case above, your insert into will much more easily work, and you won't need an update statement.
I hope this helps.
Kind regards,

Trying to include ID column in Grouped SQL SELECT statement in order to drill down in web page

I know there has been a lot of discussion around this subject but I cannot find anything that points me in the direction of a definitive answer.
I have the below sql statement within a .net page in Webmatrix:
SELECT vehicle, vehicleDescription, count(vehicleDescription) AS 'Total'
FROM vehicles
WHERE (branchRequirement = 'Manchester')
AND (deliveryBranch = 'Manchester' OR deliveryBranch IS NULL)
AND (dateDeliveredToBranch > GETDATE() OR dateDeliveredToBranch IS NULL)
AND (vgc LIKE 'B_') GROUP BY vehicle,vehicleDescription
The output is obviously GROUPED data for the chosen conditions.
What I am trying to do is provide a link in my Webgrid on the .net page which allows the user to open a child page with details of the GROUPED vehicles.
Where I'm getting stuck is I cannot include the vehicleID in the GROUP BY because they are obviously all UNIQUE.
Has anybody come across this or something similar with any degree of success as I am pulling my hair out with it which I can ill afford to do!
Thanks
M
I have come across similar issues and the solution I came up with was to use the information you already have. When the user clicks on the link, you know the vehicle and the vehicleDescription that the user wants to see. You should not need the vehicleId because you are not going to have one unique result. If they click on a vehicle that has a count of 3, the child page should have details about all 3 results.
In order to find the 3 results the user would want to see, you can alter your existing query and use it for the child page. The altered query should take the vehicle and vehicleDesciption as parameters.
SELECT *
FROM vehicles
WHERE (branchRequirement = 'Manchester')
AND (deliveryBranch = 'Manchester' OR deliveryBranch IS NULL)
AND (dateDeliveredToBranch > GETDATE() OR dateDeliveredToBranch IS NULL)
AND (vgc LIKE 'B_')
AND vehicle = #vehicle
AND vehicleDesciption = #vehicleDescription
Pass the parameters in .Net and you should end up with the same data that you summed in your last query, since this query is essentially the same.

Grouping results within SQL

I was thinking about doing this in crystal, but am thinking about doing it another way now. This is the way I was thinking about doing it before. Count by group in crystal reports
I am pulling by transactions and need a count of unique people, but in the report they want to show the count of individual people and then show their services below as shown in the image. What I'd like to do is somehow get a count of unique users that I could just throw in at the bottom. Crystal won't allow me to do a count by group and users will have duplicates in the format they want it displayed. I am hopping that I can group it in the code then just add it to the bottom of the report. I hope I'm getting across what I'm trying to accomplish. If I can somehow just add the total of unique users at the bottom of the report it will finish it for me. Thanks in advance.
select
distinct p.patient_id,
pa.fname as 'Patient',
p.clinic_id,
p.service_id,
p.program_id,
p.protocol_id,
p.discharge_reason,
p.date_discharged
from patient_assignment p
join patient pa
on p.patient_id = pa.patient_id
where p.program_id not in ('TEST', 'SA', 'INTAKE' ) and (p.date_discharged between '2013-01-01 00:00:00.000' and '2013-06-01 00:00:00.000')
and p.patient_id not in ('00000004', '00001667', '00020354')
This is too long for a comment.
SQL Queries have fixed columns. You can't "just throw" a different type of row at the bottom. Although there are SQL solutions (such as concatenating all the fields to make a single row), these are not very palatable.
Instead, here are some other ways.
You can run another query to get the count.
You can query the "result" set to get the count (perhaps after fetching all the rows).
You can do some minor coding work in the application.