How Can I merge these two Access Sql queries - sql

I want to merge these two queries into one query.
Here are the codes.
it's one table for both, but you see different data from different parts.
Just I want to make one record with only one query.
> DoCmd.RunSQL "insert into Report (id, [date], namep , [NEXTC],
> [Nurse])" & _ " values (" & Chr(34) & x & Chr(34) & " ," & Chr(34) & b
> & Chr(34) & "," & "5," & _ " " & Chr(34) & c & Chr(34) & ", " &
> Chr(34) & n & Chr(34) & ")"
and this one
DoCmd.RunSQL "INSERT INTO Report ( brand, Bag, Acc, Id , NameP)" & _
"Select Top 1 * from" & _
"(SELECT TOP 1 Brand FROM (SELECT * FROM Report WHERE ID=" & _
x & _
") WHERE Brand IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Brand IS NULL) AS Brand," & _
"(SELECT TOP 1 Bag FROM (SELECT * FROM Report WHERE ID=" & _
x & _
") WHERE Bag IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Bag IS NULL) AS Bag," & _
"(SELECT TOP 1 ACC FROM (SELECT * FROM Report WHERE ID=" & _
x & _
") WHERE ACC IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE ACC IS NULL) AS ACC," & _
"(SELECT TOP 1 ID FROM Report WHERE ID=" & _
x & _
") AS ID," & _
"( SELECT TOP 1 NameP FROM Report WHERE ID=" & _
x & _
") as NameP;"

Test this, it should work (maybe some parentheses be wrong, check it before use):
DoCmd.RunSQL "insert into Report (id, [date], namep , [NEXTC], [Nurse], brand, Bag, Acc, Id , NameP)" & _
" values (" & Chr(34) & x & Chr(34) & " ," & Chr(34) & b & Chr(34) & "," & "5," & _
" " & Chr(34) & c & Chr(34) & ", " & Chr(34) & n & Chr(34) & ", " & _
"(SELECT TOP 1 Brand FROM (SELECT * FROM Report WHERE ID=" & x & _
") WHERE Brand IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Brand IS NULL) AS Brand " & ", " & _
"(SELECT TOP 1 Bag FROM (SELECT * FROM Report WHERE ID=" & x & _
") WHERE Bag IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE Bag IS NULL) AS Bag " & ", " & _
"(SELECT TOP 1 ACC FROM (SELECT * FROM Report WHERE ID=" & x & _
") WHERE ACC IS NOT NULL ORDER BY date DESC Union All SELECT top 1 null FROM report WHERE ACC IS NULL) AS ACC " & ", " & _
"(SELECT TOP 1 ID FROM Report WHERE ID=" & x & ") AS ID," & _
"( SELECT TOP 1 NameP FROM Report WHERE ID=" & x & ") as NameP )"

Your query is not clear but your query should be something like this:
INSERT INTO Report (id, [date], namep , [NEXTC], [Nurse], brand, Bag, Acc, Id , NameP)
SELECT TOP 1 'value1', 'value2', ..., FROM yourTable ...
Using INSERT INTO SELECT
value1, value2 could be statistic but also you can get some value from yourtable

Related

SELECT INTO inserts only the last row - VBA, Access 2000?

I have this SQL string which I create in a Loop:
"SELECT '" & Trim(Str(j)) & "' AS cpa, Count(Val('" & rsCPANezbirni("tipprod") & "')) AS BrojProd, Sum(Val('" & rsCPANezbirni("povrsina") & "')) AS p, Sum(Val('" & rsCPANezbirni("pmagacin") & "')) AS pm INTO T14_KPD_CPA_samo_podatoci FROM CPA_nezbirni WHERE (t4k" & Trim(Str(j)) & "<>'' Or t4k" & Trim(Str(j)) & " Is Not Null);"
And the loop I use is:
Dim j As Integer
j = 1
Do While j <= 3
cpaSelectSQL = "SELECT '" & Trim(Str(j)) & "' AS cpa, Count(Val('" & rsCPANezbirni("tipprod") & "')) AS BrojProd, Sum(Val('" & rsCPANezbirni("povrsina") & "')) AS p, Sum(Val('" & rsCPANezbirni("pmagacin") & "')) AS pm INTO T14_KPD_CPA_samo_podatoci FROM CPA_nezbirni WHERE (t4k" & Trim(Str(j)) & "<>'' Or t4k" & Trim(Str(j)) & " Is Not Null);"
Debug.Print "j = " & Str(j) & ", cpa select SQL: " & cpaSelectSQL
DoCmd.RunSQL cpaSelectSQL, True
On Error GoTo ErrorHandler
j = j + 1
Loop
The problem I have, only the last generated row gets copied in T14_KPD_CPA_samo_podatoci i.e cpa = 3
I want to copy each for for the value of cpa 1 to 3.
What do I do wrong?
SELECT INTO is a "Create table" query, it will overwrite the target table each time you run it.
Once the table exists you need INSERT INTO.
Well, I used this sort of SQL query
INSERT INTO table1 (col1, col2, ..., coln) SELECT col1, col2,..., coln FROM table2 WHERE condition GROUP BY colx;

WHERE clause makes LEFT JOIN work like an INNER JOIN

I am trying to left join three tables with a where clause. In the first example
the query results in an inner join. If I take out the where clause it results in a left join, but in includes records outside the desired date range.
I'm using Microsoft Access 2010 and Visual Basic 2010.
strQry = " SELECT tblUnits.UnitNumber, TenantName, SchedRent, SchedCAM, sum(AMOUNT) as SUMAMOUNT " _
& " FROM ((tblUnits LEFT JOIN tblTenants ON tblTenants.Unitptr = tblUnits.ID) " _
& " LEFT JOIN tblTrans ON (tblTenants.ID = tblTrans.id) ) " _
& " WHERE (tblTrans.PostDate BETWEEN #" & txtStartDate.Text & "# AND #" & txtEndDate.Text & "# ) " _
& " GROUP BY tblUnits.UnitNumber, TenantName, SchedRent, SchedCAM " _
& " ORDER BY tblUnits.UnitNumber "
In the second example it works perfectly, but only joins two tables
strQry = " SELECT U.UnitNumber, sum(AMOUNT) as sumamount " _
& " FROM tblUnits AS U " _
& " LEFT JOIN " _
& " ( " _
& " SELECT * " _
& " FROM tblTrans " _
& " WHERE (tblTrans.PostDate BETWEEN #" & txtStartDate.Text & "# AND #" & txtEndDate.Text & "# ) " _
& " ) as X " _
& " ON U.ID = X.ID " _
& " GROUP BY U.UnitNumber "
I can't get the syntax correct when I try to join the third table
Try WHERE tblTrans.PostDate IS NULL OR ...
As it stands, your LEFT JOIN includes tblUnits rows for which there is no matching tblTrans row. Then your WHERE clause eliminates these rows.
The following works
strQry = " SELECT U.UnitNumber, T.TenantName, T.SchedRent, T.SchedCAM, sum(AMOUNT) as SUMAMOUNT " _
& " FROM ((tblUnits AS U " _
& " LEFT JOIN tblTenants as T ON U.ID = T.UnitPtr) " _
& " LEFT JOIN " _
& " ( " _
& " SELECT * " _
& " FROM tblTrans " _
& " WHERE (tblTrans.PostDate BETWEEN #" & txtStartDate.Text & "# AND #" & txtEndDate.Text & "# ) " _
& " ) as X " _
& " ON U.ID = X.ID) " _
& " GROUP BY U.UnitNumber, TenantName, SchedRent, SchedCAM " _
& " ORDER BY U.UnitNumber "

Using insert into where not exists in VBA

I have a lovely form and a lovely table in MS access (I promise). I would like to insert into this table at the press of a button using where not exists but I am getting a not-so-friendly run-time error 3067: "Query input must contain at least one table or query."
My query already does...
strSQL = "insert into tbl_MAP_systemTask (TaskID, SystemID) " & _
" Values (" & taskID & ", " & sysID & _
") where not exists " & _
" (select M.TaskID, M.SystemID from tbl_MAP_systemTask as M where M.TaskID = " & taskID & _
" and M.SystemID = " & sysID & ");"
Debug.Print strSQL
DoCmd.RunSQL (strSQL)
strSQL is now
insert into tbl_MAP_systemTask (TaskID, SystemID)
Values (1, 1)
where not exists
(select M.TaskID, M.SystemID
from tbl_MAP_systemTask as M where M.TaskID = 1 and M.SystemID = 1);
Can anyone shed any light on
a) what I broke?
b) how to fix it?
Well instead of using a SubQuery, you could use a Domain function to get this going,
If Dcount("*", "tbl_MAP_systemTask", "TaskID = " & taskID & " AND SystemID = " &sysID) = 0 Then
strSQL = "INSERT INTO tbl_MAP_systemTask (TaskID, SystemID) " & _
" VALUES (" & taskID & ", " & sysID & ")
CurrentDb.Execute strSQL
Else
MsgBox "The Data already exists in the table, so nothing was added."
End If
Try this:
strSQL = "insert tbl_MAP_systemTask (TaskID, SystemID) " & _
" select " & taskID & ", " & sysID & _
" where not exists " & _
" (select M.TaskID, M.SystemID from tbl_MAP_systemTask as M where M.TaskID = " & taskID & _
" and M.SystemID = " & sysID & ");"
=>
insert tbl_MAP_systemTask (TaskID, SystemID)
select 1, 1
where not exists
(select M.TaskID, M.SystemID
from tbl_MAP_systemTask as M where M.TaskID = 1 and M.SystemID = 1);
and seems to work in my case. Seems like the where not exists needs a select statement, so you have to model your insert like this.
Maybe you can use a recordset to insert these values.
Dim rs as Recordset
Set rs = Currentdb.openRecordset("SELECT * FROM tbl_MAP_systemTask WHERE TaskID=" & Me.TaskID & " AND SystemID=" & Me.SystemID)
if not (rs.eof or rs.bof) then
rs.addnew
rs.TaskID = Me.TaskID
rs.SystemID = Me.SystemID
rs.update
end if
rs.close
set rs = nothing
TOP 1 clause is must in the main query.
INSERT INTO tbl_MAP_systemTask (TaskID, SystemID)
SELECT TOP 1 1 AS TaskID 1 AS SystemID
FROM tbl_MAP_systemTask
WHERE NOT EXISTS (SELECT TOP 1 TaskID,SystemID FROM
tbl_MAP_systemTask WHERE TaskID = 1 and SystemID=1);
If tbl_MAP_systemTask table is empty or if there is only one record in the table then TOP 1 clause must be omitted in sub-query.
I have included Top 1 clause is sub-query for performance purpose.

Access 2010 VBA SQL INSERT with multiple SELECT

The following Code prompts out with, according to google, a kind of random/default error that doenst really lead to the problem. (Query input must contain at least one table or query)
Private Sub ButtonInsertUntergruppe_Click()
Dim sql As String
sql = "INSERT INTO tblArbeitsschritte (Auftrag_FK, Prozesspunkt_FK, Prozesspunkt) " & _
"VALUES (" & _
Forms!frm_GUI!ID_Auftraege & _
", " & _
"(SELECT ID_Prozesspunkt " & _
"FROM tblProzesspunkt " & _
"WHERE Untergruppe_FK = " & _
Me.cbUntergruppe.Column(0) & _
") , " & _
"(SELECT Prozesspunkt " & _
"FROM tblProzesspunkt " & _
"WHERE Untergruppe_FK = " & _
Me.cbUntergruppe.Column(0) & _
"));"
Debug.Print sql
CurrentDb.Execute sql, dbFailOnError
End Sub
This is what the debugger gives me:
INSERT INTO tblArbeitsschritt
(
Auftrag_FK, Prozesspunkt_FK, Prozesspunkt
)
VALUES
(
1,
(SELECT ID_Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1)
,
(SELECT Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1)
);
Not sure if that syntax is supported. Personally I would do:
INSERT INTO tblArbeitsschritt
(
Auftrag_FK, Prozesspunkt_FK, Prozesspunkt
)
SELECT 1, ID_Prozesspunkt, Prozesspunkt
FROM tblProzesspunkt
WHERE Untergruppe_FK = 1

Query - Error assigning value to variable in VB

I have the following code to query in VB6:
SQL = " if object_id('tempdb..#MovSeq','U') is not null drop table #MovSeq;" & _
" declare #Data_Inicio datetime, #Data_Fim datetime; set dateformat dmy; set #Data_Inicio = DataInicio; set #Data_Fim = DataFinal; set #Data_Fim = DateAdd(day, +1, #Data_Fim); " & _
" with Mov as ( SELECT EI.Cod_Empresa, EI.Cod_Estoque, EI.Cod_Produto, 'E' as Tipo_Mov, E.Dta_Entrada as Data_Mov, EI.id_Doc as NF, EI.Qtde, EI.V_Unitario, EI.V_Total " & _
" from Entrada_Itens as EI inner join Entrada as E on EI.Cod_Empresa=E.Cod_Empresa and EI.id_Doc=E.id_Doc " & _
" where E.Dta_Entrada >= #Data_Inicio and EI.Cod_Empresa='" & Sys.Empresa & "' and EI.Cod_Estoque='" & dcEstoque.BoundText & "' and EI.Cod_Produto='" & dtProdutos.BoundText & "' " & _
" Union " & _
" SELECT SI.Cod_Empresa, SI.Cod_Estoque, SI.Cod_Produto, 'S', S.Dta_Entrada , SI.id_Doc, -SI.Qtde, SI.V_Unitario, SI.V_Total " & _
" from Saida_Itens as SI inner join Saida as S on SI.Cod_Empresa=S.Cod_Empresa and SI.id_Doc=S.id_Doc " & _
" where S.Dta_Entrada >= #Data_Inicio and SI.Cod_Empresa='" & Sys.Empresa & "' and SI.Cod_Estoque='" & dcEstoque.BoundText & "' and SI.Cod_Produto='" & dtProdutos.BoundText & "' " & _
" Union " & _
" SELECT Cod_Empresa, Cod_Estoque, Cod_Produto, 'A', #Data_Inicio, null, null, null, null " & _
" From Estoque " & _
" where Cod_Empresa='" & Sys.Empresa & "' and Cod_Estoque='" & dcEstoque.BoundText & "' and Cod_Produto='" & dtProdutos.BoundText & "') " & _
" SELECT *, Seq= row_number() over (partition by Cod_Empresa, Cod_Estoque, Cod_Produto order by Data_Mov desc, Tipo_Mov desc) into #MovSeq from Mov; " & _
" create unique clustered index IndMovSeq on #MovSeq (Cod_Empresa, Cod_Estoque, Cod_Produto, Seq); " & _
" SELECT M.Cod_Empresa, M.Cod_Estoque, M.Cod_Produto, P.Descricao," & _
" Estoque= case when M.Seq=1 then E.Qtde_Estoque else (E.Qtde_Estoque - (SELECT sum(Mi.Qtde) from #MovSeq as Mi " & _
" Where Mi.Cod_Empresa = M.Cod_Empresa And Mi.Cod_Estoque = M.Cod_Estoque And Mi.Cod_Produto = M.Cod_Produto and Mi.Seq < M.Seq)) end " & _
" from #MovSeq as M inner join " & _
" Estoque as E on M.Cod_Empresa=E.Cod_Empresa and M.Cod_Estoque=E.Cod_Estoque and M.Cod_Produto=E.Cod_Produto inner join " & _
" Produtos as P on M.Cod_Empresa=P.Cod_Empresa and M.Cod_Estoque=P.Cod_Estoque and M.Cod_Produto=P.Cod_Produto " & _
" where Data_Mov < #Data_Fim " & _
" order by M.Cod_Empresa, M.Cod_Estoque, M.Cod_Produto, Seq desc; " & _
" drop table #MovSeq;"
the error appears 'invalid columm name' when run showing DataInicio as a reason
I know the error is in the assignment of the variable. but how to solve.
Thanks for the help...
Your type of code is very prone to SQL Injection attacks...
Are you escaping the variable values correctly? A simple quote (') in one of the variables can change the SQL string completely...
You should consider using parameters to pass values instead of building SQL commands using string concatenation.