sql string to get the maximum of the union of minimum values - sql

I have two tables and I would like to have an sql query to get the minimum value of a field of the union of the maximums of the tables.
Set tmpRS = CurrentDb.OpenRecordset(" SELECT MIN(s.TorqueMax) FROM ( " & _
" (SELECT MAX(ds.TorqueMax) FROM tblUIOpTorqueRangeDS ds)" & _
" UNION " & _
" (SELECT MAX(cv.TorqueMax) FROM tblUIOpTorqueRangeCV cv )) as s")

You can do something like this:
SELECT MIN(s.TorqueMax)
FROM (SELECT MAX(ds.TorqueMax) as TorqueMax
FROM tblUIOpTorqueRangeDS ds
UNION
SELECT MAX(cv.TorqueMax) as TorqueMax
FROM tblUIOpTorqueRangeCV cv
) as s;

Related

SQL (MS Access): For a given record, how to query top 5 values from a given set of fields?

I have a table with a few dozen fields, 18 of which are fields with varying integer values. I'd like to pull the field names and corresponding values for the five fields with the greatest values for a given record. I'll use the below table as example where I'd like to query only the two greatest values for a given record.
Name, FigureA, FigureB, FigureC
John, 40, 73, 81
Luke, 35, 21, 65
I'd like to return the following for, say, John:
FigureB, 73
FigureC, 81
I've gotten this far:
sSQL = "Select t.* " & _
"From (Select 'A' as [FigureA], FigureA " & _
"From Table) as t " & _
"Union All " & _
"Select t.* " & _
"From (Select 'B' as [FigureB], FigureB " & _
"From Table) as t " & _
"Union All " & _
"Select t.* " & _
"From (Select 'C' as [FigureC], FigureC " & _
"From Table) as t"
In MS Access, this is probably simplest with union all:
select top (5) *
from (select t.*
from (select top (1) "field1" as colname, max(field1) as max_val
from t
) as t
union all
select t.*
from (select top (1) "field2" as colname, max(field2)
from t
) as t
union all
. . .
) as t
order by max_val desc;
Some versions of MS Access don't support union all in the from clause. That component might require a view.

SQL insert into with various select multiple rows and fields

I need to insert multiple rows and fields in Access 2016 with SQL VBA. I'm doing this thing below -with union -but it doesn't work, it says my sintax with union is wrong. I need to figure out what's wrong otherwise run queries one by one and I have 9 like this!
(EDIT: solution found!)
query = "INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier) SELECT qryTotals.JRN AS SumOfJRN, qryTotals.[Rate JRN],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & " union "
query = query & "SELECT qryTotals.MG AS SumOfMG, qryTotals.[Rate MG],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & ""
Here is the answer of what worked, very similar from a code someone showed me below but a differences that changed everything (no error messages and it does insert in the table!). I had to put the selects into a select, still gave me an error and for some reason, when I added the -> as Price and as Quantity it worked. I'm still not sure why it works now, let me know if you have an explanation!
query = "INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier ) SELECT * FROM (SELECT qryTotals.JRN as Quantity, qryTotals.[Rate JRN] as Price, qryTotals.MMDCarrier FROM qryTotals where qryTotals.MMDCarrier like '" & Me.Combo0 & "'"
query = query & " UNION SELECT qryTotals.MG , qryTotals.[Rate MG], qryTotals.MMDCarrier From qryTotals where qryTotals.MMDCarrier like '" & Me.Combo0 & "')"
If you're using INSERT INTO ... SELECT with unions, you need to put all unions in a subquery, e.g.:
INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier)
SELECT * FROM (
SELECT qryTotals.JRN AS SumOfJRN, qryTotals.[Rate JRN], qryTotals.MMDCarrier from qryTotals
where qryTotals.MMDCarrier like 'something'
UNION
SELECT qryTotals.MG AS SumOfMG, qryTotals.[Rate MG],
qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like 'somethingElse'
) As A
Or, in your VBA implementation:
query = "INSERT INTO tblInvoice2 ( Quantity, Price, MMDCarrier) SELECT * FROM (SELECT qryTotals.JRN AS SumOfJRN, qryTotals.[Rate JRN],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & " union "
query = query & "SELECT qryTotals.MG AS SumOfMG, qryTotals.[Rate MG],"
query = query & "qryTotals.MMDCarrier from qryTotals where qryTotals.MMDCarrier like " & Me.Combo0 & ") As A"
Note that your query also contains a trailing comma in the INSERT INTO part, which isn't a syntax error in Access SQL, but is one in most other forms of SQL, and still is a bad practice. Also, LONG was probably right, you want those single quotes (but really, you should use parameters instead)

SQL Select DISTINCT GROUP BY Weekday in Access

I am trying to Count the distinct Number of UserID's in a table for each Weekday (e.g. 545 UserID's on Weekday 1 = Monday, 120 UserID's on Weekday 2 = Tuesday etc.). I am doing this in Access Visual Basic, but the syntax should be universal to SQL. Here is my VB Code:
sSQL = " SELECT Weekday(" & tablename & ".[DATE]) AS WEEKDAY, Count(DISTINCT " & tablename & ".[UserID]) AS User_COUNT"
sSQL = sSQL & " FROM " & tablename
sSQL = sSQL & " GROUP BY Weekday(" & tablename & ".[DATE])"
qdf.SQL = sSQL
The plain SQL Syntax should look like this (edited based on comments & test):
SELECT Weekday(tbl.[Date]) AS WEEKDAY, Count(DISTINCT tbl.[UserID]) AS User_COUNT
FROM tbl
GROUP BY Weekday(tbl.[Date])
..whereas [Date] is a field in tbl formatted as Datetime and [UserID] is a field formatted as Long (with duplicates).
When I try to run the command it tells me "Missing Operator in Query-Syntax.."
Is this a problem of my VB Code or is the SQL Syntax wrong?
MS Access database engine does not support COUNT(DISTINCT ...).
To workaroud it, please see this thread: SQL : how can i count distinct record in MS ACCESS where author suggests to solve issue by using subquery:
SELECT
user_id
, COUNT(*) AS count_distinct_clients
FROM
( SELECT DISTINCT
user_id,
client_id
FROM tbl_sActivity
) AS tmp
GROUP BY
user_id ;
Change the query code to your needs.
[EDIT]
SELECT
wday, COUNT(UserId) AS count_distinct_users
FROM
( SELECT DISTINCT WEEKDAY([Date]) AS wday, UserId
FROM tblName
) AS tmp
GROUP BY
wday;

Update one duplicate record and delete the rest of them - Classic ASP & SQL Server 2008r2

I want to update one duplicate record and delete the rest of them
I have a table...
id start unit
1 1 a
2 1 a
3 2 a
4 2 a
5 3 b
which I want to turn into...
id start unit
1 1 b
3 2 b
5 3 b
I have sorted out finding the duplicates but I'm failing to be able to do anything with them - or in the example below I end up deleting all the duplicates and not keeping the first record.
I'm also not convinced that this method will be the best way to approach the problem
strSQL_dup = "SELECT start_date, id
FROM test
WHERE start_date IN
(SELECT start_date
FROM test WHERE adId = " & adId & " AND Unit = " & scId & "
GROUP BY start_date HAVING (COUNT(start_date ) > 1) )
GROUP BY test.id, start_date"
Set rsSQL_dup = conn.Execute(strSQL_dup)
Do While Not rsSQL_dup.EOF
start_date = rsSQL_dup.Fields("start_date").value
id = rsSQL_dup.Fields("id").value
'Response.Write("<p> "&start_date&" | "& id & " update me </p>"
if bookingstate = "Provisional" Then
dateStatusNo = 8
else
dateStatusNo = 1
End if
'Response.Write("<p> " & id & " update me</p>")
strSQL_dup_update = "UPDATE test SET Unit = '" & dateStatusNo & "' WHERE id = '" & id & "' "
Set rsSQL_dup_update = conn.Execute(strSQL_dup_update)
strSQL_delete = "SELECT top 1 start_date, id FROM test WHERE start_date = " & start_date
Set rsSQL_delete = conn.Execute(strSQL_delete)
Do While Not rsSQL_delete.EOF
start_date = rsSQL_delete.Fields("start_date").value
id = rsSQL_delete.Fields("id").value
'Response.Write("<p> "&start_date&" | "& id & " delete me</p>")
strSQL_dup_delet = "DELETE FROM test WHERE id = '" & id & "' "
Set rsSQL_dup_delet = conn.Execute(strSQL_dup_delet)
rsSQL_delete.MoveNext()
Loop
rsSQL_dup.MoveNext()
Loop 'End Do While Not rsSQL_dup.EOF
Loop
i agree with #Ken white how a change into b but if you want to remove duplicate record
why dont you use distinct command like
select distinct start_date
FROM test
and if you want your query to run then you can combine it with your query like
select distinct start_date
FROM test WHERE start_date IN
(SELECT start_date
FROM test WHERE adId = " & adId & " AND Unit = " & scId & "
GROUP BY start_date HAVING (COUNT(start_date ) > 1) )
GROUP BY test.id, start_date"
and if you want to delete records then use this query
WITH test AS(
SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
RN = ROW_NUMBER()OVER(PARTITION BY col1 ORDER BY col1)
FROM dbo.Table1
)
DELETE FROM test WHERE RN > 1
I'll be honest. You can probably put this together with a merge or multiple statements in a transaction. But, why not just create a temporary table, truncate the original table, and then re-insert the data?
select min(id), start, 'b' as unit
into #test
from test
group by start;
truncate table test;
insert into test(id, start, unit)
select id, start, unit
from #test;
drop table #test;

max nearest values sql

I have a table with some numerical values (diameters)
18
21
27
34
42
48
60
76
89
114
etc...
How Can I select the max nearest value if I put for example in a text.box a number.
25 to select 27, 100 to select 114, 48 to select 48.
I put the following code but it is not acting correct ...It is selecting the closest nearest value but not the MAX nearest value:
strSQL = "SELECT * " & "FROM [materials] WHERE ABS([dia] - " & Me.TextBox1.Text & ") = (SELECT MIN(ABS([dia] - " & Me.TextBox1.Text & ")) FROM [materials])"
this code is inside on an user form in excel that is connected to an DAO database.
Thank you!
Lets say you were using SQL Server, you could try something like
strSQL = "SELECT TOP 1 * " & "FROM [materials] WHERE [dia] >= " & Me.TextBox1.Text & " ORDER BY dia ASC"
If it was MySQL You would have to use LIMIT
The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement.
strSQL = "SELECT TOP 1 * FROM materials " & _
"WHERE dia >= " & Me.TextBox1.Text & " " & _
"ORDER BY dia"
Actually, your problem description is wrong.
You don't want the closest nearest value, you want the minimum value of what's bigger or equal than requested.
The solution for what you actually requested would be:
DECLARE #fVal float
SET #fVal = 116 -- 114.5 -- 114.4 -- 114.6
;WITH CTE AS
(
SELECT
dia
,(#fVal - dia) AS dist
,ABS(#fVal - dia) AS absdist
,SIGN(#fVal - dia) AS sig
FROM
(
SELECT 18.0 AS dia
UNION SELECT 21.0 AS dia
UNION SELECT 27.0 AS dia
UNION SELECT 34.0 AS dia
UNION SELECT 42.0 AS dia
UNION SELECT 48.0 AS dia
UNION SELECT 60.0 AS dia
UNION SELECT 76.0 AS dia
UNION SELECT 89.0 AS dia
UNION SELECT 114.0 AS dia
UNION SELECT 115.0 AS dia
) AS tempT
)
SELECT TOP 1 * FROM
(
SELECT * FROM CTE as cte2
WHERE cte2.dist = (SELECT MAX(ct3.DIST) FROM CTE as ct3 WHERE sig = -1 )
UNION
SELECT * FROM CTE as cte2
WHERE cte2.dist = (SELECT MIN(ct3.DIST) FROM CTE as ct3 WHERE sig = 1)
UNION
SELECT * FROM CTE AS cte2
WHERE cte2.dist = 0
) AS o
ORDER BY
CASE WHEN dist = 0
THEN 0
ELSE 1
END
,absdist, sig