SQL query ordering wrong, not sure why - sql

SELECT a.[Evaluation Number], a.[CSO Name], a.service
, a.[Date of call], a.[Name of Monitor]
, a.[Date Sheet Completed]
FROM [KD call monitoring] AS a
WHERE a.[Evaluation Number]
IN (SELECT TOP 1 [Evaluation Number]
FROM [KD call monitoring] b
WHERE b.[CSO Name] = a.[CSO Name]
AND b.[Date of Call] =
(SELECT MAX([date of call])
FROM [KD call monitoring]
WHERE [cso name] = a.[CSO Name])
ORDER BY [Evaluation Number]);
this is the code i have on my call evaluation database at work, it is ordering the entries so i know which employee has not had their calls monitored for a while. however it orders fine from 31st jan up until the end of febuary (about halfway down the list) then just places random peoples entries before settling down and giving me the most recent person and entry that has been evaluated.
this list only needs to show one entry per person - the latest one.
im not sure if its messing up because of the leap year or something but i have no idea how to fix it!
im using ACCESS XP. and i would attach an image however im a new user so not allowed!

You don't seem to have an ORDER BY on your outer-most query so the final resultset will not be ordered.

Related

SQL unknown 10 desc script

I am struggling with the below SQL script relating to the bolded "10 desc" at the end of the script
This field is not in the original tables. It was created separately.
I don't exactly know what it is for but if I remove it it will give me different result. Hope I could have some guidance on this.
SELECT ce.[Agreement ID], m.AGREEMENT_NAME, ce.Max_Deduct_Bond, d.[Product Type], d.Margin, d.Ccy, Left(Right(d.[Margin],12),2) AS Cty, d.Posted_Received_Flag, d.[Market Value], (d.[Market Value]*r.[Rate]) AS [Market Value HKD]
FROM [Step 0103 - CE: CE Source] AS ce,
[201_0002 - Get_Agreement_Treats_Mapping] AS m,
[201_0000 - Get_nCOMS_201_Details] AS d,
SysReportDate AS sd,
SysTOR AS r
WHERE (((ce.[Agreement ID])=[m].[AGREEMENT_ID] And (ce.[Agreement ID])="11") AND ((m.AGREEMENT_NAME)=[d].[Agreement]) AND ((ce.Max_Deduct_Bond)<>0) AND ((d.[Product Type])='Bond') AND ((d.[Reporting Date])=[sd].[Reporting Date]) AND ((sd.Date_Code)='01_CM') AND ((r.[Ccy Code])=[d].[Ccy]))
ORDER BY ce.[Agreement ID], 10 DESC;
10 in order by mean its ordering by 10th column listed in the select statement, which in your query is [Market Value HKD].
which is not recommended to do so , and your order by statement changes depend on the order of columns returned in the select .
always use column names:
... ORDER BY ce.[Agreement ID], [Market Value HKD] DESC;

Need MS Access Form Field to automatically Calculate and Allocate Costs based on given Parameters

Below is my mock database that I am using. I have four different tables: Tbl_MainDatabase, Tbl_InsuranceCoverage, Tbl_MatterDetail, and Tbl_PaymentProcessing.
What I want -
I want my form to determine the remaining Retention Limit (i.e., Retention Limit for the applicable policy - sum of invoices for the same Claim Number )
According to the mock database, the required answer should be [ $2500 - (300+700+355)] as highlighted for your convenience
What I tried
I used the help of Graphical representation through the following query:
SELECT [Claim Number], Sum([Net Invoice Amount])
FROM [PaymentProcessing]
GROUP BY [Claim Number]
This method works to show me how much I spent per claim number so far in the form of a graph. However I want to display the remaining amount.
Any Help is appreciated :)
I am one month old at using Access. But I am trying my best to learn
Thank you in advance!
SELECT
IC.[Retention Limit]-SUM([Net Invoice Amt]) AS Remaining, MD.[Claim Number], IC.[Retention Limit], IC.InsuranceID
FROM tbl_InsuranceCoverage IC
INNER JOIN tbl_MatterDetail MD ON ic.InsuranceID = MD.Policy
INNER JOIN tbl_PaymentProcessing PP ON MD.MatterDetailID=pp.MatterDetailID AND MD.[Claim Number]=pp.[Claim Number]
GROUP BY MD.[Claim Number], IC.[Retention Limit], IC.InsuranceID
See if this works. Havent tested it but seems simple. You can remove the extra columns, but this will hlep you understand joins a bit
For All the New users The above code by #Doug Coats works perfectly.
Make Sure All the Foreign Key and Primary Keys is linked in the Relationship Property. ( One of the way To do this in the Query is - Right click on the Query and select Design View --> Right click again on the grey space and Select Show all Tables Now Drag your Primary Key of the table and drop at the foreign Key on the other table --> This will create a relationship between both for the Query Purpose.
This will also Prevent Data from Duplication in the query then use a similar code as described by Doug Coats in the above comment in the SQL View
SELECT [Insurance Coverage].[Retention Unit]-Sum([Net Invoice Amount]) AS Remaining, [Matter Detail].[Claim Number], [Insurance Coverage].[Retention Unit], [Matter Detail].Policy
FROM (([Main Database] INNER JOIN [Matter Detail] ON [Main Database].[Database ID] = [Matter Detail].[Short Name]) INNER JOIN [Payment Processing] ON ([Matter Detail].[Matter Detail ID] = [Payment Processing].[Matter Detail ID]) AND ([Main Database].[Database ID] = [Payment Processing].[Short Name])) INNER JOIN [Insurance Coverage] ON [Matter Detail].Policy = [Insurance Coverage].[Insurance ID]
GROUP BY [Matter Detail].[Claim Number], [Insurance Coverage].[Retention Unit], [Matter Detail].Policy;
You can then display this query in the form - I am still evaluating best way to display this query probably in a Combo Box (Not sure if any other controls has a row source)
Thank you

MS Access 2010 throwing "Query Too Complex" error with larger record set

I've having repeated but sporadic issues with Access 2010 throwing up "Query Too Complex" errors on queries that actually aren't hugely complex, but involve a decent number of records (say more than 5000). This always involves working with a linked SharePoint list.
Here's an example (the table I'm inserting into is on the SharePoint server, the other tables are local in the Access file on my drive):
INSERT INTO [NR Info]
(Title,
[NR ID],
[Project],
[Sub-project],
[PD Number],
[WBS Number],
[Network],
[IA PO Activity],
[FA PO Activity],
[ASP],
[status],
[MS10],
[PO Status],
[2G/3G HW CPO],
[4G HW CPO],
[4G SW CPO],
[Additional HW CPO],
[Antenna HW CPO],
[2G/3G/4G HWAC CPO],
[Swap Prep CPO],
[VOD I&C CPO],
[Antenna Refresh CPO],
[Additional Services CPO],
[Decom CPO],
[Variances Build Services CPO],
[Unknown Variances CPO],
[Other CPO A],
[Other CPO B],
[Other CPO C],
[Other CPO D],
[Other CPO E] )
SELECT sh.[NR_Unique_ID],
sh.[NR_ID],
sh.[Project_lookup],
sh.[SubProject_lookup],
cn.[project_definition],
cn.[wbs_element],
cn.[network],
cpo.[IAPO_activity],
cpo.[FAPO_activity],
sh.[ASP_lookup],
sh.[Status],
cpo.[MS10],
cpo.[cpo_state],
cpo.[2G3G_HW_State],
cpo.[4G_HW_State],
cpo.[4G_SW_State],
cpo.[Addl_HW_State],
cpo.[Antenna_HW_State],
cpo.[2G3G4G_HWACS_State],
cpo.[Swap_Prep_State],
cpo.[VOD_IC_State],
cpo.[Antenna_Refresh_State],
cpo.[Addl_Serv_State],
cpo.[Decom_State],
cpo.[Var_Build_State],
cpo.[Unknown_Var_State],
cpo.[Other_POA_State],
cpo.[Other_POB_State],
cpo.[Other_POC_State],
cpo.[Other_POD_State],
cpo.[Other_POE_State]
FROM (Staging_SH_keyData AS sh
LEFT JOIN Staging_SAP_CN AS cn ON sh.[NR_ID] = cn.[nr_id])
LEFT JOIN staging_SH_cpoStatus AS cpo ON sh.[NR_Unique_ID] = cpo.[NR_Unique_ID]
WHERE sh.[NR_Unique_ID] NOT IN (SELECT [title] FROM [NR Info]);
This would be another one which also causes issues when working on big record sets. I tried to use it to insert about 13,000 rows from my local file to the Sharepoint server. I ended up having to use a TOP 1000 temporarily on the SELECT and run the query 13+ times. Even then, I'd periodically get the error, though closing the file and re-opening it would fix it for a few more runs. I'd also sometimes get "System Resource" related issues.
INSERT INTO [Order Items]
([Title],
[Order Item],
[NR ID],
[Vfe Material ID],
[E/// Material Num],
[Material Description],
[Item Category],
[Quantity Ordered],
[Date Requested],
[Requester],
[Item Request Status],
[PO2 Number],
[PO2 Line Number],
[PO Technical Check],
[PO Accepted Date],
[SO Number],
[SO Line Number],
[SO Line Status],
[SO Item Quantity],
[SO Release Date],
[SO Activated Date],
[Event Day],
[MS10])
SELECT [Order_Item],
[Order_Item],
(SELECT TOP 1 [id] FROM [NR Info] nri WHERE nri.[NR ID]=soi.[NR_ID]),
[VF_SAP_Material],
[Mat_Num],
[Mat_Desc],
[Mat_Cat],
[Order_Quan],
[Request_Date],
[Requester],
[Item_ReqStatus],
[PO2_Num],
[PO2_LineNum],
[PO_TechCheck],
[PO_AcceptedDate],
[SO_Num],
[SO_LineNum],
[SO_LineStatus],
[SO_Quantity],
[SO_RelDate],
[SO_ActivatedDate],
[EventDay],
[MS10]
FROM Staging_OrderItems AS soi
WHERE soi.[Order_Item] NOT IN (SELECT [Title] FROM [Order Items]);
Any help greatly appreciated!
As per this article:
JET gives this generic message any time it cannot pinpoint what's wrong. The cause can be wrong delimiters, misinterpreted data types, mismatched brackets, using reserved words as table or field names or aliases, confusion from Name AutoCorrect, or a host of other possibilities.
Solutions
In most cases, the solution it to figure out which part Access does not understand. Check the data types match in expressions, joins, and criteria. Explicitly typecast where needed. Explicitly declare parameters, so JET knows their type.
Verify your names (tables, fields, aliases) are not on the reserved words list. Add square brackets around any suspect names, and explicitly specify their source table, e.g. "SELECT [Table1].[Name] FROM ... " rather than "SELECT Name FROM ... "
Make sure Name AutoCorrect is off. Then compact/repair the database.
If necessary, break the query down to find the problem. Drop half of the WHERE clause, omit the GROUP BY clause until the query works. Then start adding thing back until you pinpoint the culprit.
Occasionally, the query actually is too complex: too many UNIONs, more than 32 tables, 100 ANDs in the WHERE clause, or nesting queries more than 50 levels deep. For a list of the limits, open Help in the main Access window, and enter specifications. In Access 2007, go to help topic HA10030739.

SQL Server 2012 Max Date in Subquery in a joined table

I manage a state wide application and use Tableau to create visualizations of data.
I have been tasked with creating a visualization that show how much time is passing between contact entries and today (Case Note Dates). I know how to isolate the max case note date in the case note table:
Select
[Case_Master_ID],
[Case_Note_Date],
[Case_Note_Category_Desc],
[Case_Note_Summary_Narr]
From
buCase_Note
Where
Case_Note_Date = (Select MAX(Case_Note_Date)
From buCase_Note)
This query will show me that max case notes in the table from today. The issue is I need to show the max case note for all participants, not just the ones from today. The original query I have been using to view case notes is:
Select
vc.[_Case Master ID],
vc.[_Caseload Assignment Current],
vc.[_Participant Name],
vc.[Case Status],
vc.[Reporting Structure Level 4],
vc.[Reporting Structure Level 5],
vc.[Application Date],
vc.[Eligibility Date],
vc.[Eligibility Determination Extension Date],
vc.[Eligibility Extended To Date],
vc.[Days in Application],
cn.[Case_Note_Date],
cn.[Case_Note_Category_Desc],
cn.[Case_Note_Summary_Narr]
From
biVR_Cases vc
Left outer Join
buCase_Note cn ON cn.Case_Master_ID = vc.[_Case Master ID]
I need to keep biVR_Cases on the left to show all the open clients. Then I need to join in the case note table and for every participant, I want to show their max case note date. When I add this to the end of the above query:
Where cn.[Case_Note_Date] = (
Select
MAX(cn.Case_Note_Date)
From buCase_Note)
I get the following error is SSMS 2012:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
I am looking to retain the bi table on the left while successfully joining in the case note table and bringing in only the most recent case note per participant.
Adding details:
Of course,
Here is a sample of data I get when running the following query:
Select
vc.[_Case Master ID],
vc.[_Caseload Assignment Current],
vc.[_Participant Name],
cn.[Case_Note_Date],
From biVR_Cases vc
LEFT outer JOIN buCase_Note cn ON vc.[_Case Master ID] = cn.Case_Master_ID
_Caseload Assignment Current Test Participant Name Casenote Date
Test Counselor Participant A
September 29, 2010
September 23, 2010
August 30, 2010
June 30, 2010
June 1, 2010
The bi table contains participant information like name, application, case master ID, etc. The casenote table contains the case master ID as well hence the join. It also contains the dates each entry is created. So for the dataset above, I am trying to only bring in the most recent casenote for each participant. I only included 1 in the sample above, but we have over 15,000. Each participant will have many case notes. I am trying to grab the top casenote so I can calculate the date difference between the most recent case note and today for each participant. When I add :
Where cn.[Case_Note_Date] = (Select
top 1 [Case_Note_Date]
From buCase_Note
Order by 1 DESC))
OR
Where Case_Note_Date=(
Select
MAX(Case_Note_Date)
From buCase_Note)
It is only showing the top or max casenote for participants that had a casenote created today. Instead of showing the max casenote in the casenote table, I need the max casenote per participant. I hope that makes more sense.
You might try something like what I have included below. Without actual data, I do not know if it is efficient enough for you, but it should work. If you get a better answer, however, I would love to know it.
Select vc.[_Case Master ID],
vc.[_Caseload Assignment Current],
vc.[_Participant Name],
vc.[Case Status],
vc.[Reporting Structure Level 4],
vc.[Reporting Structure Level 5],
vc.[Application Date],
vc.[Eligibility Date],
vc.[Eligibility Determination Extension Date],
vc.[Eligibility Extended To Date],
vc.[Days in Application],
cn.[Case_Note_Date],
cn.[Case_Note_Category_Desc],
cn.[Case_Note_Summary_Narr]
From biVR_Cases vc
LEFT outer JOIN
(SELECT Case_Master_ID, Case_Note_Date, Case_Note_Category_Desc, Case_Note_Summar_Narr,
ROW_NUMBER() OVER (PARTITION BY Case_Master_ID ORDER BY Case_Note_Date DESC) as RowNum FROM buCase_Note) cn
ON cn.Case_Master_ID = vc.[_Case Master ID] AND cn.RowNum=1
Remove the cn. from the MAX(cn.Case_Note_Date) row. You don't want to reference column from the main query. You just want to select a Case_Note_Date from buCase_Note.
So the whole query will be
Select
vc.[_Case Master ID],
vc.[_Caseload Assignment Current],
vc.[_Participant Name],
vc.[Case Status],
vc.[Reporting Structure Level 4],
vc.[Reporting Structure Level 5],
vc.[Application Date],
vc.[Eligibility Date],
vc.[Eligibility Determination Extension Date],
vc.[Eligibility Extended To Date],
vc.[Days in Application],
cn.[Case_Note_Date],
cn.[Case_Note_Category_Desc],
cn.[Case_Note_Summary_Narr]
From biVR_Cases vc
LEFT outer JOIN buCase_Note cn ON cn.Case_Master_ID = vc.[_Case Master ID]
Where cn.[Case_Note_Date] = (Select
MAX(Case_Note_Date)
From buCase_Note)

access xp list showing last time an employees call was evaluated

I work in the management staff of a call centre and I've created a "Call Evaluation Database" using access XP where an employees call can be rated on things such as customer service, knowledge, call control etc.
Part of this has now developed and I would like to add a form with a list showing all employees and next to their name only the LAST time a call was evaluated and the service it was for. this would be sorted in ascending order so we can see when a call was last evaluated and the people at the top would need theirs evaluating next.
I only want this to show their last call for each and every employee, not ALL of them. and I'm struggling to do this in a query.
I hope this makes sense, if not ill try answer any questions the best I can. its probably really simple but I don't class myself as an Access expert!
You can use GROUP BY. For example:
SELECT Employee.ID, Max(LastEval)
FROM Employees
INNER JOIN Evaluations
ON Employee.ID = Evalutations.EmployeeID
GROUP BY Employee.ID
You can build such queries easily enough using the query design window and the sigma button Σ
EDIT re comment
SELECT a.[Evaluation Number],
a.[CSO Name],
a.service,
a.[Date of call],
a.[Name of Monitor],
a.[Date Sheet Completed]
FROM [KD call monitoring] a
WHERE a.[Evaluation Number]
IN (SELECT TOP 1 [Evaluation Number]
FROM [KD call monitoring] b
WHERE b.[CSO Name] = a.[CSO Name]
AND b.[Date of Call] =
(SELECT MAX([date of call])
FROM [KD call monitoring]
WHERE
[cso name] = a.[CSO Name])
ORDER BY [evaluation number])