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
Related
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
I have some sample data:
Date Status OfferNum Amount
------------------------------------------------------
2016/10/30 - 1 - 2000 - 1000,00
2016/08/25 - 0 - 2000 - 1100,00
2016/07/12 - 0 - 2001 - 1200,00
2016/08/30 - 0 - 2001 - 1300,00
2016/07/12 - 1 - 2002 - 1400,00
2016/08/30 - 1 - 2002 - 1500,00
2016/08/30 - 1 - 2003 - 1600,00
I don't want to count if one of offerNum status value has 1 and in the same quarter(if it has 1 but it isnt same quarter it has to be count). But I want to sum all of the amount(it isnt depends status column)
Here is the result that I want:
Quarter Count TotalAmount
----------------------------------------------------
2016/Q3 2 (offerNum 2002 and 2003) 8100,00
2016/Q4 1 (offerNum 2000) 1000,00
Here is the sqlfiddle : http://sqlfiddle.com/#!6/eac9d
You can use a subquery to compute the status of each offer, then compute the final result aggregated by quarter. Notice that the GROUP BY year is important, otherwise result will contain data coming from the same quarter of the previous years.
--
-- Answer updated according to SQL Fiddle.
-- Check: http://sqlfiddle.com/#!6/709ff/9
--
WITH offers AS
(
SELECT
CONCAT(DATEPART(yy, date), '/Q', DATEPART(qq, date)) AS Quarter,
offer,
MAX(status) AS status,
SUM(amount) AS TotalAmount
FROM temp
GROUP BY
DATEPART(yy, date),
DATEPART(qq, date),
offer
)
SELECT
Quarter,
SUM(status) AS Count,
SUM(TotalAmount) AS TotalAmount
FROM offers
GROUP BY Quarter
Are you locking for this:
SELECT
CONCAT(DATEPART(yy, [date]), '/Q', DATEPART(qq, [date])) AS Quarter,
COUNT(case [status] when 1 THEN 1 ELSE NULL END) AS [Count],
SUM([Amount]) AS TotalAmount
FROM [dbo].[temp]
group by DATEPART(yy, [date]), DATEPART(qq, [date])
You can query like this
;WITH cte
AS (SELECT
concat(YEAR(date), '/Q', DATEPART(q, date)) AS q,
amount,
SUM(status) OVER (PARTITION BY concat(YEAR(date), '/Q', DATEPART(q, date))) AS OfferStatusSum,
status
FROM temp)
SELECT
q, COUNT(DISTINCT status),
SUM(CASE WHEN OfferStatusSum >= 1 THEN amount
ELSE 0
END)
FROM cte
GROUP BY q
I'm trying to create a PIVOT TSQL statment that totals the products by date and state/province and provides the AVG Transit Time. Here is what I have so far:
select *
from (select createdate [Date Processed],
stateprovince as [Province],
count(*) as [Total],
avg(datediff(day,createdate,t.eventdate)) as [AVG Delivery],
product
from recipient C left outer join
(select delivid, product, eventdesc, eventdate, eventcode
from deliverystatus
where delivid in (select max(deliv_id)
from deliverystatus
where eventcode = 'DELIVERED'
group by product)) as t ON c.product = t.product
where account = 3519 and consol <>'' and trknum <> '' and C.createdate between '2/4/2016' and '2/4/2016'
group by C.createdate, c.stateprovince, c.product
) as Q
pivot (
count(product)
for [Province] in (NY, IL, GA)
) as PVT
My Result is:
Date Processed Total AVG Transit NY IL GA
2016-02-04 00:00:00.000 1 8 0 0 1
2016-02-04 00:00:00.000 1 11 2 4 1
2016-02-04 00:00:00.000 1 12 0 0 0
2016-02-04 00:00:00.000 1 15 0 0 0
I need the result to be:
Date Processed Total AVG Transit NY IL GA
2016-02-04 00:00:00.000 8 11.5 2 4 2
The ultimate goal is to have the AVG Transit listed by State/Province like this:
Date Processed Total Total AVG NY AVG IL AVG GA AVG
2016-02-04 00:00:00.000 8 11.5 2 8 4 11 2 15
Thanks in advance.
You need to add a GROUP BY clause after the pivot and either take the AVG SUM or MAX value for each output column:
select [Date Processed], SUM(NY+IL+GA) AS [Total], AVG([AVG Delivery]) AS [AVG Delivery], SUM(NY) AS NY, SUM(IL) AS IL, SUM(GA) AS GA
from (select createdate [Date Processed],
stateprovince as [Province],
count(*) as [Total],
avg(datediff(day,createdate,t.eventdate)) as [AVG Delivery],
product
from recipient C left outer join
(select delivid, product, eventdesc, eventdate, eventcode
from deliverystatus
where delivid in (select max(deliv_id)
from deliverystatus
where eventcode = 'DELIVERED'
group by product)) as t ON c.product = t.product
where account = 3519 and consol <>'' and trknum <> '' and C.createdate between '2/4/2016' and '2/4/2016'
group by C.createdate, c.stateprovince, c.product
) as Q
pivot (
count(product)
for [Province] in (NY, IL, GA)
) as PVT
group by [Date Processed]
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
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