How to view the Suggsetions sorted in the Database for the last three months? - sql

I am a New ASP.NET Developer and I am trying to develop a simple suggestion box system. I have the following part of my database desing:
User Table: Username, Name, DivisionCode... etc
Division Table: SapCode, Division
SuggestionLog Table: ID, Title, Description, submittedDate, Username
(The first attribute is the primary key in each table and the attribute (submittedDate) is of DateTime data type)
Now, I need to develop a table that shows suggestions for the last three months. I already developed a query that shows the Employee Name, Username, Division, Suggestion Title, Suggestion Description. All what I want now is to show the Month. For example, to show the suggestions for the last three months, the Month column should show: Jan-2012, Dec-2011, Nov-2011 So how to do that?
My current SQL query:
SELECT dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsType.Type, dbo.SafetySuggestionsLog.Username,
dbo.employee.Name, dbo.Divisions.DivisionShortcut
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID
The desired output is to display:
Employee Name, Username, Division, SuggestionTitle, SuggstionDescription, SuggestionType Month(submissionDate)

I reformatted you query so it would fit on the page without scrolling.
Hopefully this provides what you need. It uses DATENAME to get the month and year parts from the current date and DATEPART to do the "three months ago" calculation.
Note that DATEPART doesn't behave as you might expect - it counts the number of period-end boundaries (in this case months) - hence the condition is
...WHERE DATEDIFF(month,SafetySuggestionsLog.submittedDate,getdate()) < 3
because the last three months have two month-end boundaries between them.
I also added an ORDER BY clause.
SELECT dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description,
dbo.SafetySuggestionsType.Type,
dbo.SafetySuggestionsLog.Username,
dbo.employee.Name,
dbo.Divisions.DivisionShortcut,
left(datename(month,SafetySuggestionsLog.submittedDate),3)
+ '-'
+ datename(year,SafetySuggestionsLog.submittedDate) AS SubmittedMonth
FROM dbo.Divisions
INNER JOIN dbo.employee
ON dbo.Divisions.SapCode = dbo.employee.DivisionCode
INNER JOIN dbo.SafetySuggestionsLog
ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username
INNER JOIN dbo.SafetySuggestionsType
ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID
WHERE DATEDIFF(month,SafetySuggestionsLog.submittedDate,getdate()) < 3
ORDER BY SafetySuggestionsLog.submittedDate DESC
It might also be worth noting that you don't have to fully qualify the name of all the columns in the query - it's valid SQL to alias the input tables like so:
...INNER JOIN dbo.SafetySuggestionsLog AS log
You can then refer to column names by alias in the query - e.g.
log.Username
instead of
dbo.SafetySuggestionsLog.Username
which makes it a bit easier to read.

Related

How to show all employees absent dates only in MS Access 2010 query?

I want to have a query which shows me records of only those employees that were absent on various dates.
I have two queries in MS Access 2010. One is qAllDatesAllEmp which has all monthly dates for all employees. Second is qDailyWorkEmp which shows date-wise the working of employees. Now, say Emp1 had only one missing date of 5-Jan-2019; emp2 had 15-Jan-2019 missing and so on, the result should show me only these missing dates with employee names. What i have tried so far is that I have joined the date field from qAllDatesAllEmp to the date field in qDailyWorkEmp with join arrow pointing from qAllDatesAllEmp to qDailyWorkEmp. I also added the date field from qDailyWorkEmp to the query grid below but removed the check mark. When I run this query, it gives blank result. I would really welcome the experts' help on how to get the desired output below.
My Sample Data:
Query1: qAllDatesAllEmp contains {WorkDate; empID; empName; CityBased}
Query2: qDailyWorkEmp contains {DailyDate; empID; empName; CityBased}
The SQL for this is as follows:
SELECT qDailyWorkEmp.empID, qDailyWorkEmp.empName, qDailyWorkEmp.CityBased
FROM qAllDatesAllEmp LEFT JOIN
qDailyWorkEmp
ON qAllDatesAllEmp.WorkDate = qDailyWorkEmp.DailyDate
WHERE (((qDailyWorkEmp.DailyDate) Is Null));
My desired output:
empID; EmpName; MissingDate
001; ABC; 5-Jan-2019
007; LMN; 15-Jan-2019
...and so on
From what I can gather from your question, it seems like you are on the right track with your left join query, however, since your qAllDatesAllEmp query contains the master data, you should output the data from this query for records for which the corresponding values are null in your qDailyWorkEmp query.
You also appear to have a typo in your query on this line:
qAllDatesAllEmp.WhatDate = qDailyWorkEmp.DailyDate
As you have stated in your question that the query qAllDatesAllEmp contains the fields:
Query1: qAllDatesAllEmp contains {WorkDate; empID; empName; CityBased}
WhatDate is not one of these fields.
You will also need to join the empID field in both queries, so that you are comparing the date field on a per-employee basis, as opposed to comparing each date with the dates for all employees - hence your join criteria should be:
qAllDatesAllEmp LEFT JOIN qDailyWorkEmp ON
qAllDatesAllEmp.WorkDate = qDailyWorkEmp.DailyDate AND
qAllDatesAllEmp.empID = qDailyWorkEmp.empID
With the information provided, I might suggest the following:
SELECT
qAllDatesAllEmp.empID,
qAllDatesAllEmp.empName,
qAllDatesAllEmp.CityBased
qAllDatesAllEmp.WorkDate as MissingDate
FROM
qAllDatesAllEmp LEFT JOIN qDailyWorkEmp ON
qAllDatesAllEmp.WorkDate = qDailyWorkEmp.DailyDate AND
qAllDatesAllEmp.empID = qDailyWorkEmp.empID
WHERE
qDailyWorkEmp.DailyDate IS NULL

Include missing years in Group By query

I am fairly new in Access and SQL programming. I am trying to do the following:
Sum(SO_SalesOrderPaymentHistoryLineT.Amount) AS [Sum Of PaymentPerYear]
and group by year even when there is no amount in some of the years. I would like to have these years listed as well for a report with charts. I'm not certain if this is possible, but every bit of help is appreciated.
My code so far is as follows:
SELECT
Base_CustomerT.SalesRep,
SO_SalesOrderT.CustomerId,
Base_CustomerT.Customer,
SO_SalesOrderPaymentHistoryLineT.DatePaid,
Sum(SO_SalesOrderPaymentHistoryLineT.Amount) AS [Sum Of PaymentPerYear]
FROM
Base_CustomerT
INNER JOIN (
SO_SalesOrderPaymentHistoryLineT
INNER JOIN SO_SalesOrderT
ON SO_SalesOrderPaymentHistoryLineT.SalesOrderId = SO_SalesOrderT.SalesOrderId
) ON Base_CustomerT.CustomerId = SO_SalesOrderT.CustomerId
GROUP BY
Base_CustomerT.SalesRep,
SO_SalesOrderT.CustomerId,
Base_CustomerT.Customer,
SO_SalesOrderPaymentHistoryLineT.DatePaid,
SO_SalesOrderPaymentHistoryLineT.PaymentType,
Base_CustomerT.IsActive
HAVING
(((SO_SalesOrderPaymentHistoryLineT.PaymentType)=1)
AND ((Base_CustomerT.IsActive)=Yes))
ORDER BY
Base_CustomerT.SalesRep,
Base_CustomerT.Customer;
You need another table with all years listed -- you can create this on the fly or have one in the db... join from that. So if you had a table called alltheyears with a column called y that just listed the years then you could use code like this:
WITH minmax as
(
select min(year(SO_SalesOrderPaymentHistoryLineT.DatePaid) as minyear,
max(year(SO_SalesOrderPaymentHistoryLineT.DatePaid) as maxyear)
from SalesOrderPaymentHistoryLineT
), yearsused as
(
select y
from alltheyears, minmax
where alltheyears.y >= minyear and alltheyears.y <= maxyear
)
select *
from yearsused
join ( -- your query above goes here! -- ) T
ON year(T.SO_SalesOrderPaymentHistoryLineT.DatePaid) = yearsused.y
You need a data source that will provide the year numbers. You cannot manufacture them out of thin air. Supposing you had a table Interesting_year with a single column year, populated, say, with every distinct integer between 2000 and 2050, you could do something like this:
SELECT
base.SalesRep,
base.CustomerId,
base.Customer,
base.year,
Sum(NZ(data.Amount)) AS [Sum Of PaymentPerYear]
FROM
(SELECT * FROM Base_CustomerT INNER JOIN Year) AS base
LEFT JOIN
(SELECT * FROM
SO_SalesOrderT
INNER JOIN SO_SalesOrderPaymentHistoryLineT
ON (SO_SalesOrderPaymentHistoryLineT.SalesOrderId = SO_SalesOrderT.SalesOrderId)
) AS data
ON ((base.CustomerId = data.CustomerId)
AND (base.year = Year(data.DatePaid))),
WHERE
(data.PaymentType = 1)
AND (base.IsActive = Yes)
AND (base.year BETWEEN
(SELECT Min(year(DatePaid) FROM SO_SalesOrderPaymentHistoryLineT)
AND (SELECT Max(year(DatePaid) FROM SO_SalesOrderPaymentHistoryLineT))
GROUP BY
base.SalesRep,
base.CustomerId,
base.Customer,
base.year,
ORDER BY
base.SalesRep,
base.Customer;
Note the following:
The revised query first forms the Cartesian product of BaseCustomerT with Interesting_year in order to have base customer data associated with each year (this is sometimes called a CROSS JOIN, but it's the same thing as an INNER JOIN with no join predicate, which is what Access requires)
In order to have result rows for years with no payments, you must perform an outer join (in this case a LEFT JOIN). Where a (base customer, year) combination has no associated orders, the rest of the columns of the join result will be NULL.
I'm selecting the CustomerId from Base_CustomerT because you would sometimes get a NULL if you selected from SO_SalesOrderT as in the starting query
I'm using the Access Nz() function to convert NULL payment amounts to 0 (from rows corresponding to years with no payments)
I converted your HAVING clause to a WHERE clause. That's semantically equivalent in this particular case, and it will be more efficient because the WHERE filter is applied before groups are formed, and because it allows some columns to be omitted from the GROUP BY clause.
Following Hogan's example, I filter out data for years outside the overall range covered by your data. Alternatively, you could achieve the same effect without that filter condition and its subqueries by ensuring that table Intersting_year contains only the year numbers for which you want results.
Update: modified the query to a different, but logically equivalent "something like this" that I hope Access will like better. Aside from adding a bunch of parentheses, the main difference is making both the left and the right operand of the LEFT JOIN into a subquery. That's consistent with the consensus recommendation for resolving Access "ambiguous outer join" errors.
Thank you John for your help. I found a solution which works for me. It looks quiet different but I learned a lot out of it. If you are interested here is how it looks now.
SELECT DISTINCTROW
Base_Customer_RevenueYearQ.SalesRep,
Base_Customer_RevenueYearQ.CustomerId,
Base_Customer_RevenueYearQ.Customer,
Base_Customer_RevenueYearQ.RevenueYear,
CustomerPaymentPerYearQ.[Sum Of PaymentPerYear]
FROM
Base_Customer_RevenueYearQ
LEFT JOIN CustomerPaymentPerYearQ
ON (Base_Customer_RevenueYearQ.RevenueYear = CustomerPaymentPerYearQ.[RevenueYear])
AND (Base_Customer_RevenueYearQ.CustomerId = CustomerPaymentPerYearQ.CustomerId)
GROUP BY
Base_Customer_RevenueYearQ.SalesRep,
Base_Customer_RevenueYearQ.CustomerId,
Base_Customer_RevenueYearQ.Customer,
Base_Customer_RevenueYearQ.RevenueYear,
CustomerPaymentPerYearQ.[Sum Of PaymentPerYear]
;

Oracle SQL, Select and compare dates against null values

I need to select and compare the last advertised date in advert, to any null values in lease to get when an un-leased property and when it was last advertised. This is the code I have so far;
SELECT YR_LEASE.PROPERTYNUM,
MAX(YR_ADVERT.DATETO),
count(YR_LEASE.RENTERNUM)
FROM YR_LEASE
JOIN YR_ADVERT
ON YR_LEASE.PROPERTYNUM=YR_ADVERT.PROPERTYNUM
GROUP BY YR_LEASE.PROPERTYNUM
This returns a count this is far too high and I'm not sure what i'm doing wrong, here's my ERD to try and give this question some context;
http://www.gliffy.com/pubdoc/4239520/L.png
I think you need to first identify unleased properties. From there you can find the latest advert date. Assuming some properties have never been advertised you'll need to go via YR_PROPERTY and do a left join to include unadvertised properties.
SELECT NVL(TO_CHAR(MAX(YR_ADVERT.DATETO),'DD/MM/YYYY'),'NO LAST ADVERT DATE') LAST_ADVERT_DATE
,YR_PROPERTY.PROPERTYNUM
FROM YR_PROPERTY LEFT JOIN YR_ADVERT ON YR_PROPERTY.PROPERTYNUM = YR_ADVERT.PROPERTYNUM
WHERE NOT EXISTS (SELECT 1
FROM YR_LEASE
WHERE YR_LEASE.PROPERTYNUM = YR_PROPERTY.PROPERTYNUM
AND YR_LEASE.RENT_FINISH > SYSDATE)
GROUP BY YR_LEASE.PROPERTYNUM;

SQL SELECT query with JOIN, SUM and GROUP BY

I have 5 tables in a MS Access databse: tblMember, tblPoint, tblRace, tblRaceType and tblResult. (All of which have primary keys.)
tblPoint contains (RaceTypeID, Position, Points) fields.
What I want to do is look at all the races that the members participated in, see what position they came (stored in tblResult) and see if those positions score points (as defined in tblPoint). I then want to add up all the points for each member and show these, along with the member name in my query...
Is this possible? I came up with my best shot at this SQL query below:
SELECT Sum(tblPoint.Points) AS SumOfPoints, Count(tblRace.RaceID) AS CountOfRaceID,
tblMember.MemberName, tblPoint.Points
FROM ((tblRaceType INNER JOIN tblPoint ON tblRaceType.RaceTypeID = tblPoint.RaceTypeID)
INNER JOIN tblRace ON tblRaceType.RaceTypeID = tblRace.RaceTypeID) INNER JOIN
(tblMember INNER JOIN tblResult ON tblMember.MemberID = tblResult.MemberID) ON
tblRace.RaceID = tblResult.RaceID
GROUP BY tblMember.MemberName, tblPoint.Points
ORDER BY tblPoint.Points DESC;
Is anyone able to point me in the right direction at all?
I'd say this
GROUP BY tblMember.MemberName, tblPoint.Points
ORDER BY tblPoint.Points DESC;
should probably be more like this:
GROUP BY tblMember.MemberName
ORDER BY Sum(tblPoint.Points) DESC;
Also, remove tblPoint.Points at the end of your select. This is just a single point value, you want the sum.
Grouping by points means that you'll get one row per member and point value they scored - probably not what you intended.

choosing latest string when aggregating results in mysql

I've been tasked to do generate some reports on our Request Tracker usage. Request Tracker is a ticketing system we use for several departments were I work. To do this I'm taking a nightly snapshot of details about tickets altered for the day into another database. This approach decouples my reporting from the the internal database schema that RT uses.
Amongst many other questions for the report, I need to report how many tickets were resolved in each month per Department. In RT the department is stored as a CustomField, and my modelling follows that trend, as you can see in my query below. However due to how I'm grabbing snapshots each night, I have multiple rows for a ticket, and the Department field can change over the month. I'm only interested in the most recent Department field. I don't know how to get that in a query.
I know I can use 'GROUP BY' to reduce my query results down to one per ticket, but when I do that, I don't know how to grab the last Department setting. As the Departments are all strings, a MAX() doesnt't get the last one. MySQL doesn't require you to use an aggregating function for fields you're selecting, but the results are indeterminate (from my testing it looks like it might grab the first one on my version of MySQL).
To illustrate, here is the results from a query that shows me two tickets, and all it's Department field settings:
"ticket_num","date","QueueName","CF","CFValue","closed"
35750,"2009-09-22","IT_help","Department","",""
35750,"2009-09-23","IT_help","Department","",""
35750,"2009-09-24","IT_help","Department","",""
35750,"2009-09-25","IT_help","Department","",""
35750,"2009-09-26","IT_help","Department","",""
35750,"2009-10-02","IT_help","Department","",""
35750,"2009-10-03","IT_help","Department","",""
35750,"2009-10-12","IT_help","Department","",""
35750,"2009-10-13","IT_help","Department","",""
35750,"2009-10-26","IT_help","Department","Conference/Visitors","2009-10-26 10:10:32"
35750,"2009-10-27","IT_help","Department","Conference/Visitors","2009-10-26 10:10:32"
36354,"2009-10-20","IT_help","Department","",""
36354,"2009-10-21","IT_help","Department","",""
36354,"2009-10-22","IT_help","Department","FS Students",""
36354,"2009-10-23","IT_help","Department","FS Students",""
36354,"2009-10-26","IT_help","Department","FS Students","2009-10-26 12:23:00"
36354,"2009-10-27","IT_help","Department","FS Students","2009-10-26 12:23:00"
As we can see, both tickets were closed on the 26th, and both tickets had an empty Department field for a few days when they first showed up. I've included my query below, you can see that I've artificially limited the number of columns returned in the second half of the where statement:
SELECT d.ticket_num, d.date, q.name as QueueName, cf.name as CF, cfv.value as CFValue, d.closed
FROM daysCF dcf
INNER JOIN daily_snapshots d on dcf.day_id = d.id
INNER JOIN Queues q on d.queue_id = q.id
INNER JOIN CustomFieldValues cfv on dcf.cfv_id = cfv.id
INNER JOIN CustomFields cf on cf.id = cfv.field_id
WHERE cf.name = 'Department' and (d.ticket_num = 35750 or d.ticket_num = 36354)
ORDER by d.ticket_num, d.date
How can I modify that query so I get a result set that tells me that in October there was one ticket closed for "FS Students" and one ticket closed for "Conference/Visitors"?
This is the "greatest-n-per-group" problem that comes up frequently on Stack Overflow.
Here's how I'd solve it in your case:
SELECT d1.ticket_num, d1.date, q.name as QueueName,
cf.name as CF, cfv.value as CFValue, d1.closed
FROM daysCF dcf
INNER JOIN daily_snapshots d1 ON (dcf.day_id = d1.id)
INNER JOIN Queues q ON (d1.queue_id = q.id)
INNER JOIN CustomFieldValues cfv ON (dcf.cfv_id = cfv.id)
INNER JOIN CustomFields cf ON (cf.id = cfv.field_id)
LEFT OUTER JOIN daily_snapshots d2 ON (d1.ticket_num = d2.ticket_num AND d1.date < d2.date)
WHERE d2.id IS NULL AND cf.name = 'Department'
ORDER by d1.ticket_num, d1.date;
Mysql doesn't have a LAST operator, so you really need to do this using a temporary table.
CREATE TEMPORARY TABLE last_dates SELECT ticket_num, MAX(date) AS date
FROM daily_snapshots GROUP BY ticket_num
that gets you a table with the last date for each ticket. Then in your main query, join against this table with both the ticket_num and date fields. This will filter out all rows for which the date isn't the latest for the corresponding ticket number.
You might need an index on that temporary table, I'll leave that to you.