Extract Both Counts AND Earliest Instance from my Dataset - sql

Using Microsoft Sql 2000
I have a requirement to be able to email a monthly report that details a number of events.
(I have got the email bit sussed).
Amongst the data I need to email is a report on the number of certain courses people have attended. (so far so easy, couple of inner joins and a Count() and Im there.)
To add to that, some of the internal courses that we run have an expiry date which prompts a referesher course. I have been able to crudely get the data I need by using the sql code for part one and sticking the result set into a temp table, then by iterating over each row in that table, getting the user Id, querying the users course attendences, sorting it on date so that the earliest is at the top, and just taking the TOP 1 record.
This seems so inefficient, so is there any way I can ammend my current query so that I can also get the date of just the earliest course that the user attended?
i.e.
SELECT uName, COUNT(uId), [ not sure what would go in here] FROM UserDetails
INNER JOIN PassDates
ON PassDates.fkUser = uId)
GROUP BY uName, uId
where, for examples sake
UserDetails
uId
uName
and
PassDates
fkUser
CourseId
PassDate
Hope Ive explained this well enough for someone to help me.

To put an answer to the question..
SELECT uName, COUNT(uId), MIN(PassDate)
FROM UserDetails
INNER JOIN PassDates ON PassDates.fkUser = uId
GROUP BY uName, uId
You can turn it into a left join if you have users without any courses (yet)

Related

Get account information based on last login time

I have this query
SELECT
c.* ,concat ( s.FirstName,'',s.LastName) as FullName
FROM [dbo].[Monitor] c
left join acc.Staff s on s.Id = c.UserId where c.UserId=1
Results:
enter image description here
How to get account information based on last login time in SQL Server.
I don't know how to get account information based on last login time.
From what I understand you want to query the very last login.
SELECT TOP 1 * FROM Monitor m Join Staff s on s.Id = m.UserId
WHERE Object = 'Login' ORDER BY AccessDate Desc
Here is an explanation of the code.
SELECT TOP 1 * FROM Monitor m
The code above is going to query only 1 result (TOP 1) and show all the columns (*) from the table Monitor. If you wish to get only specific columns, you can change * to whatever columns needed. I've given the table Monitor the alias m, because the word starts with that letter, but you can name your alias however you please, for as long as you remember it, or it's easy to realize what column it refers to.
Join Staff s ON s.Id = m.UserID
I've used Join, because you haven't really specified what exact result you are expecting, your question is more about getting the last login, so whatever join is used depends on your expectations. The same goes with the columns I've joined the two tables on. I just copied yours, but they would depend on demanded result and obviously if you have a foreign key in any of the tables, then use that key to join them.
WHERE Object = 'Login' ORDER BY AccessDate DESC
This is the important part of the code for your question. By specifying that we only need rows WHERE the column Object has value of 'Login', we are making sure that only Logins, are shown and all the Logouts are excluded. With ORDER BY AccessDate DESC, we are making sure that the biggest date value is at the top. The way dates work in SQL Server, if you compare two dates, the later date is considered bigger, so the last login would be at the very top, and since we have SELECT TOP 1 at the beginning we are making sure that we are going to get only the very last row.

MS Access SQL, sort by age in a specific order

My task: "Compile an SQL query that outputs a specific store (enter parameter window) the age of the youngest buyer"
I´ve tried some things, but because i´m new to SQL and i have no idea what i´m doing non of them seem to work.
I´d really appreciate, if someone would help me.
Thanks!
First you need to know the fields to SELECT (or return) and the table FROM which you are querying (asking) data; let's say you have the following tables: tblStores (containing a list of stores and related info), tblCustomers (containing customers and related info, e.g. ages, names, phone numbers, etc.), and tblPurchases (containing all the purchases at all stores by all customers and related info). You want the minimum age of a customer making a purchase at a specfic store, so you could use a MIN aggregating function. You would want to join (or relate) the tables based on customers and purchases. See my INNER JOINs in the example below. Then you filter the result by the user-inputted store name (inputStoreName) using WHERE; since the inputStoreName is undefined, in Access this would cause the parameter entry popup window to appear.
SELECT list of fields or aggregating functions you want (comma-separated)
FROM list of tables the fields are in (comma-separated) and how to join the tables
WHERE list of conditions to filter the data (separated by AND or OR)
Example:
SELECT tblStores.Name, tblStores.Description, MIN(tblCustomers.age)
FROM tblStores INNER JOIN ( tblPurchases INNER JOIN tblCustomers on tblPurchases.customerID = tblCustomer.customerID) ON tblStores.storeID = tblPurchases.storeID
WHERE (tblStores.Name = inputStoreName);
I recommend checking W3 schools. They are usually helpful for most programming tasks. If you provide more info about your database, we can provide more directed help.

Multi-level GROUP BY clause not allowed in subquery

I have a query as follows in MS Access
SELECT tblUsers.Forename, tblUsers.Surname,
(SELECT COUNT(ID)
FROM tblGrades
WHERE UserID = tblUsers.UserID
AND (Grade = 'A' OR Grade = 'B' OR Grade = 'C')) AS TotalGrades
FROM tblUsers
I've put this into a report and now when trying to view the report it displays an alert "Multi-level GROUP BY clause is not allowed in subquery"
What I dont get is I dont even have any GROUP BY clauses in the query so why is it returning this error?
From Allen Browne's excellent website of Access tips: Surviving Subqueries
Error: "Multi-level group by not allowed"
You spent half an hour building a query with subquery, and verifying it all works. You create a report based on the query, and immediately it fails. Why?
The problem arises from what Access does behind the scenes in response to the report's Sorting and Grouping or aggregation. If it must aggregate the data for the report, and that's the "multi-level" grouping that is not permitted.
Solutions
In report design, remove everything form the Sorting and Grouping dialog, and do not try to sum anything in the Report Header or Report Footer. (In most cases this is not a practical solution.)
In query design, uncheck the Show box under the subquery. (This solution is practical only if you do not need to show the results of the subquery in the report.)
Create a separate query that handles the subquery. Use this query as a source "table" for the query the report is based on. Moving the subquery to the lower level query sometimes (not always) avoids the problem, even if the second query is as simple as
SELECT * FROM Query1;
Use a domain aggregate function such as DSum() instead of a subquery. While this is fine for small tables, performance will be unusable for large ones.
If nothing else works, create a temporary table to hold the data for the report. You can convert your query into an Append query (Append on Query menu in query design) to populate the temporary table, and then base the report on the temporary table.
IMPORTANT NOTE: I'm reposting the info here because I believe Allen Browne explicitly allows it. From his website:
Permission
You may freely use anything (code, forms, algorithms, ...) from these articles and sample databases for any purpose (personal, educational, commercial, resale, ...). All we ask is that you acknowledge this website in your code, with comments such as:
'Source: http://allenbrowne.com
'Adapted from: http://allenbrowne.com
Try this version:
SELECT users.Forename, users.Surname, grades.TotalGrades
FROM tblUsers AS users
LEFT JOIN (SELECT COUNT(ID) as TotalGrades, UserID FROM tblGrades WHERE (Grade = 'A' OR Grade = 'B' OR Grade = 'C') group by userid) AS grades on grades.UserID = users.UserID
I have not tested it. The query itself should be OK, but I'm not sure whether it works in the report data source.
try this:
SELECT users.Forename, users.Surname, count(grades.id) AS TotalGrades
FROM tblUsers AS users
INNER JOIN tblGrades AS grades ON users.ID=grades.UserID
WHERE grades.Grade in ("A","B","C") group by users.ID;
This is a simple joined table. Basically it means. Select all cases where a user has a grade with "A" or "B" or "C" (which would give you a table like this:
user1 | A
user1 | B
user1 | A
user2 | A
...
And then it groups it by users, counting how many times a grade appeared -> giving you the number of grades in the desired range for each user.

mysql join question, joining newest record in a one to many relationship

I have a simple (hopefully) SQL question for you, any help would be much, much appreciated :).
I have two tables which I would like to join.
One Is Users, lets say it's called users
One is a kind of history of that user, lets say its called users_history.
The relationship of these two is a one users to many users_history relationship.
What I'd like to do is a query which joins the tables and joins the newest record in users_history onto each user.
Lets say the tables are like this, I'm simplifying for conciseness.
users
id
name
users_history
id
user_id
date
The date is formatted YYYYMMDD.
The end result is I'd like to be able to pull out all of the users who don't have a users_history record for today, for example today is 20101021.
Any help would be very gratefully received! :)
Try
SELECT MAX(users_history.date), users.name FROM users
LEFT JOIN users_history ON users.id = users_history.user_id
GROUP BY users_history.user_id
HAVING MAX(users_history.date) < CURDATE()
If you dont want users who doesnt have eny users_history records in the resultset, change the "LEFT JOIN" to a "JOIN"
If all you really want is finding the users without a user_history entry for today, you can use a subquery like so:
SELECT * FROM users WHERE NOT EXISTS (SELECT id FROM users_history WHERE user_id = users.id AND `date` = DATE(NOW()));
IMHO, this is more readable than a join and some filtering in your host language.
edit: Judging from your date format description, you probably use a varcharcolumn to store the date. In that case, replace DATE(NOW()) with the appropriate string representation for "today" - though I'd recommend changing the column type to a date/time type.
pull out all of the users who don't have a users_history record for today, for example today is 20101021.
select
u.*
from
users u
left outer join users_history uh on
u.id = uh.user_id and uh.history_date = curdate()
where
uh.user_id is null;

Compute Users average weight

I have two tables, Users and DoctorVisit
User
- UserID
- Name
DoctorsVisit
- UserID
- Weight
- Date
The doctorVisit table contains all the visits a particular user did to the doctor.
The user's weight is recorded per visit.
Query: Sum up all the Users weight, using the last doctor's visit's numbers. (then divide by number of users to get the average weight)
Note: some users may have not visited the doctor at all, while others may have visited many times.
I need the average weight of all users, but using the latest weight.
Update
I want the average weight across all users.
If I understand your question correctly, you should be able to get the average weight of all users based on their last visit from the following SQL statement. We use a subquery to get the last visit as a filter.
SELECT avg(uv.weight) FROM (SELECT weight FROM uservisit uv INNER JOIN
(SELECT userid, MAX(dateVisited) DateVisited FROM uservisit GROUP BY userid) us
ON us.UserID = uv.UserId and us.DateVisited = uv.DateVisited
I should point out that this does assume that there is a unique UserID that can be used to determine uniqueness. Also, if the DateVisited doesn't include a time but just a date, one patient who visits twice on the same day could skew the data.
This should get you the average weight per user if they have visited:
select user.name, temp.AvgWeight
from user left outer join (select userid, avg(weight)
from doctorsvisit
group by userid) temp
on user.userid = temp.userid
Write a query to select the most recent weight for each user (QueryA), and use that query as an inner select of a query to select the average (QueryB), e.g.,
SELECT AVG(weight) FROM (QueryA)
I think there's a mistake in your specs.
If you divide by all the users, your average will be too low. Each user that has no doctor visits will tend to drag the average towards zero. I don't believe that's what you want.
I'm too lazy to come up with an actual query, but it's going to be one of these things where you use a self join between the base table and a query with a group by that pulls out all the relevant Id, Visit Date pairs from the base table. The only thing you need the User table for is the Name.
We had a sample of the same problem in here a couple of weeks ago, I think. By the "same problem", I mean the problem where we want an attribute of the representative of a group, but where the attribute we want isn't included in the group by clause.
I think this will work, though I could be wrong:
Use an inner select to make sure you have the most recent visit, then use AVG. Your User table in this example is superfluous: since you have no weight data there and you don't care about user names, it doesn't do you any good to examine it.
SELECT AVG(dv.Weight)
FROM DoctorsVisit dv
WHERE dv.Date = (
SELECT MAX(Date)
FROM DoctorsVisit innerdv
WHERE innerdv.UserID = dv.UserID
)
If you're using SQL Server 2005 you don't need the sub query on the GROUP BY.
You can use the new ROW_NUMBER and PARTION BY functionality.
SELECT AVG(a.weight) FROM
(select
ROW_NUMBER() OVER(PARTITION BY dv.UserId ORDER BY Date desc) as ID,
dv.weight
from
DoctorsVisit dv) a
WHERE a.Id = 1
As someone else has mentioned though, this is the average weight across all the users who have VISITED the doctor. If you want the average weight across ALL of the users then anyone not visiting the doctor will give a misleading average.
Here's my stab at the solution:
select
avg(a.Weight) as AverageWeight
from
DoctorsVisit as a
innner join
(select
UserID,
max (Date) as LatestDate
from
DoctorsVisit
group by
UserID) as b
on a.UserID = b.UserID and a.Date = b.LatestDate;
Note that the User table isn't used at all.
This average omits entirely users who have no doctors visits at all, or whose weight is recorded as NULL in their latest doctors visit. This average is skewed if any users have more than one visit on the same date, and if the latest date is one of those date where the user got wighed more than once.