Sql-Data purging on the basis of datetime column in the table having 10+ million rows - sql-server-2012

I am working with SQL Server 2012, I have a table with approx 35 column and 10+ million rows. Now I want to do the data purging on the basis of datetime stamp and other various filter.
The sample data is as below
ID DateTimeStamp value1 value2 value3 .... Value 35
-------------------------------------------------------------------------
2 2016-07-26 15:12:41 0.00 126.20 328051.07
2 2016-07-26 15:14:41 0.00 126.20 328051.07
2 2016-07-26 15:18:17 0.00 126.14 328052.32
2 2016-07-26 15:23:17 0.00 126.75 328054.40
2 2016-07-26 15:24:34 0.00 126.75 328054.40
2 2016-07-26 15:25:18 0.00 126.75 328054.40
2 2016-07-26 15:28:15 0.00 126.95 328060.64
2 2016-07-26 15:29:15 0.00 126.95 328060.64
2 2016-07-26 15:30:15 0.00 126.95 328060.64
2 2016-07-26 15:34:15 0.00 126.95 328060.64
I want to do the data purging on the basis of time interval, Let’s say if I select the time interval of 5 minutes my expected result set should be as below
ID DateTimeStamp value1 value2 value3 .... Value 35
-----------------------------------------------------------------------
2 2016-07-26 15:12:41 0.00 126.20 328051.07
2 2016-07-26 15:18:17 0.00 126.14 328052.32
2 2016-07-26 15:23:17 0.00 126.75 328054.40
2 2016-07-26 15:28:15 0.00 126.95 328060.64
2 2016-07-26 15:34:15 0.00 126.95 328060.64
It should happen in such way that if the required datetime stamp is not exist the most closest value (Previous or next, whichever is most closest should be considered. )
Though I have achieved it with below logic (pseudo code), but it's extremely slow
While(1)
begin
StartDate = Start date of data purging at first iteration latter on assign it to EndDate in all next iteration
EndDate = EndDate + Interval
NextEndDate = EndDate + Interval
Set maxDateTime = Select top(1) *
from <TableName>
where dateTime between StartDate to End Date
order by datetime asc
Set minDateTime = Select top(1) *
from <TableName>
where dateTime between EndDate to End NextEndDate
order by datetime desc
Now compare difference and choose the one which is smaller.
Diff(maxDateTime, EndDateTime) & Diff (minDateTime, EndDateTime)
end
Can anyone suggest the efficient approach for the above logic

Below is an example that deletes all but the first row within each 5-minute interval. This method uses a loop for each interval to improve concurrency and avoid filling the transaction log, although it could be done as a single set-based operation using a tally table (or CTE) to calculate intervals if those are not concerns for you.
It is important to have an index (ideally clustered) with DateTimeStamp as the leftmost key column to improve performance.
CREATE TABLE dbo.TableName(
ID int NOT NULL
, DateTimeStamp datetime2(0) NOT NULL
, value1 decimal(18,2) NOT NULL
, value2 decimal(18,2) NOT NULL
, value3 decimal(18,2) NOT NULL
)
GO
INSERT INTO dbo.TableName VALUES
(2, '2016-07-26 15:12:41', 0.00, 126.20, 328051.07)
,(2, '2016-07-26 15:14:41', 0.00, 126.20, 328051.07)
,(2, '2016-07-26 15:18:17', 0.00, 126.14, 328052.32)
,(2, '2016-07-26 15:23:17', 0.00, 126.75, 328054.40)
,(2, '2016-07-26 15:24:34', 0.00, 126.75, 328054.40)
,(2, '2016-07-26 15:25:18', 0.00, 126.75, 328054.40)
,(2, '2016-07-26 15:28:15', 0.00, 126.95, 328060.64)
,(2, '2016-07-26 15:29:15', 0.00, 126.95, 328060.64)
,(2, '2016-07-26 15:30:15', 0.00, 126.95, 328060.64)
,(2, '2016-07-26 15:34:15', 0.00, 126.95, 328060.64);
GO
CREATE CLUSTERED INDEX cdx ON dbo.TableName(DateTimeStamp);
GO
SET NOCOUNT ON;
DECLARE
#StartDateTimeStamp datetime2(0)
, #LastDateTimeStamp datetime2(0)
, #EndDateTimeStamp datetime2(0)
, #IntervalSeconds int = 300;
SET #StartDateTimeStamp = (SELECT MIN(DateTimeStamp) FROM dbo.TableName);
SET #LastDateTimeStamp = (SELECT MAX(DateTimeStamp) FROM dbo.TableName);
WHILE #StartDateTimeStamp <= #LastDateTimeStamp
BEGIN
SET #EndDateTimeStamp = DATEADD(second, #IntervalSeconds, #StartDateTimeStamp);
WITH rows_to_delete AS (
SELECT ROW_NUMBER() OVER(ORDER BY DateTimeStamp) AS row_num
FROM dbo.TableName
WHERE
DateTimeStamp >= #StartDateTimeStamp
AND DateTimeStamp < #EndDateTimeStamp
)
DELETE rows_to_delete
WHERE row_num > 1;
SET #StartDateTimeStamp = DATEADD(second, #IntervalSeconds, #StartDateTimeStamp);
END;
GO

Related

Monthly Actual Cost vs Monthly Contract Amount

I have a project that pulls cost per category (labor, equipment, indirect), per month for a job and then shows a running, cumulative total of the contract amount per month. (This calculation is based on the total contract amount divided by the number of months in a project. Then the second month is the first month + second month, third month is first month + second month + third month, etc.)
I have the query shown below. When I run this, it returns the data shown under current results. What I need is the running total column populated even when there are no costs as shown under expected results. How do I accomplish this?
Current results:
fiscalMonth
Labor
Equipment
Indirect
RunningTotal
ContractPerMonth
2021-12-01
0.00
0.00
0.00
0.00
0.00
2022-01-01
6518.78
0.00
0.00
2141444.44
2141444.44
2022-02-01
8563.68
0.00
58.81
4282888.88
2141444.44
2022-03-01
7271.28
429.14
139167.21
6424333.32
2141444.44
2022-04-01
44538.32
2117.64
59379.53
8565777.76
2141444.44
2022-05-01
-14932.44
2476.85
1279972.38
10707222.20
2141444.44
2022-06-01
3701.65
250.00
992.45
12848666.64
2141444.44
2022-07-01
0.00
0.00
0.00
0.00
0.00
2022-08-01
0.00
0.00
0.00
0.00
0.00
Expected results:
fiscalMonth
Labor
Equipment
Indirect
RunningTotal
ContractPerMonth
2021-12-01
0.00
0.00
0.00
2141444.44
0.00
2022-01-01
6518.78
0.00
0.00
4282888.88
2141444.44
2022-02-01
8563.68
0.00
58.81
6424333.32
2141444.44
2022-03-01
7271.28
429.14
139167.21
8565777.76
2141444.44
2022-04-01
44538.32
2117.64
59379.53
10707222.20
2141444.44
2022-05-01
-14932.44
2476.85
1279972.38
12848666.64
2141444.44
2022-06-01
3701.65
250.00
992.45
14990111.08
2141444.44
2022-07-01
0.00
0.00
0.00
17131555.52
2141444.44
2022-08-01
0.00
0.00
0.00
19272999.96
0.00
Create Table #costs(fiscalMonth date, Labor numeric(12,2), Equipment numeric(12,2), Indirect numeric(12,2), RunningTotal numeric(12,2), ContractPerMonth numeric(12,2))
Declare #startDate as date, #endDate as date, #lastMonth as date,#count int
select #startDate = StartMonth, #endDate = ProjCloseDate from JCCM
WHERE
ltrim(rtrim(Contract)) = (#Job)
insert into #costs
SELECT
Mth
,isnull(Sum(LaborCost),0) as LaborCost
,Isnull(Sum(EquipmentCost),0) as EquipmentCost
,isnull(Sum(IndirectCost),0) as IndirectCost
,SUM (ContractAmtPerMonth) OVER (ORDER BY Mth) AS RunningTotal
,ContractAmtPerMonth
FROM(
SELECT
cp.Mth
,CASE WHEN ct.JBCostTypeCategory = 'L' THEN SUM(cp.ActualCost) END as LaborCost
,CASE WHEN ct.JBCostTypeCategory = 'E' THEN SUM(cp.ActualCost) END as EquipmentCost
,CASE WHEN ct.JBCostTypeCategory = 'O' THEN SUM(cp.ActualCost) END as IndirectCost
,(Select CASE WHEN Sum(cm.ContractAmt) <> 0 THEN CAST(SUM(cm.ContractAmt / ((DATEDIFF(Month,cm.StartMonth,cm.ProjCloseDate)+1))) as numeric(12,2)) END from JCCM cm WHERE cm.JCCo = jm.JCCo and cm.Contract = jm.Contract) as ContractAmtPerMonth
FROM
JCCP cp
LEFT JOIN JCCT ct ON cp.PhaseGroup = ct.PhaseGroup AND cp.CostType = ct.CostType
LEFT JOIN JCJM jm ON cp.JCCo = jm.JCCo and cp.Job = jm.Job
WHERE
cp.JCCo IN (#Company)
AND ltrim(rtrim(cp.Job)) = (#Job)
AND ct.JBCostTypeCategory IN ('L','E','O')
GROUP BY
jm.JCCo
,jm.Job
,jm.Contract
,cp.Mth
,ct.JBCostTypeCategory
)cost
GROUP BY
Mth
,ContractAmtPerMonth
WHILE (#startDate <= #endDate)
BEGIN
print CAST(#startDate AS VARCHAR(10)) + ' ' + CAST(#endDate AS VARCHAR(10))
select #count = Count (*) from #costs
print #count
if Not exists(select 1 from #costs where fiscalMonth = #startDate)
begin
insert into #costs (fiscalMonth, Labor, Equipment, Indirect,RunningTotal, ContractPerMonth ) values (#startDate,0,0,0,0,0)
end
set #startDate = DATEADD(month, 1, #startDate);
END
select * from #costs order by fiscalMonth
Drop table #costs
I was actually able to figure out how to accomplish what I needed. I modified how I created my table (changed table name from #costs to #months). This pulled the months, row number, and contract amount. I then joined it to my existing cost query. In SSRS, I'm able to calculate the running total by multiplying the monthly contract amount by the row number. Seems to be working.
create table #months (JCCo numeric, Job varchar(10), StartDate date, EndDate date)
insert into #months
SELECT JCCo,Contract,StartMonth, ProjCloseDate FROM JCCM WHERE JCCo = (#Company) AND Contract = (#Job);
with Q1 as
(
select JCCo,Job,StartDate as Mth
from #months
union all
select q.JCCo,q.Job,DATEADD(m, 1, q.Mth)
from Q1 q
inner join #months t on t.Job = q.Job
where Mth <= (DATEADD(MONTH,-1,t.EndDate))
)
select ROW_NUMBER() OVER ( order by Q1.Job, Q1.Mth) as Row#, Q1.JCCo, Q1.Job, Q1.Mth as fiscalMonth, ISNULL(cd.LaborCost,0) as Labor, ISNULL(cd.EquipmentCost,0) as Equipment, ISNULL(cd.IndirectCost,0) as Indirect, CAST(cm.ContractAmt / ((DATEDIFF(Month,cm.StartMonth,cm.ProjCloseDate)+1)) as DECIMAL(12,2)) as MonthlyContract, cm.ContractAmt as TotalContract
from Q1

How to check the current row with next row and update the current row not using while loop and cursor

Is there any way other than using the cursor or while loop to check the current row with the next row and update the current row and do this through all rows in the data set?
For example, this is the table we have:
id date value
1 2020-09-01 00:00:00.000 0.00
2 2020-09-01 00:15:00.000 0.30
3 2020-09-01 00:30:00.000 0.00
4 2020-09-01 00:45:00.000 0.15
5 2020-09-01 01:00:00.000 0.20
6 2020-09-01 01:15:00.000 0.10
7 2020-09-01 01:30:00.000 0.10
8 2020-09-01 01:45:00.000 0.00
9 2020-09-01 02:00:00.000 0.00
declare #i int = 1, #new_value money = 0.3
while #i <= 10
begin
select #new_value = iif(value> (#new_value * 0.2) and value < #new_value,
value,
#new_value)
from table
where value >= 0.1
and id = #i + 1;
set #i = #i + 1
end
select #new_value -- Output will be 0.10
This while loop go through each row and update #new_value based on some conditions and then check with the next row.
I would like to see if there is any way not to use a loop or cursor and get the same result.
Here it is in recursive cte
declare #tbl table
(
id int,
[value] decimal(5,2)
)
insert into #tbl values
(1, 0.00),
(2, 0.30),
(3, 0.00),
(4, 0.15),
(5, 0.20),
(6, 0.10),
(7, 0.10),
(8, 0.00),
(9, 0.00);
declare #new_value decimal(5,2) = 0.3;
with rcte as
(
select id, value,
new_value = iif(value > (#new_value * 0.2)
and value < #new_value,
value,
new_value)
from #tbl
where id = 1
union all
select t.id, t.value,
new_value = iif(t.value > (r.new_value * 0.2)
and t.value < r.new_value,
t.value,
r.new_value)
from rcte r
inner join #tbl t on r.id = t.id - 1
)
select *
from rcte
You can use the LAG window function for this, along with MIN aggregation
SELECT MIN(t.value)
FROM (
SELECT *,
LAG(t.value, 1, 0.3) OVER (ORDER BY t.id) AS prevValue
FROM [table] AS t
) AS t
WHERE t.value > (t.prevValue * 0.2) AND value < prevValue;
SQL Fiddle
I strongly suggest you do not use money data type, instead use decimal

TSQL order by group for monthly reports

I have court clearance statistic to made, but i have some slight problem with my monthly.. it didt follow in order, and wish someone could help me fix it.. and is it possible to add total in my table?
DECLARE #StartDate As date = '03-28-2015',
#EndDate As date = '03-28-2015'
DECLARE #TEMP_DATES AS TABLE (FROM_DATE DATE, TO_DATE DATE)
INSERT INTO #TEMP_DATES VALUES(#StartDate, #EndDate)
DECLARE #TENP_MONTH_YEAR AS TABLE(MONTH_YEAR VARCHAR(20), [YEAR] INT, [MONTH] INT)
INSERT INTO #TENP_MONTH_YEAR
select FORMAT(D.Dates, 'MMMM-yy', 'en-US' ) AS MonthYear, YEAR(D.Dates), MONTH(D.Dates)
from #TEMP_DATES as T
inner join master..spt_values as N
on N.number between 0 and datediff(DAY, T.FROM_DATE, T.TO_DATE)
cross apply (select dateadd(DAY, N.number, T.FROM_DATE)) as D(Dates)
where N.type ='P'
GROUP BY FORMAT(D.Dates, 'MMMM-yy', 'en-US' ), YEAR(D.Dates), MONTH(D.Dates)
ORDER BY YEAR(D.Dates), MONTH(D.Dates)
DECLARE #NEWID AS UNIQUEIDENTIFIER = NEWID()
SELECT CT.RPT_CASE_CODE_GROUP, SUM(ISNULL(INCOMING_CASES, 0)) AS INCOMING_CASES, SUM(ISNULL(OUTGOING_CASES, 0)) AS OUTGOING_CASES,
ISNULL(CAST(SUM(NULLIF(CAST(ISNULL(OUTGOING_CASES, 0) AS DECIMAL),0.00))/SUM(NULLIF(CAST(ISNULL(INCOMING_CASES, 0) AS DECIMAL),0.00)) * 100 AS DECIMAL(18,2)),0) AS [CLEARANCE_RATE],
MONTH_YEAR
FROM #tempClearanceListCases tempCLC
RIGHT OUTER JOIN (SELECT CASE_TYPE_ID, MONTH_YEAR, [YEAR], [MONTH]
FROM (SELECT DISTINCT CASE_TYPE_ID FROM #tempClearanceListCases tempCLC ) A, #TENP_MONTH_YEAR tempMonthYear) B
ON B.CASE_TYPE_ID = tempCLC.CASE_TYPE_ID AND tempCLC.MONTHLY = B.MONTH_YEAR
INNER JOIN CaseType CT WITH (NOLOCK)
ON B.CASE_TYPE_ID = CT.CASE_TYPE_ID
WHERE ISNULL(COURT_LOCATION_ID, #NEWID) = ISNULL(#COURT_LOCATION_ID, ISNULL(COURT_LOCATION_ID, #NEWID))
GROUP BY CT.RPT_CASE_CODE_GROUP, [INTERVAL_MONTH], MONTH_YEAR
ORDER BY CT.RPT_CASE_CODE_GROUP
The result which is the monthly is not correct order:
RPT_CASE_CODE_GROUP | INCOMEING CASES | OUTGOING CASES | CLEARANCERATE | MONTHYEAR
BCY/CP 15 4 26.67 March-15
BCY/CP 15 0 0.00 February-15
BCY/CP 33 0 0.00 January-15
BCY/DP 0 0 0.00 February-15
BCY/DP 2 0 0.00 March-15
BCY/DP 1 0 0.00 January-15
The result atleast i want it to be :
RPT_CASE_CODE_GROUP | INCOMEING CASES | OUTGOING CASES | CLEARANCERATE | MONTHYEAR
BCY/CP 33 0 0.00 January-15
BCY/CP 15 0 0.00 February-15
BCY/CP 15 4 26.67 March-15
BCY/DP 1 0 0.00 January-15
BCY/DP 0 0 0.00 February-15
BCY/DP 2 0 0.00 March-15
The result i want :
RPT_CASE_CODE_GROUP | INCOMEING CASES | OUTGOING CASES | CLEARANCERATE | MONTHYEAR
BCY/CP 33 0 0.00 January-15
BCY/CP 15 0 0.00 February-15
BCY/CP 15 4 26.67 March-15
63 4 6.34 Overall
BCY/DP 1 0 0.00 January-15
BCY/DP 0 0 0.00 February-15
BCY/DP 2 0 0.00 March-15
3 0 0.00 Overall
DO i have to stick to my query or create grouping query? i already spend many hour on this, i feel hard to turn back, im fresh grad :( can any guru guide me?
if all your MONTHYEAR are following the sames patter monthname-xx you can use following statement on order:
ORDER BY
cast('20' + substring(MONTHYEAR, Charindex('-', MONTHYEAR) + 1, 2) + '-' + substring(MONTHYEAR, 1, 3) + '-01' AS date)
This looks like a job for the UNION clause. It seems like you should have this execution order for the results you want:
SELECT -- data you want from tables w/ all joins
WHERE RPT_CASE_CODE_GROUP = 'BCY/CP'
UNION ALL
SELECT '', SUM([INCOMING CASES]), SUM([OUTGOING CASES]), AVG([CLEARANCE RATE], 'Overall'
FROM -- source data
WHERE RPT_CASE_CODE_GROUP = 'BCY/CP'
UNION ALL
SELECT -- data you want from tables w/ all joins
WHERE RPT_CASE_CODE_GROUP = 'BCY/DP'
UNION ALL
SELECT '', SUM([INCOMING CASES]), SUM([OUTGOING CASES]), AVG([CLEARANCE RATE], 'Overall'
FROM -- source data
WHERE RPT_CASE_CODE_GROUP = 'BCY/CP'
Alternatively, if there are more RPT_CASE_CODE_GROUP values than the one presented, you can use a loop to capture information about all of them like this:
CREATE TABLE #rccg(ID INT IDENTITY(1,1), RPT_CASE_CODE_GROUP NVARCHAR(15))
INSERT INTO #rccg(RPT_CASE_CODE_GROUP)
SELECT DISTINCT RPT_CASE_CODE_GROUP FROM --data source
DECLARE #i INT = 1, #j INT = (SELECT MAX(ID) FROM #rccg), #rccg NVARCHAR(15)
DECLARE #results TABLE(rccg NVARCHAR(15), ic INT, oc INT, cr INT, my NVARCHAR(20))
WHILE #i < #j
BEGIN
SET #rccg = (SELECT RPT_CASE_CODE_GROUP FROM #rccg WHERE ID = #i)
INSERT INTO #results
SELECT -- data you want from tables w/ all joins
WHERE RPT_CASE_CODE_GROUP = #rccg
UNION ALL
SELECT '', SUM([INCOMING CASES]), SUM([OUTGOING CASES]), AVG([CLEARANCE RATE], 'Overall'
FROM -- source data
WHERE RPT_CASE_CODE_GROUP = #rccg
END
SELECT * FROM #rccg
DROP TABLE #rccg
I know I didn't use your specific code, because that would have taken up a huge amount of space, but I think you get the general idea. For each field you want the totals of for the time period, you use the SUM(column_name) aggregate function. You can get a pretty good explanation and examples here: http://www.techonthenet.com/sql/sum.php.
I hope this at least helps point you in the right direction.

An attempt to create a balance between debit and credit

Well, I'll go directly to the case that is presented to me when trying to make a book with Extract and MUST HAVE in continuous BALANCE.
I was really hanging in my consultation, and I can not find any solution for desired.
Thanked would in some small contribution to some of you.
I'm looking for something like this:
ACCDATE ACCOUNT DEBIT CREDIT BALANCE
2013-01-01 00:00:00 11200 0.00 1500.00 -1500.00
2013-01-01 00:00:00 11200 0.00 60.00 -1560.00
2013-01-01 00:00:00 11200 0.00 400.00 -1960.00
2013-01-01 00:00:00 11200 0.00 100.00 -2060.00
2013-01-01 00:00:00 11200 0.00 300.00 -2360.00
2013-01-01 00:00:00 11200 0.00 250.00 -2910.00
OR:
ACCDATE ACCOUNT DEBIT CREDIT BALANCE
2013-01-01 00:00:00 11200 1500.00 0 1500.00
2013-01-01 00:00:00 11200 0.00 60.00 1440.00
2013-01-01 00:00:00 11200 0.00 400.00 1040.00
2013-01-01 00:00:00 11200 0.00 40 1000.00
2013-01-01 00:00:00 11200 300 0 1300.00
2013-01-01 00:00:00 11200 0.00 250.00 1550.00
I really do not require account type filter it by this time, but specific.
The idea is that with my Query still does not give me that result.
They can buy creating a provisional or temporary table with the same shown below:
INSERT INTO Accounting (AccDate,DebitCredit,Account,Amount) VALUES ('20110101','D',11200,1500)
INSERT INTO Accounting (AccDate,DebitCredit,Account,Amount) VALUES ('20110101','C',11200,60)
INSERT INTO Accounting (AccDate,DebitCredit,Account,Amount) VALUES ('20110102','D',11200,400)
INSERT INTO Accounting (AccDate,DebitCredit,Account,Amount) VALUES ('20110102','C',11200,100)
INSERT INTO Accounting (AccDate,DebitCredit,Account,Amount) VALUES ('20110102','C',11200,300)
INSERT INTO Accounting (AccDate,DebitCredit,Account,Amount) VALUES ('20110102','C',11200,250)
WITH CTE_FIRST AS
(
SELECT ACCDATE,
ACCOUNT,
CASE WHEN DEBITCREDIT='D' THEN AMOUNT ELSE 0 END AS DEBIT,
CASE WHEN DEBITCREDIT='C' THEN AMOUNT ELSE 0 END AS CREDIT,
ROW_NUMBER()OVER(ORDER BY ACCOUNT,ACCDATE) RN
FROM ACCOUNTING
WHERE ACCDATE >='20130101'
)
,CTE_SECOND AS(
SELECT *,
ISNULL((SELECT TOP 1 DEBIT FROM CTE_FIRST B WHERE B.ACCOUNT=A.ACCOUNT AND B.RN<A.RN ORDER BY RN DESC),0) COL1,
ISNULL((SELECT TOP 1 CREDIT FROM CTE_FIRST B WHERE B.ACCOUNT=A.ACCOUNT AND B.RN<A.RN ORDER BY RN DESC),0) COL2
FROM CTE_FIRST A
)
SELECT ACCDATE,ACCOUNT,DEBIT,CREDIT,
CASE WHEN DEBIT=0 THEN 0-(CREDIT+COL2) ELSE DEBIT+COL1 END BALANCE
FROM CTE_SECOND
Something happens in the validation of sum or not it's taking so linear consulting ....
All of this inquiry, I tried to help me with material that I got on the web. But it gives me the total response.
In the end I got this solution, but it becomes very slow the process.
Is there a way to optimize it?
Very slow for real, and it does not work for high queries.
DECLARE #T TABLE( FECHA DATETIME, COMENTARIO NVARCHAR (300), CUENTA
VARCHAR(15), DEBE NUMERIC(15,2), HABER NUMERIC(15,2) )
INSERT INTO #T SELECT FECHA, COMENTARIO, CUENTA, DEBE, HABER FROM
DIARIOAPUNTES;
/* INSERT INTO #T VALUES ('001-0001','20130102',100,0); INSERT INTO #T
VALUES ('001-0001','20130102',0,200); INSERT INTO #T VALUES
('001-0001','20130102',100,0); INSERT INTO #T VALUES
('001-0001','20130103',100,0); INSERT INTO #T VALUES
('001-0001','20130105',0,100); INSERT INTO #T VALUES
('001-0002','20130105',100,0); INSERT INTO #T VALUES
('001-0002','20130106',500,0);
*/
--DEBIT - CREDIT + BALANCE
WITH T_ROW AS (
SELECT (ROW_NUMBER() OVER(ORDER BY (T1_1.FECHA) ASC)) AS CONTADOR, FECHA, T1_1.CUENTA, T1_1.COMENTARIO, T1_1.DEBE, T1_1.HABER
FROM #T T1_1 )
SELECT T1.CONTADOR, T1.CUENTA, T1.COMENTARIO AS DESCRIPCION,
Convert(CHAR(10), T1.FECHA, 103) AS FECHA, T1.DEBE, T1.HABER,
ROUND(T1.DEBE-T1.HABER + COALESCE(T2.SALDO,0),2) AS SALDO FROM T_ROW
T1
CROSS APPLY(
SELECT ROUND(SUM(DEBE)-SUM(HABER),2) AS SALDO
FROM T_ROW T2
WHERE T2.CONTADOR < T1.CONTADOR AND T1.CUENTA = T2.CUENTA
) AS T2
--WHERE T1.FECHA BETWEEN '20130101' AND '20131231'
ORDER BY T1.CUENTA, T1.FECHA
--WHERE T1.ACCOUNTNO = '001-0001'

Impossible Task On Sql Calculation Where Date Is Equal

**
LOOK AT MY ANSWER WHICH IS REFERE AS NEW QUESTION ON SAME PROBLEM.
**
I have Confusion against utilize If,Else Statement against calculation of stock By date. And sort the same by date.
There is real challenge to calculate running total between equal date:
If date is equal
If date is greater than
If date is less than
My Table Schema Is:
TransID int, Auto Increment
Date datetime,
Inwards decimal(12,2)
Outward decimal(12,2)
Suppose If I have Records as Below:
TransID Date(DD/MM/YYYY) Inward Outward
1 03/02/2011 100
2 12/04/2010 200
3 03/02/2011 400
Than Result Should be:
TransID Date(DD/MM/YYYY) Inward Outward Balance
2 12/04/2010 200 -200
1 03/02/2011 100 -300
3 03/02/2011 400 100
I wants to calculate Inward - outwards = Balance and Balance count as running total as above. but the condition that it should be as per date order by Ascending
How to sort and calculate it by date and transID?
What is transact SQL IN SQL_SERVER-2000**?.
You can use a brute O(n2) approach of self-joining the table to itself, or if the table is large, it is better to iteratively calculate the balance. The choices for SQL Server 2000 are limited, but the approach I will show uses a loop that traverses the table in date, transid order rather than using cursors.
Here is a sample table for discussion
create table trans (transid int identity, date datetime, inwards decimal(12,2), outward decimal(12,2))
insert trans select '20110203', null, 100
insert trans select '20100412', null, 200
insert trans select '20110203', 400, null -- !same date as first
This is the T-SQL batch that will give you the output you require. If you merely wanted to update a balance column in the table (if it had such an extra column), change all references to #trans to the table itself.
-- fill a temp table with the new column required
select *, cast(null as decimal(12,2)) as balance
into #trans
from trans
-- create an index to aid performance
create clustered index #cix_trans on #trans(date, transid)
-- set up a loop to go through all record in the temp table
-- in preference to using CURSORs
declare #date datetime, #id int, #balance decimal(12,2)
select top 1 #date = date, #id = transid, #balance = 0
from #trans
order by date, transid
while ##ROWCOUNT > 0 begin
update #trans set #balance = balance = #balance + coalesce(inwards, -outward)
where transid = #id
-- next record
select top 1 #date = date, #id = transid
from #trans
where (date = #date and transid > #id)
or (date > #date)
order by date, transid
end
-- show the output
select *
from #trans
order by date, transid
;
-- clean up
drop table #trans;
Output
2 2010-04-12 00:00:00.000 NULL 200.00 -200.00
1 2011-02-03 00:00:00.000 NULL 100.00 -300.00
3 2011-02-03 00:00:00.000 400.00 NULL 100.00
EDIT
If you need to show the final output using the date formatted to dd/mm/yyyy, use this
-- show the output
select transid, convert(char(10), date, 103) date, inwards, outward, balance
from #trans
order by #trans.date, transid
;
Is Balance (Inward-Outward) ?
select TransID,
Date,
Inward,
Outward,
(select sum(Inward - Outward)
from tbl_name b1
where b1.TransID <= b.TransID) as RunB
from tbl_name b
order by Date desc,TransID desc
This would order by Date in descending order - if the dates are same they are ordered by TransID
Edit:
Assume a Transaction table as this
select * from Transactions
1 NULL 100.00 2010-01-01 00:00:00.000
2 NULL 200.00 2010-01-02 00:00:00.000
3 400.00 NULL 2010-01-03 00:00:00.000
4 50.00 NULL 2010-01-03 00:00:00.000
5 NULL 100.00 2010-01-04 00:00:00.000
If you do this query ie, sort by TransactionIDs you would get this!
select TransID,
Date,
isNull(Inward,0.0),
isNull(Outward,0.0),
(select sum(isNull(Inward,0.0) - isNull(Outward,0.0))
from Transactions b1
where b1.TransID <= b.TransID) as RunB
from Transactions b
order by Date asc,TransID asc
1 2010-01-01 00:00:00.000 0.00 100.00 -100.00
2 2010-01-02 00:00:00.000 0.00 200.00 -300.00
3 2010-01-03 00:00:00.000 400.00 0.00 100.00
4 2010-01-03 00:00:00.000 50.00 0.00 150.00
5 2010-01-04 00:00:00.000 0.00 100.00 50.00
Instead if you use this query - sort by date you would get this? Is this what you meant Mahesh?
select TransID,
Date,
isNull(Inward,0.0),
isNull(Outward,0.0),
(select sum(isNull(Inward,0.0) - isNull(Outward,0.0))
from Transactions b1
where b1.Date <= b.Date) as RunB
from Transactions b
order by Date asc,TransID asc
1 2010-01-01 00:00:00.000 0.00 100.00 -100.00
2 2010-01-02 00:00:00.000 0.00 200.00 -300.00
3 2010-01-03 00:00:00.000 400.00 0.00 150.00
4 2010-01-03 00:00:00.000 50.00 0.00 150.00
5 2010-01-04 00:00:00.000 0.00 100.00 50.00
The difference in queries being -> (b1.Date <= b.Date) and (b1.TransID <= b.TransID)
Take this first bit of cyberkiwi's solution:
select *, cast(null as decimal(12,2)) as balance
into #trans
from stock
and change it so the nvarchar dates from your table are converted to datetime values. That is, expand the * into the actual set of columns, replacing the date column with the converting expression.
Given the structure you've shown in your original question, it may look like this:
select
TransID,
convert(datetime, substring(Date,7,4) + substring(Date,4,2) + substring(Date,1,2)) as Date,
Inward,
Outward,
cast(null as decimal(12,2)) as balance
into #trans
from stock
Leave the rest of the script untouched.
Now this is Solution with date in format dd/MM/yyyy of above question.
select *, cast(null as decimal(12,2)) as balance
into #trans
from stock
-- create an index to aid performance
create clustered index #cix_trans on #trans(date, transid)
--set up a loop to go through all record in the temp table
-- in preference to using CURSORs
declare #date datetime, #id int, #balance decimal(12,2)
select top 1 #date = date, #id = transid, #balance = 0
from #trans
order by date, transid
while ##ROWCOUNT > 0 begin
update #trans set #balance = balance = #balance + coalesce(input, -output)
where transid = #id
-- next record
select top 1 #date = date, #id = transid
from #trans
where (date = #date and transid > #id)
or (date > #date)
order by date, transid
end
-- show the output
select
transID,
date= convert(varchar,convert(datetime,date,103),103),
input,
output,
balance
from #trans
order by convert(datetime,date,103), transID
-- clean up
drop table #trans;