I’m working with 2 tables, t_funds and t_psg2_nav.
In the t_funds table, the relevant columns are fundnum and br_cd
In t_psg2_nav, the relevant columns are calcdate, return_active_daily, and fundnum
Basically I need a query that sums the return_active_daily per fund for the most recent month. I think I need to use a JOIN clause, but that’s a little stetch for me right now. Here’s what I have… the t_funds table i'm using is only for switching between fundnum and br_cd (a name)... its easier for me that way.
SELECT funds.br_cd AS 'Fund Ticker'
, Month(nav.calcdate) AS 'Month'
, SUM(nav.return_active_daily) AS 'MTD Tracking'
FROM dbo.t_psg2_nav AS nav
, t_funds AS funds
INNER JOIN (SELECT fundnum
,month(max(calcdate)) AS calcdate
FROM dbo.t_psg2_nav
GROUP BY fundnum
) AS nav1
ON nav.fundnum = nav1.fundnum
AND nav.calcdate = nav1.calcdate
WHERE funds.fundnum = nav.fundnum
AND funds.fund_type LIKE 'ETF'
Append this to the end of your SQL:
HAVING Month=Month(NOW())
or, equivalently;
HAVING Month=Month(SYSDATE())
(edited)
To show only records from f.ex. March (month #3):
HAVING Month=3
Related
I cannot figure out how to create a sub-query to select only the latest date of the grouped by value sys_loc_code. Two tables E and R joined on sys_sample_code. I want to to the distinct value for the sys_loc_code field. I want this to be the data from the row that contains the latest date in it's sample_date field.
The code I have so far is:
SELECT E.sample_date, E.sys_loc_code, R.sys_sample_code, R.chemical_name, R.result_value, R.detect, R.LabSampType
FROM GMP.GMP_Sample_Results AS R
INNER JOIN GMP.GMP_Sample_Events AS E ON R.sys_sample_code = E.sys_sample_code
WHERE (R.chemical_name = N'Tetrachloroethene') and E.sample_date > '2016-01-01 00:00:00.000'
ORDER BY sys_loc_code, sample_date desc
Please see image for desired results. Desired results are in yellow.
I have tried MAX, DISTINCT, multiple joins, MAX DISTINCT, GROUP BY and countless others. Can someone please suggest the code I need to get the results I desire. Many thanks.
If you use ROW_NUMBER and PARTITION BY the column you want to be unique and ORDER BY the column you want the most recent of, and then take only those results where the row number is 1, you should get what you want.
SELECT sample_date, sys_loc_code, sys_sample_code, chemical_name, result_value, detect, LabSampType
FROM (
SELECT E.sample_date, E.sys_loc_code, R.sys_sample_code, R.chemical_name, R.result_value, R.detect, R.LabSampType
, ROW_NUMBER() OVER (PARTITION BY E.sys_loc_code ORDER BY sample_date DESC) RN
FROM GMP.GMP_Sample_Results AS R
INNER JOIN GMP.GMP_Sample_Events AS E ON R.sys_sample_code = E.sys_sample_code
WHERE (R.chemical_name = N'Tetrachloroethene') AND E.sample_date > '2016-01-01 00:00:00.000'
) X
WHERE RN = 1
ORDER BY sys_loc_code, sample_date DESC;
This is the code I used to get the results I wanted.
SELECT R.*, E.sample_date
FROM GMP.GMP_Sample_Results AS R
INNER JOIN GMP.GMP_Sample_Events AS E ON R.sys_sample_code = E.sys_sample_code
INNER JOIN (
SELECT sys_loc_code, MAX(sample_date) AS MAX_DATE
FROM GMP.GMP_Sample_Events
GROUP BY sys_loc_code
) AS MD ON E.sys_loc_code = MD.sys_loc_code AND E.sample_date = MD.MAX_DATE
WHERE (R.chemical_name = 'Tetrachloroethene') AND (E.sample_date > '2016-01-01-00:00:00.000')
ORDER BY E.sys_loc_code
I am intrigued by the TOP 1 and PARTITION solutions also, if anyone would care to explain how I can successfully get these to work. There is always more than 1 way to skin a cat. As a beginner, the more tools I have in my memory box the better I will be at my job. Thanks to all that have helped so far. #Dale K , if you can find a solution to the errors in the comments section, I will mark your's as answered as well.
I have a table that returns all Balance and cumulative amounts for each account, year/month period and each company. Please see image here
Here is my issue. There are YearMonth entries in which I have no transactions at all, so for those accounts I have no records.
But since I am showing cumulative amounts, I have to display all accounts at all YearMonth periods.
I created a separate Account table in which I have the all the Accounts to force (through left join) the first table to retrieve all Accounts at a given year/ month, but it does not work.
Can someone suggest any workaround? Any ideas?
Thank you.
Hard code the list of all years and months and left join with your existing table:
with ym as(
select * from (values ('201401'), ('201402'), ('201403'), ('201404'), ('201405'), ('201406'), ('201407'), ('201408'), ('201409'), ('201410'), ('201411'), ('201412'),
('201501'), ('201502'), ('201503'), ('201504'), ('201505'), ('201506'), ('201507'), ('201508'), ('201509'), ('201510'), ('201511'), ('201512'),
('201601'), ('201602'), ('201603'), ('201604'), ('201605'), ('201606'), ('201607'), ('201608'), ('201609'), ('201610'), ('201611'), ('201612'),
('201701'), ('201702'), ('201703'), ('201704'), ('201705'), ('201706'), ('201707'), ('201708'), ('201709'), ('201710'), ('201711'), ('201712'),
('201801'), ('201802'), ('201803'), ('201804'), ('201805'), ('201806'), ('201807'), ('201808'), ('201809'), ('201810'), ('201811'), ('201812'),
('201901'), ('201902'), ('201903'), ('201904'), ('201905'), ('201906'), ('201907'), ('201908'), ('201909'), ('201910'), ('201911'), ('201912')) a(YearMonth))
select ym.YearMonth, at.AccountNumber, mt.*
from ym
cross join [Accounts Table] at
left join [My query of transactions with YearMonth and Accounts] mt on mt.YearMonth = ym.YearMonth and mt.AccuntNumber = mt.AccountNumber
First question here so please excuse any mistakes...
I am trying to write a SQL Query for an SSRS report and I am totally confused when it comes to my joins.
Background: I have 3 tables that are relevant
Publishers - This is essentially a list of people
Publisher Reports - This is a list of records (related to the Publisher table) that details the work they have completed in a month period.
Report Months - This is a list of records (related to the Publisher Reports table) that relates to a specific month and year. On these records they have an indicator to show whether they relate to the previous six month period.
What i am trying to do is get a list of Publishers who have not submitted a publisher report that is related to a Report Month record within the last 6 months. My desired output is a list of Publishers in on column with the Report Month(s) that they are missing in the next column.
I am really struggling how to do it... I had thought of it as a three step process...
--STEP 1 - Get list of report months that are included in the last 6 months
WITH ACTIVE6MREPM AS
(
SELECT r.jajw_name,
r.jajw_CalendarDate
FROM jajw_reportmonthBase r
WHERE r.jajw_IncludedIn6MonthReport = '1'
),
--STEP 2 - Get list of all publishers
ACTIVEPUBS AS
(
SELECT c.FullName,
c.ContactId
FROM ContactBase c
WHERE c.statecode = '0'
AND c.jajw_CongregationAssignment != 640840001
AND c.jajw_CongregationAssignment != 640840006
AND c.jajw_CongregationAssignment != 640840005
--AND q.jajw_FieldServiceGroups = (#Field_Service_Group)
),
--STEP 3 - Get List of Publisher Reports for the selected Report Months
RELEVANTREPORTS AS
(
SELECT r.jajw_reportId AS Publisher_Report_GUID,
r.jajw_PublisherId AS Publisher_GUID,
r.jajw_ReportMonthId AS ReportMonth_GUID,
m.jajw_name AS ReportMonth_Name
FROM jajw_reportBase r
INNER JOIN jajw_reportmonthBase m ON r.jajw_ReportMonthId = m.jajw_reportmonthId
WHERE r.jajw_ReportPeriod6Month = '1'
ORDER BY m.jajw_CalendarDate
After these three, I want to create my list as described above and this is the bit that has me stumped! Any help would be greatly appreciated!
Thanks!
I think you can shorten your code a lot... here's a shot at it without having test data... be sure to read the comments and add in the join condition and check the where clause.
with cte as(
SELECT r.jajw_reportId AS Publisher_Report_GUID,
r.jajw_PublisherId AS Publisher_GUID,
r.jajw_ReportMonthId AS ReportMonth_GUID,
m.jajw_name AS ReportMonth_Name,
c.FullName,
c.ContactId
FROM jajw_reportBase r
INNER JOIN jajw_reportmonthBase m ON
r.jajw_ReportMonthId = m.jajw_reportmonthId
INNER JOIN ContactBase c on --what ever condition is appropiate
WHERE r.jajw_ReportPeriod6Month = '1'
and m.jajw_IncludedIn6MonthReport = '1' --maybe put this here, or does the above do the same thing?
ORDER BY m.jajw_CalendarDate)
select
p2.FullName,
p2.ReportMonth_Name
from cte p
right join(select distinct
ReportMonth_Name, FullName
from ContactBase
left join jajw_reportmonthBase on 1=1) p2 on p2.FullName = p.FullName and p2.ReportMonth_Name = p.ReportMonth_Name
where
ContactId in (select ContactId from cte group by ContactId having count(distinct ReportMonth_GUID) < 6)
and p.FullName is null
Here is an example using test data.
declare #pub table (pubname varchar(56), ReportMonthName varchar(16))
insert into #pub (pubname,ReportMonthName) values
('a','Jan'),
('a','Feb'),
('a','Mar'),
('a','Apr'),
--publisher a is missing May and Jun
('b','Jan'),
('b','Feb'),
('b','Mar'),
('b','Jun')
--publisher b is missing Apr and May
declare #dt table (ReportMonthName varchar(16))
insert into #dt (ReportMonthName) values
('Jan'),
('Feb'),
('Mar'),
('Apr'),
('May'),
('Jun')
select
p2.pubname
,p2.ReportMonthName
from #pub p
right join(
select distinct
p.pubname
,d.ReportMonthName
from #pub p
left join #dt d on 1=1)p2 on p2.pubname = p.pubname and p2.ReportMonthName = p.ReportMonthName where p.pubname is null
I have 3 tables that are joined together with this query.
One of them brings me people names , another one brings me their points and the last one brings me date time.
I select the total people score.
Also, there is a column in the 3th tables that brings me the scores' transaction Date Time. My problem is that I want to write a TSQL query with this condition:
Select the transaction date where the people score is 12,000 or more.
In my idea I should use while loop but I do not know the syntax?
This is how I would do it-
SELECT cp.FirstName
, cp.LastName
, SUM(Points) as Score
FROM ClubProfile cp
RIGHT JOIN CardTransaction ct
ON cp.ClubProfileId = ct.ClubProfileId
INNER JOIN Your3rdTable as t3
ON cp.ClubProfileId = t3.ClubProfileId
WHERE CONVERT(VARCHAR, ct.[Date Column], 101) = #your_date_param
GROUP BY
cp.FirstName
, cp.LastName
HAVING SUM(Points) >=12000
Based on your post this should be close to what you need. You need to add that 3rd table and alter this statement accordingly.
SELECT cp.FirstName
, cp.LastName
, SUM(Points) as Score
FROM [fidilio].[dbo].[ClubProfile] cp
RIGHT JOIN (
CardTransaction ct
INNER JOIN CardTransactionLog ctl
ON cp.CardTransactionLogId = ctl.CardTransactionLogId
)
ON cp.ClubProfileId = ct.ClubProfileId
GROUP BY
cp.FirstName
, cp.LastName
HAVING SUM(Points) >=12000
AND ctl.TransactionTimeStamp = #SomeDateTimeVariable
The variable #SomeDateTimeVariable has to come from someplace what is your exact time-frame criteria
Total EmpId in Database = 74.
Active Days for September 2013 in Databse = 22
I want to segregate the dates when the employee was not filled the production in MIS_Opus table.
Since FULL OUTER Join was not worked, I m using the except query. Through this query, I can get the unfilled dates for each employee by passing the empid thru c# function. For that loop will going to SQL & back to C# for 74 times. Please let me know how can I get the unfilled dates for all employees at one shot in SQL itself. I m using SQL 2012 and VS 2012 c#.
Thank you,
select _Date from MIS_BM_Calendar c
where c.Month = 'September 2013' and c.DayShiftStatus = 'active'
except
select _Date from MIS_Opus o
where o.EmpId=#Empid
One way is to build a list of all employee + day combinations using a cross join. Then you can use a left join to check if there is an employee entry for that day.
select days._Date as TheDay
, emps.EmpId as EmployeeWithMissingEntry
from (
select distinct _Date
from MIS_BM_Calendar
where Month = 'September 2013'
and DayShiftStatus = 'active'
) days
cross join -- One row for each combination of employee and date
(
select distinct EmpId
from MIS_Opus
) emps
left join
MIS_Opus o
on o._Date = days._Date
and o.EmpId = emps.EmpId
where o._Date is null -- Employee entry for day not found