Update Query with Static Value and Dynamic Value - ms-access

I am trying to update two columns on a table, in MS Access using Microsoft 365. One value is static and one is based on a select query. However I continue to get Operation must use an updateable query error message. Below is my query:
UPDATE tblBuckets AS e
SET e.DiscountExclusion = "SpecialDisc", e.DrugSpecDisc = (
SELECT sd.[Discount Rate]
FROM tblDrugSpecDis AS sd
INNER JOIN tblClaims AS s ON sd.[Drug ID] = LEFT(s.ndc11code, sd.[Length of Drug ID])
WHERE sd.Indicator = 'N'
)
WHERE e.sourceclaimid IN (
SELECT s.sourceclaimid
FROM tblClaims AS s
INNER JOIN tblDrugSpecDis AS sd ON sd.[Drug ID] = LEFT(s.ndc11code, sd.[Length of Drug ID])
WHERE sd.Indicator = 'N'
)

Related

sub-select query in SQL will not populated new column/field with specific text

How do I get my new field to populate with Yes or No rather than pre-existing data? In this case, I'm getting a new field called ESL but I can only get it to run if i populated the field with colleagueId. I want it to populate with Yes and not true with No. I've also tried case statements.
select distinct s.colleagueId, st.enrollmentStatus,
s.firstEnrolledTerm, ESL.colleagueId as ESL
from tbl_studentTerms st
left join
(select distinct colleagueId
from tbl_studentclasses
where enrolled = 1
and subject = 'ESL') as ESL
on ESL.colleagueId=st.colleagueId
inner join tbl_students s
on st.colleagueId = s.colleagueId
where s.endingCohort = '2009SP'
and st.term='2009SP'
and s.colleagueId in(select [Student ID] from dbo.pvt_SelectedStudents)
Here is one method:
select distinct s.colleagueId, st.enrollmentStatus,
s.firstEnrolledTerm,
coalesce(ESL.ESL, 'No') as ESL
from tbl_studentTerms st inner join
tbl_students s
on st.colleagueId = s.colleagueId left join
(select distinct colleagueId, 'Yes' as ESL
from tbl_studentclasses
where enrolled = 1 and subject = 'ESL'
) ESL
on ESL.colleagueId = st.colleagueId
where s.endingCohort = '2009SP' and st.term = '2009SP' and
s.colleagueId in (select [Student ID] from dbo.pvt_SelectedStudents);
Notes:
I move the inner join to be before the left join. I find it easiest to read query where inner joins come first, followed by left joins.
Do not use select distinct unless you really need to remove duplicates.

(another) LEFT JOIN issue with ACCESS

I want summary data from my 'Data' table for all companies in 'Companies' table including blank rows where there is no record in Data.
If I summarise the data in a nested SELECT clause (or in a stored query i get nothing from the data table. For example
This is the sub select
SELECT transco,
sum(m1) AS Jan15,
FROM data
WHERE (QVmeasure = 'Vol')
GROUP BY QVmeasure, transco
which outputs:
transco Jan15
0292 154373665
1419 134915098
If I use it in a sub select as follows
SELECT c.SAP_Code,
Jan15
FROM Companies AS c
LEFT JOIN (
SELECT transco,
sum(m1) as Jan15
FROM data
WHERE (QVmeasure = 'Vol')
GROUP BY QVmeasure, transco)
AS d
ON c.SAP_Code = d.transco
I get:
SAP_Code Jan15
0292
1419
I can get the correct result via a temporary table:
SELECT sum(m1) as Jan15,
transco
INTO Temp_Table
FROM data
WHERE (QVmeasure = 'Vol')
GROUP BY QVmeasure, transco
followed by
Select c.SAP_code,
jan15
FROM companies AS c
LEFT JOIN Temp_Table as i
ON (c.SAP_Code = i.transco)
giving:
SAP_code jan15
0292 154373665
1419 134915098
1423
but if I use temporary tables I will have to create macros and i want users to be able to run just a query.
The following works for this simple case but I can't apply it in other circumstances:
SELECT c.SAP_Code,
sum(m1) AS Jan15
FROM Companies AS c
LEFT JOIN data as d
ON c.SAP_Code = d.transco
WHERE (d.QVmeasure = 'Vol') OR (d.QVmeasure is null)
GROUP BY d.QVmeasure,c.sap_code
Is there something wrong with my sub select syntax or is it ACCESS (2013)
TIA
You could nest the sub-query like this:
SELECT c.SAP_Code,
(SELECT sum(d.m1)
FROM data AS d
WHERE d.QVmeasure = 'Vol' AND c.SAP_Code = d.transco
) AS [Jan15]
FROM Companies AS c

How to filter on Access Report subtotal

Have an access report that shows training programs, and which employees should be but are not trained on that program. This query is fine. Problem is that we want to only display on the report training programs which have more than 10 employees untrained. So we have the total of untrained for each program in a subtotal, but we want to filter on that value.
How can this be done?
EDIT:
Here is pass-through query to SQL Server
SELECT T.ProgramTitle
,T.ProgramCode
,AE.Code AS 'AvantiCode'
,AE.FullName
,AE.FirstName
,AE.LastName
,AE.Department
,C.Position
,AE.Shift
FROM HR_Curriculum C
INNER JOIN HR_Trainings T ON C.TrainingID = T.TrainingID
INNER JOIN HR_EmployeeDetails ED ON C.Position = ED.Postion
INNER JOIN Avanti_Employees AE ON ED.AvantiRecID = AE.RecID
LEFT JOIN HR_Employeetrainings ET ON C.TrainingID = ET.TrainingID
AND ED.AvantiRecID = ET.AvantiRecID
LEFT JOIN HR_TrainingVersion V ON V.VersionID = ET.VersionID
WHERE terminated = 0
AND T.Active = - 1
AND CompletedDate IS NULL
GROUP BY T.ProgramTitle
,T.ProgramCode
,AE.Code
,AE.FullName
,AE.FirstName
,AE.LastName
,AE.Department
,C.Position
,AE.Shift
Order by programtitle
Consider an inline view, using a grouped by table alias with HAVING clause.
Try adding one more inner join:
INNER JOIN
(SELECT TrainingID, ProgramTitle, ProgramCode
FROM HR_Trainings
GROUP BY TrainingID, ProgramTitle, ProgramCode
HAVING Count(TrainingID) > 10) AS Trainings10More
ON Trainings10More.TrainingID = T.TrainingID

MySQL update with IN clause and subquery

I want to run some updates on my MySQL database. Here is the query that I want to use:
UPDATE `wphh_wp_eStore_tbl`
SET `wphh_wp_eStore_tbl`.description = '<div class="dwrp">
<h2>F. Locker $109.99</h2>
<h2>Nike Outlet $109.99</h2>
<h2>Ch. Sports $107.99</h2>
<h2>Hoopers Hookup $89.99</h2>
<h2 class="special">These prices as of 11/20/13</h2>'
WHERE `wphh_wp_eStore_tbl`.id in (
SELECT `wphh_wp_eStore_tbl`.id FROM `wphh_wp_eStore_tbl`
INNER JOIN `wphh_wp_eStore_cat_prod_rel_tbl`
on `wphh_wp_eStore_cat_prod_rel_tbl`.prod_id = `wphh_wp_eStore_tbl`.id
WHERE `wphh_wp_eStore_cat_prod_rel_tbl`.cat_id = 5
)
This generates the following error:
#1093 - You can't specify target table 'wphh_wp_eStore_tbl' for update in FROM clause
Why? I know in MSSQL I can do this:
Update tableone
set columnname = 'xxx'
where id in (
select id
from tableone
where category = 10)
and it works.
What am I missing?
The simple solution is to enclose the in list in an additional level of nesting. MySQL will then materialize the data:
UPDATE `wphh_wp_eStore_tbl`
SET `wphh_wp_eStore_tbl`.description = '<div class="dwrp">
<h2>F. Locker $109.99</h2>
<h2>Nike Outlet $109.99</h2>
<h2>Ch. Sports $107.99</h2>
<h2>Hoopers Hookup $89.99</h2>
<h2 class="special">These prices as of 11/20/13</h2>'
WHERE `wphh_wp_eStore_tbl`.id in (
select * from (SELECT `wphh_wp_eStore_tbl`.id FROM `wphh_wp_eStore_tbl`
INNER JOIN `wphh_wp_eStore_cat_prod_rel_tbl` on `wphh_wp_eStore_cat_prod_rel_tbl`.prod_id = `wphh_wp_eStore_tbl`.id
WHERE
`wphh_wp_eStore_cat_prod_rel_tbl`.cat_id = 5) t
)
Another way is to use join to with update.
I'm not a MySQL guy but could you do this instead? I also like using table alias with these ugly names.
UPDATE `wphh_wp_eStore_tbl` e
inner join `wphh_wp_eStore_cat_prod_rel_tbl` ecpr
on ecpr.prod_id = e.id
and ecpr.cat_id = 5
set e.description = 'Some Text To Update With'
In SQL Server the "from" and the join come after the SET but.. not the case in mySQL apparently.

Mixed scenarios in MS Access

This is my table [Property]:
Loanno Balance amount PropertyType
1001045 308731.770000 1
1001045 2007700.740000 2
1001045 3087318905.770 3
1001045 308731.770000 4
1001046 306589.67 1
1001046 456321.23 1
1001046 6932542.89 1
1001047 582563.56 1
1001047 965421.34 2
1001048 567894.34 1
1001048 567894.34 2
I have to get the property type for a [Loanno] having highest balance amount.
If there is a tie in the highest balance amount and if the Property type for the loannumber is different then for that Loan number I have to populate property type as '8'.
So my final Output should look like this:
Loanno PropertyType
1001045 3
1001046 1
1001047 2
1001048 8
Edit
This is what I tried, but I am getting duplicate records.
SELECT DISTINCT
LT.LOANNO,
IIF(COUNTS.MAX_BALANCE > 1, 8,LT.PROPERTY_TYPE) AS PROPERTY_TYPE1
FROM
PROPERTY LT
INNER JOIN
(
SELECT
DISTINCT_ROWS.LOANNO,
COUNT(DISTINCT_ROWS.MaxBalance) AS MAX_BALANCE
FROM
(
SELECT DISTINCT
L.LOANNO,
MaxBalance
FROM
PROPERTY AS L
INNER JOIN
(
SELECT
LOANNO,
MAX(BALANCE_AMOUNT) AS MaxBalance
FROM PROPERTY
GROUP BY LOANNO
) AS SUB
ON (L.LOANNO=SUB.LOANNO)
AND (L.BALANCE_AMOUNT=SUB.MaxBalance)
) AS DISTINCT_ROWS
GROUP BY DISTINCT_ROWS.LOANNO
) AS COUNTS
ON LT.LOANNO=COUNTS.LOANNO
GROUP BY LT.LOANNO, IIF(COUNTS.MAX_BALANCE > 1, 8, LT.PROPERTY_TYPE)
Your query requirements are challenging for Access SQL. A custom VBA function would allow you to use a simpler SELECT statement, but brings issues which may be unacceptable for you:
A UDF (user-defined function) can only be used in a query run within an Access session ... not when you use other code (.Net, Java, PHP, VBScript, etc) to connect to the db and run your query.
UDFs can be slow.
If you can use a UDF, this query using the GetPropertyType function (see below) returns what you asked for. Note I used tblProperties as the table name because Property is a reserved word. Also I assumed Long for the data type of Loanno, Currency for Balance_amount, and Long for Property_Type.
SELECT
sub.Loanno,
GetPropertyType(sub.Loanno,sub.MaxBalance) AS PropertyType
FROM
(
SELECT
Loanno,
Max(Balance_amount) AS MaxBalance
FROM tblProperties
GROUP BY Loanno
) AS sub
ORDER BY sub.Loanno;
This is the function, which I tested with Access 2007.
Public Function GetPropertyType(ByVal pLoanno As Long, _
ByVal pBalance_amount As Currency) As Long
Const cstrQdf As String = "qryLoanPropertyTypesCount"
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Dim lngReturn As Long
Set db = CurrentDb
Set qdf = db.QueryDefs(cstrQdf)
qdf.Parameters("which_Loanno") = pLoanno
qdf.Parameters("which_Balance_amount") = pBalance_amount
If qdf.OpenRecordset()(0) > 1 Then
lngReturn = 8
Else
lngReturn = DLookup("Property_Type", "tblProperties", _
"Loanno=" & pLoanno & " AND Balance_amount=" & _
pBalance_amount)
End If
Set qdf = Nothing
Set db = Nothing
GetPropertyType = lngReturn
End Function
The function uses this saved parameter query, qryLoanPropertyTypesCount:
PARAMETERS which_Loanno Long, which_Balance_amount Currency;
SELECT Count(*) AS num_PropertyTypes
FROM
(
SELECT DISTINCT
p.Loanno,
p.Balance_amount,
p.Property_Type
FROM tblProperties AS p
WHERE
p.Loanno = [which_Loanno]
AND p.Balance_amount = [which_Balance_amount]
) AS sub;
Here's how I built up the query:
Step 1: Create a query to find the maximum balance for each [Loanno] and save that query as [Loanno_MaxBalance]:
SELECT
Loanno,
MAX([Balance amount]) AS MaxBalance
FROM [Property]
GROUP BY Loanno
Step 2a: Create a query to count the number of rows that have the maximum balance, using our saved query above to keep things simple:
SELECT
[Property].Loanno,
[Property].[Balance amount],
COUNT(*) AS RowCount
FROM
[Property]
INNER JOIN
[Loanno_MaxBalance]
ON Loanno_MaxBalance.Loanno=[Property].Loanno
AND Loanno_MaxBalance.MaxBalance=[Property].[Balance amount]
GROUP BY [Property].Loanno, [Property].[Balance amount]
Step 2b: That doesn't look too scary, so let's incorporate the SQL from Step 1 as a subquery:
SELECT
[Property].Loanno,
[Property].[Balance amount],
COUNT(*) AS RowCount
FROM
[Property]
INNER JOIN
(
SELECT
Loanno,
MAX([Balance amount]) AS MaxBalance
FROM [Property]
GROUP BY Loanno
) AS Loanno_MaxBalance
ON Loanno_MaxBalance.Loanno=[Property].Loanno
AND Loanno_MaxBalance.MaxBalance=[Property].[Balance amount]
GROUP BY [Property].Loanno, [Property].[Balance amount]
So now this query stands on its own, and we don't need to keep [Loanno_MaxBalance] as a separate saved query in Access.
We'll save the above query as [Loanno_MaxBalance_Count].
Step 3a: Now to derive the [PropertyType] values using the [Property] table and the [Loanno_MaxBalance_Count] query:
SELECT DISTINCT
[Property].Loanno,
IIf(Loanno_MaxBalance_Count.RowCount>1, 8, [Property].PropertyType) AS PropertyType
FROM
[Property]
INNER JOIN
[Loanno_MaxBalance_Count]
ON [Property].Loanno=Loanno_MaxBalance_Count.Loanno
AND [Property].[Balance amount]=Loanno_MaxBalance_Count.[Balance amount]
Step 3b: Gee, that's not too bad at all. Let's "go for it" and replace the [Loanno_MaxBalance_Count] query reference with its SQL code (from Step 2b) as a subquery:
SELECT DISTINCT
[Property].Loanno,
IIf(Loanno_MaxBalance_Count.RowCount>1, 8, [Property].PropertyType) AS PropertyType
FROM
[Property]
INNER JOIN
(
SELECT
[Property].Loanno,
[Property].[Balance amount],
COUNT(*) AS RowCount
FROM
[Property]
INNER JOIN
(
SELECT
Loanno,
MAX([Balance amount]) AS MaxBalance
FROM [Property]
GROUP BY Loanno
) AS Loanno_MaxBalance
ON Loanno_MaxBalance.Loanno=[Property].Loanno
AND Loanno_MaxBalance.MaxBalance=[Property].[Balance amount]
GROUP BY [Property].Loanno, [Property].[Balance amount]
) AS Loanno_MaxBalance_Count
ON [Property].Loanno=Loanno_MaxBalance_Count.Loanno
AND [Property].[Balance amount]=Loanno_MaxBalance_Count.[Balance amount]
That's it! One self-contained query with no need for saved Access query dependencies.