I am just curious, how do I concat join table so the result doesn't return many rows?
What I want is the firstname d return only one row like 001;004;005;003;007 in column interest, so in my grid doesn't display many rows.
Here's my code
.CommandText = String.Format("select aa.code, aa.firstname, cc.interest as interest from db.name aa ") _
'& ("left join db.interest cc on cc.lead = aa.code ") _
'& ("where convert(date,time) between '" & date1& "' and '" & date2& "' order by aa.code ")
I am asking here because I don't know the keyword that relates to this
You need to add GROUP BY Steatment to your query:
.CommandText = String.Format("select aa.code, aa.firstname,COUNT(aa.firstname) as 'FnameCount', cc.interest as interest from db.name aa ") _
'& ("left join db.interest cc on cc.lead = aa.code ") _
'& ("where convert(date,time) between '" & date1& "' and '" & date2& "' GROUP BY aa.code, aa.firstname, cc.interest order by aa.code ")
Related
I am trying to run a select query statement like this in a table from VBA:
variable_a = 1
variable_b = 2
after proper database connection the query goes like:
SQry = "select CONCAT(Col1,Colb) as TOTAL from MyTable where Col1 = '" & variable_a & "' AND '" & variable_b & "'"
But it fails.\
How can I use that "AND" in between 2 or more statements which are variables of VBA? It works fine with one condition but the "AND" or "OR" part messes it up.
Thank you
Tried dividing the query into several lines like:
sq1 = "select CONCAT(Col1,Colb) AS TOTAL from MyTable" &
sq2 = "where Col1 = " & _
sq3 = " '" & variable_a & "'" & _
sq4 = " ' and ' " & _
sq5 = " Col2 = '" & variable_b & "'"
Hi all below you see a screenshot of my database:
But now I want to be able to make a table that calculates every players last 5 games. As I'm totaly new to access db I really have no clue how to do this.
Can you guys help me a hand with this one?
When I use the 2nd snippet in the answer below I get these:
Below are SQL routes according to your data. To use in MS Access simply create a new query under Create Tab on Ribbon and place the below SQL in the SQL view of a new created query. You may need to adjust query according to your actual table names and/or fields.
SAME GAMES FOR ALL PLAYERS
Assuming every player shares the same last five games, you could run an aggregate query across all players, using a subquery in INNER JOIN clause to calculate last five game dates. Do note: subquery, LastFiveDates can be saved as its own query and used directly in INNER JOIN.
SELECT [LookUp to Players],
Sum(GamesWon) As SumOfGamesWon, Sum(GamesLost) As SumOfGamesLost,
Sum(OwnOdds) As SumOfOwnOdds, Sum(OppOdds) As SumOfOppOdds,
Sum(GamesPlayed) As SumOfGamesPlayed
FROM GamesTable
INNER JOIN
(
SELECT DISTINCT TOP 5 [Date]
FROM GamesTable
ORDER BY [Date] DESC
) As LastFiveDates
ON GamesTable.[Date] = LastFiveDates.[Date]
GROUP BY [LookUp to Players];
DIFFERING GAMES FOR EACH PLAYER
SIMPLE SELECT APPROACH
Now, if players differ in their last five games, you have to join on different queries or union queries. Again, the below uses a subquery in an inner join but you can save that LastFiveGames as its own stored query and join in INNER JOIN line.
SELECT GamesTable.[LookUp to Players],
Sum(GamesWon) As SumOfGamesWon, Sum(GamesLost) As SumOfGamesLost,
Sum(OwnOdds) As SumOfOwnOdds, Sum(OppOdds) As SumOfOppOdds,
Sum(GamesPlayed) As SumOfGamesPlayed
FROM GamesTable
INNER JOIN
(
SELECT [Lookup to Players], [Date],
(SELECT Count(*)
FROM GamesTable t2
WHERE GamesTable.[Date] <= t2.[Date]
AND GamesTable.[Lookup to Players] = t2.[Lookup to Players]) AS GameOrder
FROM GamesTable
) As LastFiveDates
ON GamesTable.[Date] = LastFiveDates.[Date]
AND GamesTable.[Lookup to Players] = LastFiveDates.[Lookup to Players]
WHERE LastFiveDates.GameOrder <= 5
GROUP BY GamesTable.[LookUp to Players];
DIFFERING GAMES FOR EACH PLAYER
VBA CREATE TABLE APPROACH
Due to performance issues of Access running the query as a stored query, VBA can re-create the GamesStats iteratively looping through all distinct players using the very first query condition for player.
Public Function GameTableStats()
Dim db As Database
Dim tbldef As TableDef, rst As Recordset
Dim strSQL As String, i As Integer
Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT DISTINCT PlayerName FROM GamesTable", dbOpenDynaset)
For Each tbldef In db.TableDefs
If tbldef.Name = "GamesStats" Then
db.Execute "DROP TABLE [GamesStats]", dbFailOnError
End If
Next tbldef
rst.MoveLast
rst.MoveFirst
i = 1
Do While Not rst.EOF
If i = 1 Then
' FIRST PLAYER (MAKE-TABLE QUERY) '
strSQL = "SELECT GamesTable.[PlayerName]," _
& " Sum(GamesWon) As SumOfGamesWon, Sum(GamesLost) As SumOfGamesLost," _
& " Sum(OwnOdds) As SumOfOwnOdds, Sum(OppOdds) As SumOfOppOdds," _
& " Sum(GamePlayed) As SumOfGamePlayed" _
& " INTO GamesStats" _
& " FROM GamesTable" _
& " INNER JOIN" _
& " (" _
& " SELECT DISTINCT TOP 5 [Date], [PlayerName]" _
& " FROM GamesTable" _
& " WHERE [PlayerName]=""" & rst!PlayerName & """" _
& " ORDER BY [Date] DESC" _
& " ) As LastFiveDates" _
& " ON GamesTable.[Date] = LastFiveDates.[Date]" _
& " WHERE GamesTable.[PlayerName]= """ & rst!PlayerName & """" _
& " GROUP BY GamesTable.[PlayerName];"
Else
' ALL OTHER PLAYERS (INSERT APPEND QUERIES) '
strSQL = "INSERT INTO GamesStats ([PlayerName], [SumOfGamesWon], [SumOfGamesLost]," _
& " [SumOfOwnOdds], [SumOfOppOdds], [SumOfGamePlayed])" _
& " SELECT GamesTable.[PlayerName], " _
& " Sum(GamesWon) As SumOfGamesWon, Sum(GamesLost) As SumOfGamesLost, " _
& " Sum(OwnOdds) As SumOfOwnOdds, Sum(OppOdds) As SumOfOppOdds, " _
& " Sum(GamePlayed) As SumOfGamePlayed " _
& " FROM GamesTable " _
& " INNER JOIN " _
& " ( " _
& " SELECT DISTINCT TOP 5 [Date], [PlayerName] " _
& " FROM GamesTable " _
& " WHERE [PlayerName]=""" & rst!PlayerName & """" _
& " ORDER BY [Date] DESC" _
& " ) As LastFiveDates " _
& " ON GamesTable.[Date] = LastFiveDates.[Date]" _
& " WHERE GamesTable.[PlayerName]= """ & rst!PlayerName & """" _
& " GROUP BY GamesTable.[PlayerName];"
End If
db.Execute strSQL, dbFailOnError
i = i + 1
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Set db = Nothing
MsgBox "Successfully created GamesStats table!", vbInformation
End Function
I have this Select statement that works fine:
rsCurrent.Source = "SELECT Calibrations.Cust_Ref, Calibrations.Rec_Date, Instruments.Inst_ID, Instruments.Description, Instruments.Model_no, Instruments.Manufacturer, Instruments.Serial_no, Instruments.Status, Instruments.Cust_Acc_No FROM Instruments INNER JOIN Calibrations ON Instruments.Inst_ID = Calibrations.Inst_ID WHERE Instruments.Cust_Name = '" & Session("MM_Username") & "' AND Instruments.Cust_Acc_No = '" & Session("MM_Password") & "' AND Instruments.Cust_Acc_No = '" + Replace(rsCurrent__MMColParam, "'", "''") + "' AND Instruments.Status IN ('E','F','G','H','I','K','L','M','N');"
I tried different approaches to try and set my records in descending order looking up for Calibrations.Rec_Date
What am I doing wrong?
Try,
rsCurrent.Source = "SELECT Calibrations.Cust_Ref, Calibrations.Rec_Date, Instruments.Inst_ID, Instruments.Description, Instruments.Model_no, Instruments.Manufacturer, Instruments.Serial_no, Instruments.Status, Instruments.Cust_Acc_No FROM Instruments INNER JOIN Calibrations ON Instruments.Inst_ID = Calibrations.Inst_ID WHERE Instruments.Cust_Name = '" & Session("MM_Username") & "' AND Instruments.Cust_Acc_No = '" & Session("MM_Password") & "' AND Instruments.Cust_Acc_No = '" + Replace(rsCurrent__MMColParam, "'", "''") + "' AND Instruments.Status IN ('E','F','G','H','I','K','L','M','N') ORDER BY Calibrations.Rec_Date DESC;"
http://www.w3schools.com/sql/sql_orderby.asp
You may want to try ORDER BY DATE(Calibrations.Rec_Date)
I have this sql string:
Dim sqlQuery As String = "SELECT TOP 1 ID, FName, FoodGroup, Calories, Protein, Carbohydrates, Fat, category.ID" &
" FROM food where Protein<='" & txtProt.Text.ToString() & "' and FoodGroup = 4 " & "and category.ID = 1 " & "JOIN foodCategory ON food.ID = foodCategory.Food_ID" & "JOIN category ON foodCategory.Category_ID = category.ID " & "ORDER BY NEWID() "
What i want to do is this: I want to type the value "FName" from table "food" to an textBox where the "ID" field of table "category" is 1.
I have 3 tables. The first is table food, the second one is table category and the third one is foodCategory.
The table foodCategory has the ID's from the first 2 tables to a one-to-many relationship.
I get the following error : Incorrect syntax near JOIN.
What do i do wrong?
your query is incorrect, the JOINs have to be set within the FROM clause, not in the WHERE clause.
Try the following query
dim sqlQuery As String
sqlQuery = "SELECT TOP 1 ID, FName, FoodGroup, Calories, Protein, " & _
"Carbohydrates, Fat, category.ID " &_
"FROM food JOIN foodCategory ON " & _
"food.ID = foodCategory.Food_ID JOIN category ON " & _
"foodCategory.Category_ID = category.ID " & _
"where Protein<='" & txtProt.Text.ToString() & "' and " & _
"FoodGroup = 4 and category.ID = 1 " & _
"ORDER BY NEWID() "
Furthermore you should have look at Parameter as your code is very vulnerable to SQL injection!
It's probably your concatenation:
... foodCategory.Food_ID" & "JOIN category ...
would evaluate to
foodCategory.Food_IDJOIN category
Your JOIN must be before the WHERE clause:
" FROM food" & " JOIN foodCategory ON food.ID = foodCategory.Food_ID" & "JOIN category ON foodCategory.Category_ID = category.ID " & " WHERE Protein<='" & txtProt.Text.ToString() & "' and FoodGroup = 4 " & "and category.ID = 1 " & " ORDER BY NEWID() ";
Dim rt As DAO.Recordset
strSQL = "SELECT DISTINCT A.OBJ FROM "
strSQL = strSQL & "(SELECT VARBL AS OBJ FROM AGR_1252 WHERE AGR_NAME = '" _
& AGR & "') A LEFT JOIN "
strSQL = strSQL _
& "(SELECT DISTINCT CONF_USOBT_C_ORG.ORG_OBJECT AS OBJ FROM Role_Content, CONF_USOBT_C_ORG "
strSQL = strSQL & "WHERE Role_Content.AGR_NAME = '" _
& AGR & "' AND Role_Content.TCode = [CONF_USOBT_C_ORG].[Name] AND Role_Content.TCode <> '" & tc & "') B "
strSQL = strSQL & "ON A.OBJ = B.OBJ WHERE B.OBJ Is Null"
Set rt = CurrentDb.OpenRecordset(strSQL)
Do While Not rt.EOF
DoCmd.RunSQL "DELETE FROM AGR_1252 WHERE AGR_NAME = '" & AGR & "' AND VARBL = '" & rt("OBJ") & "'" ', False
rt.MoveNext
Loop
rt.Close
Set rt = Nothing
I have the code above. I dont know why but it's giving me a time out error on the while loop. I dont know if it if because of the Recordset, but the table is blocking after he mades the firts Delete.
There is another way to select records without using RecordSet?
Thanks in advance.
I think you may be looking for something on the lines of:
DELETE FROM AGR_1252
WHERE AGR_NAME = Agr
AND Varbl Not In (
SELECT c.ORG_OBJECT
FROM Role_Content r
INNER JOIN CONF_USOBT_C_ORG c
ON r.TCode =c.[Name]
WHERE r.AGR_NAME Is Null)