Access Sql about pivot - sql

I have four tables now.
StuInfo
ActInfo
ActAttendance
ActLateArriveAndEarlyLeave
For Type, 1 = late arrive, 2 = early leave
Is it possible to generate a query like this with one sql statement?
C3:E4 are the cells which store the total time a person invloved in an activity.
Or if it is not possible, I want to export the final result to an Excel file.
How can I do it in VBA?
Thanks very much. Please let me know if I didn't explain clearly enough.

Pivot table is what you need unfortunately I cannot find a way to export one from Access as a flat query. It will only export it as a pivot table in excel. This query will get you the correct data. Then you have to create a pivot from it
SELECT DISTINCT
StuInfo.StuName AS Name,
StuInfo.Stu_No,
DateDiff("h",IIf([AcctLateAriveAndEarlyLeave].[Type]=1,[AcctLateAriveAndEarlyLeave].[Time],[AcctInfo].[sTime]),IIf([AcctLateAriveAndEarlyLeave].[Type]=2,[AcctLateAriveAndEarlyLeave].[Time],[AcctInfo].[eTime])) AS AttendedFor, Format([AcctInfo].[sTime],"mm/dd/yyyy") AS OnDate
FROM ((StuInfo LEFT JOIN AcctAttendance ON StuInfo.Stu_No = AcctAttendance.Stu_No) LEFT JOIN AcctInfo ON AcctAttendance.[Act_S/N] = AcctInfo.[S/N]) LEFT JOIN AcctLateAriveAndEarlyLeave ON StuInfo.Stu_No = AcctLateAriveAndEarlyLeave.Stu_No;
Then you can create a pivot table that looks like this
Obviously if you want something other than explicit hours you have to change the query a bit.

A crosstab query can work. However, I need a little bit more information for what the values under date fields calculate. In my example I assume they are Max(Type)
TRANSFORM Max(Type) AS MaxOfType
SELECT StuInfo.SteName, StuInfo.Stu_No FROM StuInfo
INNER JOIN ActLateArriveAndEarlyLeave ON StuInfo.Stu_No = ActLateArriveAndEarlyLeave.Stu_No
GROUP BY StuInfo.Ste_No, StuInfo.SteName
PIVOT Format(ActLateArriveAndEarlyLeave.TimeValue, 'short date');

Related

Is it possible to loop in SQL data blocks?

select a.Client, a.Period_Id, a.Business_Name, a.Tax, a.Number_Workers,
a.Business_Item, a.Start_Date, a.End_Date, a.Taxpayer
from sii_2014_1 as a
inner join (
select Client, count(Client) as uniques
from sii_2014_1
group by Client
having count(Client) = 1
) as b
on a.Client= b.Client
Which removes the original Client if you have duplicates along with their duplicates. I did this for the sii_2014_1 table. But I want to do it for 2 other tables that are called sii_2015_1 and sii_2016_1. The only thing that changes from the tables is the last digit of the year so I thought I could use a loop to save code. Is this possible in the SQL of the DataBricks?
Thank you all for your comments.
Since you have only three and instance to take care and I beleive that the intend is to reduce the code , I suggest you to explore creating a view which you can use in your query .
https://docs.databricks.com/spark/latest/spark-sql/language-manual/create-view.html

MS Access 2013, How to add totals row within SQL

I'm in need of some assistance. I have search and not found what I'm looking for. I have an assigment for school that requires me to use SQL. I have a query that pulls some colunms from two tables:
SELECT Course.CourseNo, Course.CrHrs, Sections.Yr, Sections.Term, Sections.Location
FROM Course
INNER JOIN Sections ON Course.CourseNo = Sections.CourseNo
WHERE Sections.Term="spring";
I need to add a Totals row at the bottom to count the CourseNo and Sum the CrHrs. It has to be done through SQL query design as I need to paste the code. I know it can be done with the datasheet view but she will not accept that. Any advice?
To accomplish this, you can union your query together with an aggregation query. Its not clear from your question which columns you are trying to get "Totals" from, but here's an example of what I mean using your query and getting counts of each (kind of useless example - but you should be able to apply to what you are doing):
SELECT
[Course].[CourseNo]
, [Course].[CrHrs]
, [Sections].[Yr]
, [Sections].[Term]
, [Sections].[Location]
FROM
[Course]
INNER JOIN [Sections] ON [Course].[CourseNo] = [Sections].[CourseNo]
WHERE [Sections].[Term] = [spring]
UNION ALL
SELECT
"TOTALS"
, SUM([Course].[CrHrs])
, count([Sections].[Yr])
, Count([Sections].[Term])
, Count([Sections].[Location])
FROM
[Course]
INNER JOIN [Sections] ON [Course].[CourseNo] = [Sections].[CourseNo]
WHERE [Sections].[Term] = “spring”
You can prepare your "total" query separately, and then output both query results together with "UNION".
It might look like:
SELECT Course.CourseNo, Course.CrHrs, Sections.Yr, Sections.Term, Sections.Location
FROM Course
INNER JOIN Sections ON Course.CourseNo = Sections.CourseNo
WHERE Sections.Term="spring"
UNION
SELECT "Total", SUM(Course.CrHrs), SUM(Sections.Yr), SUM(Sections.Term), SUM(Sections.Location)
FROM Course
INNER JOIN Sections ON Course.CourseNo = Sections.CourseNo
WHERE Sections.Term="spring";
Whilst you can certainly union the aggregated totals query to the end of your original query, in my opinion this would be really bad practice and would be undesirable for any real-world application.
Consider that the resulting query could no longer be used for any meaningful analysis of the data: if displayed in a datagrid, the user would not be able to sort the data without the totals row being interspersed amongst the rest of the data; the user could no longer use the built-in Totals option to perform their own aggregate operation, and the insertion of a row only identifiable by the term totals could even conflict with other data within the set.
Instead, I would suggest displaying the totals within an entirely separate form control, using a separate query such as the following (based on your own example):
SELECT Count(Course.CourseNo) as Courses, Sum(Course.CrHrs) as Hours
FROM Course INNER JOIN Sections ON Course.CourseNo = Sections.CourseNo
WHERE Sections.Term = "spring";
However, since CrHrs are fields within your Course table and not within your Sections table, the above may yield multiples of the desired result, with the number of hours multiplied by the number of corresponding records in the Sections table.
If this is the case, the following may be more suitable:
SELECT Count(Course.CourseNo) as Courses, Sum(Course.CrHrs) as Hours
FROM
Course INNER JOIN
(SELECT DISTINCT s.CourseNo FROM Sections s WHERE s.Term = "spring") q
ON Course.CourseNo = q.CourseNo

SQL - LEFT JOIN and WHERE statement to show just first row

I read many threads but didn't get the right solution to my problem. It's comparable to this Thread
I have a query, which gathers data and writes it per shell script into a csv file:
SELECT
'"Dose History ID"' = d.dhs_id,
'"TxFieldPoint ID"' = tp.tfp_id,
'"TxFieldPointHistory ID"' = tph.tph_id,
...
FROM txfield t
LEFT JOIN txfielpoint tp ON t.fld_id = tp.fld_id
LEFT JOIN txfieldpoint_hst tph ON fh.fhs_id = tph.fhs_id
...
WHERE d.dhs_id NOT IN ('1000', '10000')
AND ...
ORDER BY d.datetime,...;
This is based on an very big database with lots of tables and machine values. I picked my columns of interest and linked them by their built-in table IDs. Now I have to reduce my result where I get many rows with same values and just the IDs are changed. I just need one(first) row of "tph.tph_id" with the mechanics like
WHERE "Rownumber" is 1
or something like this. So far i couldn't implement a proper subquery or use the ROW_NUMBER() SQL function. Your help would be very appreciated. The Result looks like this and, based on the last ID, I just need one row for every og this numbers (all IDs are not strictly consecutive).
A01";261511;2843119;714255;3634457;
A01";261511;2843113;714256;3634457;
A01";261511;2843113;714257;3634457;
A02";261512;2843120;714258;3634464;
A02";261512;2843114;714259;3634464;
....
I think "GROUP BY" may suit your needs.
You can group rows with the same values for a set of columns into a single row

In Access 2010, how do I write an update query to "fill in the blanks"?

Here is a picture explaining what I have and what I'm looking for.
Tables and data describing the question.
This originally seemed like a very simple update query but it has proven I really don't understand how the query works. Can someone please explain the SQL I would need to move all the data from tblImport.Addtl_Initiator to the respective blanks under tblEntries.Initiator, and the data from tblImport.Addtl_Date_Initiated to the respective blanks under tblEntries.Date_Initiated? Essentially just moving the data to the left one column, but in a different table.
Additional information: There is a unique ID field on each of the tables not shown in the picture.
Try it with Nz.
UPDATE tblentries
INNER JOIN tblimport
ON tblentries.eid = tblimport.eid
AND tblentries.initiator = tblimport.initiator
AND tblentries.date_initiated = tblimport.date_initiated
SET tblentries.initiator = nz(tblimport.initiator, tblimport.addtl_initiator),
tblentries.date_initiated = nz(tblimport.date_initiated, import.addtl_date_initiated)
This link might also be helpful: coalesce alternative in Access SQL
Use IsNull to get the non-blank values:
SELECT
IsNull(Initiator, Addtl_Inititator) AS Initiator,
IsNull(Date_Initiated, Addtl_Date_Initiated) AS Date_Initiated,
FROM
tblImport

Convert row data into columns Access 07 without using PIVOT

I am on a work term from school. I am not very comfortable using SQL, I am trying to get a hold of it....
My supervisor gave me a task for a user in which I need to take row data and make columns. We used the Crosstab Wizard and automagically created the SQL to get what we needed.
Basically, we have a table like this:
ReqNumber Year FilledFlag(is a checkbox) FilledBy
1 2012 (notchecked) ITSchoolBoy
1 2012 (checked) GradStudent
1 2012 (notchecked) HighSchooler
2 etc, etc.
What the user would like is to have a listing of all of the req numbers and what is checked
Our automatic pivot code gives us all of the FilledBy options (there are 9 in total) as column headings, and groups it all by reqnumber.
How can you do this without the pivot? I would like to wrap my head around this. Nearest I can find is something like:
SELECT
SUM(IIF(FilledBy = 'ITSchoolboy',1,0) as ITSchoolboy,
SUM(IIF(FilledBy = 'GradStudent',1,0) as GradStudent, etc.
FROM myTable
Could anyone help explain this to me? Point me in the direction of a guide? I've been searching for the better part of a day now, and even though I am a student, I don't think this will be smiled upon for too long. But I would really like to know!
I think your boss' suggestion could work if you GROUP BY ReqNumber.
SELECT
ReqNumber,
SUM(IIF(FilledBy = 'ITSchoolboy',1,0) as ITSchoolboy,
SUM(IIF(FilledBy = 'GradStudent',1,0) as GradStudent,
etc.
FROM myTable
GROUP BY ReqNumber;
A different approach would be to JOIN multiple subqueries. This example pulls in 2 of your categories. If you need to extend it to 9 categories, you would have a whole lot of joining going on.
SELECT
itsb.ReqNumber,
itsb.ITSchoolboy,
grad.GradStudent
FROM
(
SELECT
ReqNumber,
FilledFlag AS ITSchoolboy
FROM myTable
WHERE FilledBy = "ITSchoolboy"
) AS itsb
INNER JOIN
(
SELECT
ReqNumber,
FilledFlag AS GradStudent
FROM myTable
WHERE FilledBy = "GradStudent"
) AS grad
ON itsb.ReqNumber = grad.ReqNumber
Please notice I'm not suggesting you should use this approach. However, since you asked about alternatives to your pivot approach (which works) ... this is one. Stay tuned in case someone else offers a simpler alternative. :-)