Several MAX values based on another column value - sql

I'm trying to write a SQL query in MS ACCESS and I've narrowed it down to the table below, but can't seem to get the last thing right without making several extremely large querys.
Here's the strucuture of thetable I'm trying to query:
The results I want: MemberId and year where memberId had most visits in that year.(That is which memberId had most visits 2014, which had most visits 2015 etc..and I also want the relevant year to be shown in the result)
Thanks!

Sounds like you need to determine MAX(Visits) by year in a subquery, then JOIN to that:
SELECT a.*,b.Max_Visits
FROM YourTable a
JOIN (SELECT Year,MAX(Visits) AS Max_Visits
FROM YourTable
GROUP BY Year
) b
ON a.Year = b.Year
AND a.Visits = b.Max_Visits
If you want to see all members and not just those that had the most visits per year, you can change from JOIN to LEFT JOIN
If there's a tie, this returns both members.

Related

SQL How to pull in all records that don't contain

This is a bit of a trick question to explain, but I'll try my best.
The essence of the question is that I have a employee salary table and the columns are like so,: Employee ID, Month of Salary, Salary (Currency).
I want to run a select that will show me all of the employees that don't have a record for X month.
I have attached an image to assist in the visualising of this, and here is an example of what UI would want from this data:
Let's say from this small example that I want to see all of the employees that weren't paid on the 1st October 2021. From looking I know that employee 3 was the only one paid and 1 and 2 were not paid. How would I be able to query this on a much larger range of data without knowing which month it could be that they weren't paid?
You need to join your EmployeeSalary table against a list of expected EmployeeID/MonthOfSalary values, and determine the gaps - the instances where there is no matching record in the EmployeeSalary table. A LEFT OUTER JOIN can be used here, whenever there's no matching record / missing record in your EmployeeSalary table, the LEFT OUTER JOIN will give you NULL.
The following query shows how to perform the LEFT OUTER JOIN, however note that I've joined your table on itself to get the list of EmployeeID and MonthOfSalary values. You would be better to join these from other tables, i.e. I assume you have an Employee table with all the IDs in it, which would be more efficient (and more accurate) to use, than building the ID list from the EmployeeSalary table (like I've done).
SELECT EmployeeList.EmployeeID, MonthList.MonthOfSalary
FROM (SELECT DISTINCT MonthOfSalary FROM EmployeeSalary) MonthList
JOIN (SELECT DISTINCT EmployeeID FROM EmployeeSalary) EmployeeList
LEFT OUTER JOIN EmployeeSalary
ON MonthList.MonthOfSalary = EmployeeSalary.MonthOfSalary
AND EmployeeList.EmployeeID = EmployeeSalary.EmployeeID
WHERE EmployeeSalary.EmployeeID IS NULL
You need first to get the latest value, then to calculate the difference and make a filter on it. The filter can be done thanks to having clause.
I propose you the following starting point, that you might need to adapt, at least to cast some formats according to your column types.
with latest_pay as (
-- Filter to get, for each employee, the latest paid month
select Employee_ID, Month, Salary, max(month) as latest_pay_month
from your_table
group by Employee_ID
)
-- Look for employees not paid since more than 'your_treshold' months
select Employee_ID, latest_pay_month, Salary, datediff(latest_pay_month, getdate(), Month) as latest_paid_month_delay
from latest_pay
having datediff(latest_pay_month, getdate(), Month) > your_threshold
Btw, I know it's an example, but avoid using column names such as Month, which would lead to confusions and errors with SQL keywords
This is ideally where you would use a calendar table - having one available is handy for tasks such as this where you need to find missing dates.
You can build one on the fly, I have done so in this example however you would normally have a permanant table to use.
In order to determin which rows are missing you need to generate a list of expected rows, an outer join to your actual data will then reveal the missing rows.
So here we have a CTE that generates a list of dates (based on a date range you can set), followed by another to give a list of all the EmployeeId values.
You expect each employeeId to have a row for each month, so we do a cross join to generate the list of expected results, we then outer join with the actual data and filter to the null rows, these are the employees who have no been paid for that month.
See example DB<>Fiddle
declare #from date='20210101', #to date='20211001';
with dates as (
select DateAdd(month,n,#from) dt from (
select top(100) Row_Number() over(order by (select null))-1 n from master.dbo.spt_values
)v
), e as (select distinct employeeId from t)
select dt, e.EmployeeId
from dates d cross join e
left join t on DatePart(month,d.dt)=DatePart(month,t.PaidDate) and t.EmployeeId=e.EmployeeId
where d.dt<=#to
and t.EmployeeId is null

Count transactions within a month only once

I have a situations like below:
I have two database tables. The first table, which I will call TB1 contains all the salaries that the client credits & also the date when the transaction is made.
The second table, which I will call TB2, contains all the products the client has in the bank.
My purpose is to find the number of salaries the client has got before the date he/she got a product (OVERDRAFT in my case) in our bank.
Till now, everything works fine and I have made the query to extract the necessary data.
The only problem, is that I need to improve the query. So, if a certain client has got more than 1 salary (for example every 15 days) within the same month of the same year, the salary is counted only once.
How can I do that PLEASE?
The query is like below:
SELECT TB1.customer_id, COUNT(TB1.customer_id)
FROM table_1 TB1
JOIN
( SELECT TB2.CUSTOMER_ID, TB2.OD_START_DATE
FROM table_2 TB2
JOIN table_2 TB2_MAX
ON TB2.CUSTOMER_ID = TB2_MAX.CUSTOMER_ID
HAVING TB2.od_start_date = MAX(TB2.od_start_date)
GROUP BY TB2.customer_id, TB2.od_start_date
) TB2
ON TB1.CUSTOMER_ID = TB2.CUSTOMER_ID
WHERE TB1.DATE_FROM < TB2.OD_START_DATE
GROUP BY TB1.CUSTOMER_ID
PS: DATE_FROM field contains the date when the transaction is made, while OD_START_DATE field contains the date when the LATEST product is opened.
JOIN in your inner query is redundant. You simply need a MAX date for each customer.
In your outer query you should be counting the DATE_FROM, and not Customer_Id. Since you want to count only once for transactions in a month, Convert DATE_FROM to year month combination and use DISTINCT to count only once.
SELECT TB1.customer_id, COUNT(DISTINCT TO_CHAR(TB1.DATE_FROM,'YYYYMM'))
FROM table_1 TB1
JOIN
( SELECT CUSTOMER_ID, MAX(OD_START_DATE) AS OD_START_DATE
FROM table_2
GROUP BY customer_id
) TB2
ON TB1.CUSTOMER_ID = TB2.CUSTOMER_ID
WHERE TB1.DATE_FROM < TB2.OD_START_DATE
GROUP BY TB1.CUSTOMER_ID

Complex Aggregations in SQL

All I want to do is get a data set that shows me how many orders were placed and how many calls were made for each order. I also need the date of the calls and the date of the order, in the same table. The table is 10M+ rows, so aggregation of the result set is essential for analysis. The only analysis I want to do is the sum of calls/the total orders, and to be able to see how many support_tickets were generated from orders within an order range, up to a call_date. Very simple, but surprisingly complex to code up. Here is my attempt. I have also tried to change the below into a union, but still get wrong aggregate results.
-- The Query:-
SELECT
category_name
count(order_code)
order_date
sum(support_ticket_call)
call_date
FROM
(Select distinct name, order_code, order_date from table1) b
left join
(select count(call_ids), call_date FROM table2) b
on b.order_ID_code = a.order_id_code
group by category_name, order_date, call_date
Whenever there are no support_ticket_calls, the call_date is NULL, as you would expect. The count of orders is like 60,000 though, which is different from the usual 12 or so in the rest of the result set. I know something is wrong with this query, but It's driving me insane trying to solve it, literally all day so far.
It's a little difficult to answer this question without sample data and expected results, but the comment was getting too long.
You have several problems with your current query. First you need to join on the date fields by using on criteria. You also need to add group by to those queries that use aggregation. Finally, where does support_ticket_call come from? Can I presume it's the alias for the count(call_ids)?
Something like this should get you close:
SELECT
a.name as category_name,
count(a.order_code),
sum(b.support_ticket_call),
a.order_date as call_date
FROM
(Select distinct name, order_code, order_date
from table1) a
left join
(select count(call_ids) as support_ticket_call, call_date
from table2 group by call_date) b on a.order_date = b.call_date
group by a.name, a.order_date

How to include missing rows in sql return

I am currently trying to do a query like this:
(Psuedocode)
SELECT
NAME, SUM(VALUE), MONTH
FROM TABLE
WHERE MONTH BETWEEN 12 MONTHS AGO AND NOW
GROUP BY MONTH, NAME
The problem I am getting is that a name exists in a few of the months, but not all of the months, so if i filter this down to return the values for only one name, i sometimes get only 3 or 4 rows, rather than the 12 I expect to see.
My question is, is there a way to return rows, where it will still include the name, and month within the range, where the value would just be set to zero when I am missing the row from the previous result.
My first thought was to just union another select onto it, but I cant seem to get the logic to work to adhere to the group by, as well as the where clauses for limiting the names.
I you have data for all months, you can take the following approach. Generate all the rows (uses a cross join) then bring in the data you want:
select m.month, n.name, sum(t.value)
from (select distinct month from table) m cross join
(select distinct name from table) n left join
table t
on t.month = m.month and t.name = n.name
group by m.month, n.name;
This will return the missing sums as NULL values. If you want zero, then use coalesce(sum(t.value), 0).
you can use something like the following table to generate all the past 12 months as separate rows:
SELECT add_months(trunc(add_months(sysdate, -12), 'MONTH'), LEVEL - 1) AS month_in_range
FROM all_objects
CONNECT BY LEVEL <= 1 + months_between(add_months(sysdate, -12), TRUNC (sysdate, 'MONTH'));
and then do an outer join between you table and this.
I ended up implementing a left outer join similar to #paqogomez 's comment. As my team is already maintaining a time table, its very easy to get the month list for an outer join.
SELECT NAME, SUM(VALUE), TIME.MONTH
FROM (SELECT DISTINCT MONTH FROM TIME_TABLE
WHERE MONTH BETWEEN 12 MONTHS AGO AND NOW) TIME
LEFT OUTER JOIN TABLE ON (TIME.MONTH = TABLE.MONTH)
GROUP BY TIME.MONTH, NAME

SELECT a variable as condition and display another one

My problem is the following.
I want to SELECT the minimum of a years list and display another row of my table.
An example:
SELECT MIN(Year)
FROM table -> Searching for the lowest year.
and then I want it to display the Winners of the first year.
Is there a way to do this in just one line?
select winner from table where year in (select min(year) from table)
You need to do a self-JOIN between table and itself (I suppose you want to do it in a single statement, not a single line):
SELECT A.*
FROM table AS A
JOIN ( SELECT MIN(Year) AS Year FROM table ) AS B
ON (A.Year = B.Year);
This assumes that there is only one record per minimum-year in every group of interest.
Try it
select t.columntoshow, min(t.year) from table t group by t.columntoshow