Get all funds which has at least minimum data points - sql-server

I have two tables
1) Fund details
ID Symbol
-------------------
1 ABC
2 XYZ
2) Fund Price data
Fund_id date Price
-------------------------------------------
1 2014-07-01 00:00:00.000 25.25
1 2014-07-02 00:00:00.000 25.45
......
2 2014-07-01 00:00:00.000 75.25
2 2014-07-02 00:00:00.000 75.42
.......
Now what I want to achieve is:
Here I am fetching the monthly data of a particular Fund as below:
SELECT YEAR(date) [Year], MONTH(date) [Month],
DATENAME(MONTH,date) [Month Name], COUNT(1) [Sales Count], F.Symbol
FROM FundData FD inner join FundDetails F on F.ID = FD.Fund_ID
where F.Symbol = 'ABC'
GROUP BY YEAR(date), MONTH(date), DATENAME(MONTH, date), F.Symbol
Output:
Year Month Month Name Sales Count Symbol
-------------------------------------------
2014 4 April 21 ABC
2014 5 May 21 ABC
2014 6 June 21 ABC
2014 7 July 3 ABC
.......
Total Rows: 301
So here this is only for only particular fund which has returned 301 rows.
Now I want to get all the funds from the Fund details table which has rows less than given count ex 216 which I will pass as a parameter

Use Following query:
Declare #YourParameter int = 10
SELECT YEAR(date) [Year],
MONTH(date) [Month],
DATENAME(MONTH,date) [Month Name],
COUNT(1) [Sales Count],
F.Symbol
FROM FundData FD
INNER JOIN FundDetails F on FD.ID = F.Fund_ID
Where FD.ID IN (SELECT z.Fund_ID
FROM FundDetails z
WHERE z.Fund_ID=FD.ID
GROUP BY z.Fund_ID, YEAR(z.date), MONTH(z.date)
HAVING COUNT(*) <= #YourParameter
)
GROUP BY YEAR(date), MONTH(date), DATENAME(MONTH, date), F.Symbol

I have fixed it:
Declare #YourParameter int = 110
WITH CTE AS
(
SELECT YEAR(date) [Year], MONTH(date) [Month],
DATENAME(MONTH,date) [Month Name], COUNT(1) [Sales Count], F.Symbol
FROM FundData FD inner join FundDetails F on F.ID = FD.Fund_ID
where F.ID
IN (SELECT z.ID FROM FundDetails z)
GROUP BY F.Symbol, YEAR(date), MONTH(date), DATENAME(MONTH, date)
)
SELECT Symbol, COUNT(*) as cnt FROM CTE
GROUP BY Symbol
having COUNT(*) >= #YourParameter

Related

Get the no of records in table group by year

Consider the following data set.
table name : TBL_EMPLOYEE
EMP_NUMBER EMP_JOIN_DATE
001 2014-02-08
002 2014-03-15
003 2014-05-20
004 2015-05-24
005 2015-10-24
006 2017-01-30
007 2017-12-06
I need to get no. of joined employees in last 10 years as follows
required result
year (no of joined employees count)
2018 0
2017 2
2016 0
2015 2
2014 3
I have tried bellow sql.
SELECT top 10 DATEPART(yyyy, EMP_JOIN_DATE) AS RESIGN_YEAR,COUNT(EMP_NUMBER)AS COUNTT
FROM TBL_EMPLOYEE
WHERE DATEPART(yyyy, EMP_JOIN_DATE) <= 2018
GROUP BY DATEPART(yyyy, EMP_JOIN_DATE)
ORDER BY EMP_JOIN_DATE DESC
But it returns following result
year (no of joined employees count)
2017 2
2015 2
2014 3
#Scrat, you can use a numbers table or a SQL numbers table function as given in the referred document
Then you can use this table as the main table in FROM clause as follows
select * from dbo.NumbersTable(2008,2018,1)
Then you can simply LEFT JOIN your tables and development and join these two over years
;with cte as (
SELECT top 10 DATEPART(yyyy, EMP_JOIN_DATE) AS RESIGN_YEAR,COUNT(EMP_NUMBER)AS COUNTT
FROM TBL_EMPLOYEE
WHERE DATEPART(yyyy, EMP_JOIN_DATE) <= 2018
GROUP BY DATEPART(yyyy, EMP_JOIN_DATE)
)
select *
from dbo.NumbersTable(2008,2018,1) nt
left join cte on nt.i = cte.RESIGN_YEAR
ORDER BY EMP_JOIN_DATE DESC
Try the following query :
WITH yearlist AS
(
SELECT (DATEPART(Year,getdate())-10) as year
UNION all
SELECT yl.year + 1 as year
FROM yearlist yl
WHERE yl.year + 1 <= YEAR(GetDate())
)
SELECT Y.year ,ISNULL(A.[No of Employees],0) [No of Employees]
FROM yearlist Y
LEFT JOIN
(
SELECT YEAR(EMP_JOIN_DATE) [Year],Count(YEAR(EMP_JOIN_DATE)) [No of Employees]
FROM TBL_EMPLOYEE
WHERE DATEDIFF(YEAR,EMP_JOIN_DATE,GETDATE()) < 10
GROUP BY YEAR(EMP_JOIN_DATE)
) A ON A.Year = Y.year
ORDER BY Y.year DESC;
Hope it works!!
I have done it in another way.. Try this
SELECT #min_year = min(EMP_JOIN_DATE)
,#max_year = max(EMP_JOIN_DATE)
FROM #TBL_EMPLOYEE;
WITH CTE
AS (
SELECT datepart(year, #min_year) AS yr
UNION ALL
SELECT yr + 1
FROM CTE
WHERE yr <= datepart(year, #max_year)
)
SELECT TOP 10 yr AS RESIGN_YEAR
,COUNT(EMP_NUMBER) AS COUNTT
FROM CTE
LEFT JOIN #TBL_EMPLOYEE ON year(EMP_JOIN_DATE) = yr
WHERE yr <= 2018
GROUP BY yr
ORDER BY yr ASC
try This
DECLARE #Strt INT=2007,#End INT = 2017
;WITH YR
AS
(
SELECT
MyYear = #Strt
UNION ALL
SELECT
MyYear = MyYear+1
FROM YR
WHERE MyYear < #End
)
SELECT
YR.MyYear,
JoinCnt = COUNT(EMP.EMP_NUMBER)
FROM YR
LEFT JOIN Tbl_EmploYee EMP
ON YEAR(EMP.EMP_JOIN_DATE) = YR.MyYear
GROUP BY YR.MyYear

How to get number of employees per year

I have a table called Mst_Employee. The fields are:
Emp_No | Emp_Name | Emp_JoiningDate | Emp_ResignedDate | Emp_Status
How do I get the No. of Employees by year for each year somebody joined or resigned? (Joined and Resigned includes by year)
E.g. result should look like this:
Year No. of Employees.
------------------------
2011 125
2012 130
2013 100
One way to solve it is with a recursive cte and group by:
DECLARE #FromYear int, #ToYear int
SELECT #FromYear = YEAR(MIN(Emp_JoiningDate)),
#ToYear = YEAR(GETDATE())
FROM Mst_Employee
;WITH CTE AS
(
SELECT #FromYear As TheYear
UNION ALL
SELECT TheYear + 1
FROM CTE
WHERE TheYear < #ToYear
)
SELECT TheYear as [Year],
COUNT
(
CASE WHEN TheYear <= YEAR(COALESCE(Emp_ResignedDate, GETDATE())) THEN
1
END
) As [No. of Employees.]
FROM CTE
INNER JOIN Mst_Employee ON(TheYear >= YEAR(Emp_JoiningDate))
GROUP BY TheYear
See fiddle here
You can achieve this with:
select y as [Year], count(*) as [No. of Employees.]
from(select Emp_No, YEAR(Emp_JoiningDate) as y from Mst_Employee
union
select Emp_No, YEAR(Emp_ResignedDate) from Mst_Employee
where Emp_ResignedDate is not null)t
group by y

Get month wise records of payments for last six months

Table Structure:
Invoice
Invoice Payment
Current Query:
;WITH cte (clientid, invoiceid, paid, disc)
As
(
Select client_id clientId, vinvoice_Id invoiceId, sum(amount_received) paid, sum(discount) disc
From tbl_Vendor_Invoice_Payment
Group by vinvoice_id, client_id
)
Select I.date, I.total_price, Isnull(paid, 0) Paid, (Total_price - Isnull(paid,0) - Isnull(disc,0)) Balance
From tbl_Vendor_invoice I Left join cte On I.client_id = cte.clientId
And I.vinvoice_id = cte.invoiceid
order by vinvoice_id desc
Output:
But my requirement is to get month-wise result of last six months as below:
Month total_price Paid Balance
--------------------------------------------
October 800.00 750.00 50.00
September 200.00 100.00 100.00
August 350.00 350.00 0.00
.........
Can anyone please help me to get this ?
SELECT DATEADD(month,DATEDIFF(month,0,[vi.date]),0), SUM(vi.total_price) total_price, SUM(vip.amount_received) Paid, SUM(vip.balance) balance
FROM tbl_Vendor_Invoice vi
INNER JOIN tbl_Vendor_Invoice_Payment vip
on vi.vInvoice_Id = vip.vInvoice_Id
WHERE [vi.date] >= DATEADD(month, -6, DATEADD(month,DATEDIFF(month,0,[vi.date]),0))
GROUP BY DATEADD(month,DATEDIFF(month,0,[vi.date]),0)
This will group by the first day of the month, including the year. If you want just the month name, you can extract that using DATENAME(month, [date]).
I have found an answer:
;WITH cte (clientid, invoiceid, paid, disc)
As
(
Select client_id clientId, vinvoice_Id invoiceId, sum(amount_received) paid, sum(discount) disc
From tbl_Vendor_Invoice_Payment
Group by vinvoice_id, client_id
)
SELECT DATENAME(month, [date]) mMonth, SUM(Isnull(paid, 0)) Amount_Paid
FROM tbl_Vendor_Invoice vi
INNER JOIN cte vip on vi.vinvoice_Id = vip.invoiceid
WHERE [date] >= DATEADD(month, -6, DATEADD(month,DATEDIFF(month,0,getdate()),0))
GROUP BY DATENAME(month, [date]), MONTH([date])
ORDER BY MONTH([date])

how can i subtract the data from sql table

How can i subtract two columns based on AccountGroupId 4 - AccountGroupId 5
I have data like :
ID Month Year AccountGroupName AccountGroupId Balance
1 February 2014 Expense 5 200
2 February 2014 Income 4 300
3 March 2014 Expense 5 250
4 March 2014 Income 4 200
Desired Result :
ID Month Year AccountGroupName AccountGroupId Balance
1 February 2014 Income 4 100
2 March 2014 Expense 5 -50
Query :
IF OBJECT_ID('tempdb..#temptbale') IS NOT NULL DROP TABLE #temptbale
IF OBJECT_ID('tempdb..#subTable') IS NOT NULL DROP TABLE #subTable
SELECT
(DATENAME(Month,JD.CreatedDateTime)) as [Month],
DATEPART(yyyy ,JD.CreatedDateTime) as [Year],
AG.AccountGroupName,
AT.AccountGroupID,
Sum(A.OpeningBalance) as Balance
into #temptbale
FROM AccountGroup AG
INNER JOIN AccountType AT ON AG.AccountGroupID=AT.AccountGroupID
Right join Account A on A.AccountTypeID = AT.AccountTypeID
Inner join JournalMasterDetail JD on JD.AccountID = A.AccountID
where AG.AccountGroupID > 3 and year(JD.CreatedDateTime) = year(getdate())
and datepart(dy, JD.CreatedDateTime) <= datepart(dy, getdate())
group by
A.AccountName,
JD.CreatedDateTime,
AG.AccountGroupName,
A.OpeningBalance,
AT.AccountGroupID
select ROW_NUMBER() OVER(ORDER BY [Month]) AS 'ID',[Month],[Year],AccountGroupName,AccountGroupID,SUM(Balance)as Balance
into #subTable
from #temptbale
group by
[Month],
AccountGroupName,
AccountGroupID,
[Year]
order by
[Month]
select * from #subTable
You can run this query
select t.Month,t.Year
,Case when tblExp.Balance > tblIncome.Balance then tblExp.AccountGroupName else tblIncome.AccountGroupName end as AccountGroupName
,Case when tblExp.Balance > tblIncome.Balance then tblExp. AccountGroupId else tblIncome. AccountGroupId end as AccountGroupId
,tblIncome.Balance - tblExp.Balance as Balance
from table t
inner join(select * from table where AccountGroupId = 4) as tblExp on tblExp.year = t.year and tblexp.Month = t.Month
inner join(select * from table where AccountGroupId = 5) as tblIncome on tblIncome.year = t.year and tblIncome.Month = t.Month
group by t.Month,t.Year
It's joining the Month and year with two derived tables as Income and expense

how to fetch record monthly total in select query in sql server 2005

I am having following output of query
Query:
SELECT DATENAME(mm, date) [Month], sum(braekTime) [TotalBreakTime],
sum(DATEPART(hh,totalTime) * 60 + DATEPART(mi,totalTime) + DATEPART(ss,totalTime) * 0.017) [Minute],firstName
FROM employeeAttendance,employee
where FK_employeeId = employee.employeeId
GROUP BY DATENAME(mm, date),firstName
ORDER BY [Month]
but I want each n every month record with null/ 0 value
like June and July record is not available then it should display like following
Month TotalBreakTime Minute firstName
----- -------------- ------ ---------
January 0 0 NULL
February 0 0 NULL
March 0 0 NULL
April 0 0 NULL
May 50 1015.000 foramaa
June 0 0 NULL
July 0 0 NULL
.... Like till Dec
You should create a virtual table or subquery for the months, and left join it to the totals query.
eg
select * from
(
select number, datename(m,DATEADD(m, number-1, 0)) as monthname
from master..spt_values
where type='p' and number between 1 and 12
) months
left join
(your totals query) totals
on months.monthname = totals.month
try this:
;with cte as(
select 1 as rn union all select 2 union all select 3),
cte1 as (select ROW_NUMBER() over(order by c1.rn) as row_num
from cte cross join cte c1 cross join cte c2)
select * from cte1
left join
(SELECT DATENAME(mm, date) [Month],
sum(braekTime) [TotalBreakTime],
sum(DATEPART(hh,totalTime) * 60 + DATEPART(mi,totalTime) + DATEPART(ss,totalTime) * 0.017) [Minute],
firstName
FROM employeeAttendance join employee
on FK_employeeId = employee.employeeId
GROUP BY DATENAME(mm, date),firstName
ORDER BY [Month])B
on B.[Month]=DateName( month , DateAdd( month ,cte1.row_num , 0 ) - 1 )
and cte1.row_num <=12

Resources