Transact SQL :: How To Get Cumulative Value In Query

Aug 18, 2015

I have table like below, its period wise ,here the value get cumulative period wise.

amtname period
10CHR201202
20TNG201202
10CHR201203
20TNG201203

View 3 Replies


ADVERTISEMENT

Transact SQL :: Cumulative Sum On Value Column

Apr 28, 2015

How would I iterate through this table and do a cumulative sum on the value column :

I'm trying to get the following result:

View 5 Replies View Related

Transact SQL :: Cumulative Totals - Rolling Window

Aug 14, 2015

I'm trying to generate a cumulative total with a rolling window of 13 time periods..Previously I was able to do left outer join to the same table 13 times to add the quantity field but it appears with the migration to SQL Server 2014, that many left outer joins is not possible (query that would run in 3 mins is taking well over 15 hours now)..

View 7 Replies View Related

Transact SQL :: Cumulative Values Quarter And Half Yearly Wise

Nov 23, 2015

Having table like below. Here want to cumulative the values quarter and half yearly wise...

declare @table table 
(month varchar(10),
value int)
insert into @table values('apr' ,100 )
insert into @table values('may' ,200 )
insert into @table values('jun' ,300 )

[Code] ....

Like wise the data should added...

View 3 Replies View Related

Query For Cumulative GPA Calculation

Oct 9, 2015

I have a table with the following creation sql script

CREATETABLE [dbo].[TEST_ENROLLMENT](
      [ENROLLMENT_ID] [int]
NOTNULL,
      [COURSE_OFFERING_ID] [int]
NOTNULL,
      [STUDENT_ID] [int]

[Code] ....

Below is the sql insert for the above table’s data

INSERTINTO TEST_ENROLLMENT(ENROLLMENT_ID,COURSE_OFFERING_ID,STUDENT_ID,DEPT_ID,COURSE_CODE,CREDIT,SECTION_ID,
SEMESTER,ACAD_LEVEL,ACAD_YEAR,DATE_ENROLLED,[STATUS],TOTAL_MARK,GRADE_LETTER,QPE,Honor,INSTRUCTOR_ID,USERNAME
)VALUES(877,356,104,15,'IRD

[Code] ...

I was trying to calculate GPA and Commulative GPA (CGPA) for this student and the formula of GPA is SUM(Honor)/SUM(CREDIT) and the formula of the CGPA is the Average of the SUM(Honor)/SUM(CREDIT) grouped by semester and I wrote the below query which is calculating the GPA correctly but wrongly calculating the CGPA.

How to get the correct CGPA shown in the below desired result set table.

select x.STUDENT_ID,AVG(x.gpa)as
GPA,AVG(y.gpa)AS'COMMULATIVE GPA'
from
(
select STUDENT_ID,SUM(Honor)/SUM(CREDIT)
gpa,ACAD_YEAR,SEMESTER

[Code] ....

Current result set (Incorrect CUMULATIVE GPA)

STUDENT_ID GPA CUMULATIVE GPA
104 2.9 2.9
104 2.25 2.25
104 3 3
 
Desired result set

STUDENT_ID GPA COMMUTATIVE GPA
104 2.9 2.9
104 2.25 2.575
104 3 2.716

View 5 Replies View Related

Query Regarding Cumulative Count And Graph

Mar 29, 2007

Can we calculate Cumulative Count using Runnning value function like it is in 2005 reporting services. If any other alternative please let me know.



Also I have few queries regarding graph.

Can we breakup graph if the scale is more than the certain range?

Can we adjust the scale/Range of the graph depending on the certain parameters from Dataset?



Thank you,



Regards,

Palak Shah

View 3 Replies View Related

SQL Server Admin 2014 :: Query To Get Cumulative Package

Feb 6, 2014

Query to get CU# of sql server Instance ?

View 3 Replies View Related

Transact SQL :: Adding Results Of Query To Another Query Via Dynamically Added Columns

Jul 30, 2015

For each customer, I want to add all of their telephone numbers to a different column. That is, multiple columns (depending on the number of telephone numbers) for each customer/row. How can I achieve that?

I want my output to be

CUSTOMER ID, FIRST NAME, LAST NAME, TEL1, TEL2, TEL3, ... etc

Each 'Tel' will relate to a one or more records in the PHONES table that is linked back to the customer.

I want to do it using SELECT. Is it possible?

View 13 Replies View Related

Transact SQL :: Use Query Results As Select Criteria For Another Query

Jul 10, 2015

I have a query that performs a comparison between 2 different databases and returns the results of the comparison. It returns 2 columns. The 1st column is the value of the object being compared, and the 2nd column is a number representing any discrepancies.What I would like to do is use the results from this 1st query in the where clause of another separate query so that this 2nd query will only run for any primary values from the 1st query where a secondary value in the 1st query is not equal to zero.I was thinking of using an "IN" function in the 2nd query to pull data from the 1st column in the 1st query where the 2nd column in the 1st query != 0, but I'm having trouble ironing out the correct syntax, and conceptualizing this optimally.

While I would prefer to only return values from the 1st query where the comparison value != 0 in order to have a concise list to work with, I am having difficulty in that the comparison value is a mathematical calculation of 2 different tables in 2 different databases, and so far I've been forced to include it in the select criteria because the where clause does not accept it.Also, I am not a DBA by trade. I am a system administrator writing SQL code for reporting data from an application I support.

View 6 Replies View Related

Transact SQL :: SELECT On Column Name From Query Result Set In Same Query?

May 9, 2015

I have a column colC in a table myTable that has a value (e.g. '0X'). The position of a non-zero character in column colC refers to the ordinal position of another column in the table myTable (in the aforementioned example, colB).

To get a column name (i.e., colA or colB) from table myTable, I can join ("ON cte.pos = cn.ORDINAL_POSITION") to INFORMATION_SCHEMA.COLUMNS for that table catalog, schema and name. But I want to show the value of what is in that column (e.g., 'ABC'), not just the name. Hoping for:

COLUMN_NAME Value
----------- -----
colB        123
colA        XYZ

I've tried dynamic SQL to no success, probably not executing the concept correctly...

Below is what I have:

CREATE TABLE myTable (colA VARCHAR(3), colB VARCHAR(3), colC VARCHAR(3))
INSERT INTO myTable (colA, colB, colC) VALUES ('ABC', '123', '0X')
INSERT INTO myTable (colA, colB, colC) VALUES ('XYZ', '789', 'X0')
;WITH cte AS
(
SELECT CAST(PATINDEX('%[^0]%', colC) AS SMALLINT) pos, STUFF(colC, 1, PATINDEX('%[^0]%', colC), '') colC

[Code] ....

View 4 Replies View Related

Transact SQL :: Query Plan Shows Table Not Even In Query?

Jul 22, 2015

I am trying to optimize a stored procedure in SQL 2008.  When I look at an actual execution plan generated from when I run it in SSMS it shows a table being used in the plan that has no relation to what is actually in the query script and this is where the biggest performance hit occurs.

I've never seen a table show up before that wasn't part of the query. why this might occur and how to correct it?  I can't just change the query script because the table in question isn't there.

View 10 Replies View Related

Cumulative Log

Sep 7, 2007

Is it possible to create a cumulative log using SSIS? basiclly I have 5 logs which hold failed records. I would like to create a cumulative log and send it via email using SSIS.
thoughts?

thanks

View 6 Replies View Related

Cumulative Sum(Urgent)

Apr 26, 2000

I'm trying to get the final result using an aggregate function.

Table looks like below;
ID ACRE Probability
1 3 0.3
2 1 0.6
3 6 0.2
4 5 0.5
5 2 0.1

First, I want to descend by probability then select all records that cumulative acre <= 8

So, final result will be:

ID ACRE Probability
2 1 0.6
4 5 0.5

Any idea how to write a script?

Thanks in advance,

Mike Jun
hyunhyo@hotmail.com
GIS reserch Group
University of Colorado
303-492-8781

View 1 Replies View Related

Cumulative Count

Oct 4, 2005

I have to group the no. of employees based on month. i.e

Jan 10 employees
Feb 20 employees
Mar 30 employess

The result is to be

Jan 10
Feb 20
Mar 60.

Kindly provide the sql for getting the above result.

Thanks,
Lakshmi

View 6 Replies View Related

Cumulative Weeks

Jul 20, 2005

SQL Server 2000 SP3Hi,How can I get the cumulative weeks from a givedate to the currentdate. I know I can get the weeknumber by using datepart(wk,getdate())but this will giveme the week number for this year. What if I want to know the number ofweeksthat have passed since june 1 2001. If I use datepart(wk,'20010106') Iwillget the week number for 2001 but I would like the number of weeksexpired between then now.Thanks,Reg

View 1 Replies View Related

Hierarchical Cumulative Sum

Aug 23, 2006

I have a table consisting of 3 columns: Parent varchar(50), Child varchar(50), Pop int.

The table is setup as follows:

Parent Child Pop
----------------------------------
Europe France 0
France Paris 1
New York New York City 10
North America United States 0
North America Canada 0
United States New York 0
United States Washington 0
Washington Redmond 200
Washington Seattle 100
World Europe 0
World North America 0

This is just some sample data modified a tiny bit from an example of a hierachical print out sample that is a stored procedure that allows me to pass any place and see all of that place's children/grandchildren.

I need to figure out how to write a query to show me cumulative sums (ROLLUP?) of the whole tree. So the output should basically be something like this (it can include parent and child columns too):

World Null 311
World Europe 1
Europe France 1
France Paris 1
World North America 310
North America United States 310
North America Canada 0
United States New York 10
United States Washington 300
New York New York City 10
Washington Redmond 200
Washington Seattle 100

Hopefully you understand what i'm looking for. I've tried using WITH ROLLUP and I also tried using an Inner Join but I'm not really sure what I need to do to pull this off. I seem to only be able to get it to work 1-2 levels deep but not through the whole tree.

Any help/ideas would be appreciated! Thank you.

View 13 Replies View Related

Finding Cumulative Sum

Dec 29, 2007

In the emp table :
>
> EMPNO ENAME SAL
> ==================
> 7369 SMITH 1000
> 7499 ALLEN 2000
> 7521 WARD 3000
> 7566 JONES 4000
> 7654 MARTIN 5000
>
> there is a requirement to have a calculated col.
> called cummulative sal
>
> EMPNO ENAME SAL CUMMULATIVE_SAL
> 7369 SMITH 1000 1000
> 7499 ALLEN 2000 3000
> 7521 WARD 3000 6000
> 7566 JONES 4000 10000
> 7654 MARTIN 5000 15000
>
>

How to show this calculated col. by using one select statement?
I could get the result using Empno. in my query as --
select ename,sal,(select sum(sal) from emp k where k.empno <= e.empno) as cum from emp e order by ename

but I was asked to get the same result if empno. col is not there?

SUCKS........... the below code is giving the result but I don't know how you could use operator (<) on two strings to compare......????
select ename,sal,(select sum(sal) from emp k where k.ename <= e.ename) as cum from emp e order by ename

Someone tell me if this is the right approach or is there a better way of getting the thing done.

View 4 Replies View Related

Saving Cumulative Data Or Something Like That :)

May 4, 2007

Hi,There are 3 tablesTable,TableDetails,TableDaily.With structureTABLE:TableID        UserID        Money----------        ----------        ----------(int)            (int)            (money)TABLEDETAILS:TableDetailsID    TableID        ItemID        PaidForItem    DayID----------               ----------        ----------        ----------           ----------(int)                   (int)             (int)            (money)         (int)TABLEDAILY:TableDailyID    TableID        PaidForItem    Money        Total                                 Change----------            ----------        ----------            ----------        ----------                              ----------(int)                (int)             (money)          (money)      (PaidForItem + Money)       (money)"Table"    holds id for user and his money amount, which changes during time. "TableDetails" holds data about items user bought, amount paid for them and dayid which relates to one particular day."TableDaily" holds history. I do not know how to update this table.I created job whish runs stored procedure. This procedure sums "PaidForItem" using group by TableID and WHERE DAYID = '11'.Problem is with Change column. This column sould hold difference between today's Total and previous one etc.Current procedure looks like this:INSERT INTO    TableDaily        (TableID, PaidForItem, Money, DayID)SELECT        TableDetails.TableID,                     SUM(PaidForItem) AS PaidForItem,                     Table.Money,                    (SELECT    DayID                    FROM    Days                    WHERE  (Aktive = 1)) AS DayIDFROM          TableDetails INNER JOIN                    Table ON TableDetails.TableID = Table.TableID GROUP BY    TableDetails.TableID, Table.Money

View 3 Replies View Related

Cumulative Counts With GROUP BY?

Jun 6, 2014

I have the following:

SELECT '201305' AS PAYPERIOD,
EMPLOYEE,
RIGHT ('000' + CAST (DEPT_ID AS VARCHAR(3)) ,3) AS DEPARTMENT,
COUNT (EMPCODE) AS BONUSCOUNT_YTD
FROM Table1
WHERE (YEAR = 2013 AND PERIOD < 2)
GROUP BY EMPCODE, YEAR, PERIOD, DEPT_ID

[Code] ...

How can I get the counts to be cumulative? In other words, if an employee appears in pay period 201305 that's 1, if they then appear in pay period 201306 that becomes 2.

View 4 Replies View Related

Cumulative Result Calculation

Jul 5, 2014

Is there any way to calculate Cumulative result.

Manpower|Count|Cum_Count|Formula
Apr|70|70|Sum(APR)
May|40|110|Sum(Apr+May)
Jun|110|220|Sum(Apr+May+Jun)

View 2 Replies View Related

How To Calculate Cumulative Of Months

Aug 2, 2014

How to calculate the cumulative of months.

Jan FebMar AprMay JunJul AugSep Oct Nov Dec
321 394571 577 617 692924 944956 1010 1308 1686

if i execute my query in this month(getdate) then it should sum from Jan to Aug Similarly i execute same query it should sum from Jan to Sept So on.

View 1 Replies View Related

Cumulative Update Package 2 For SP2

Jun 30, 2007

I tried to install "Cumulative update package 2 for SQL Server 2005 Service Pack 2"
Everything went well except for the "SQL Server Database Services" update.
It errored out as it was trying to "Finalize" the update.

Kicker to this whole thing is the database file "temp_MS_AgentSigningCertificate_database.mdf" does not even exist.

I could not see any references to it in the master database.
I checked the registry and I can find a couple of search references for it.
It apparently may have been a database that existed in the server at one time.

I am not sure if I should remove the registry references to the database.



Below is a part of the install summary where it has failed:
===========================================================
Product Installation Status
Product : SQL Server Database Services 2005 (MSSQLSERVER)
Product Version (Previous): 3050
Product Version (Final) :
Status : Failure
Log File : C:Program FilesMicrosoft SQL Server90Setup BootstrapLOGHotfixSQL9_Hotfix_KB936305_sqlrun_sql.msp.log
Error Number : 29537
Error Description : MSP Error: 29537 SQL Server Setup has encountered the following problem: [Microsoft][SQL Native Client][SQL Server]A file activation error occurred. The physical file name 'F:Data emp_MS_AgentSigningCertificate_database.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation.. To continue, correct the problem, and then run SQL Server Setup again.

If someone can tell me what I need to do to resolve this issue, I would greatly
appreciate it.

Thanks,
Larry :-(

Larry :-)

View 4 Replies View Related

Page Subtotals (Not Cumulative)

Jul 30, 2007

Hello,

I want to display subtotals for a column only for that page. Like;

Index Value
-----------------------------
1 4
2 5
Subtotal 9
----------------------------
3 1
4 2
Subtotal 3
Total 12


RunningValue gives cumulative totals. I need subtotals for each visible page only. Is there a way to do it ?
Constraints:
I'm using a table. And I shouldn't use page breaks on my report.

Thanks in advance

View 3 Replies View Related

Which Cumulative Update Package For Sp2

Jun 20, 2007

Hi

I have found two cumulative update packages available for sql 2005 sp2 - build 3161 (http://support.microsoft.com/kb/935356) and build 3175 (http://support.microsoft.com/kb/936305).



The fixes are supposed to be cumulative and include all fixes since the last service pack, but the list of hotfixes in each package is different.



Does build 3175 contain the fixes in build 3161? What about fixes mentioned in build 3175 that have version lowere than 3161 - are they included in build 3161?



Anthony

View 1 Replies View Related

How Can I Get The Cumulative Sum Of A Field In A Table

Aug 29, 2007

For Eg.

I have a table like gias given below:
Name Amount
------------------------------
aaa 10
bbb 20

and I want an output like one given below on running SQL query or stored procedure
Name Amount cumulative amount
---------------------------------------------------------------------
aaa 10 10
bbb 20 30

can anyone plz help me on this

View 28 Replies View Related

The Cumulative Hotfix Is Able To Roll Back??

Aug 23, 2006

Hi,
I'm planning to install the cumulative hotfix (build 2187) on my sql 2000 clustering server (SP4, 2040). And I would like to know if the cumulative hotfix is able to roll back. If possible, please provide me any information about that. Thanks in advance.

View 2 Replies View Related

Cumulative Related Records From Hierarchy

May 30, 2008

Morning chucky eggsThis is duplicated over at SQLTeam...except I've moved on a bit so my question to you is different:http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=103798SQL 2k5I have a standard hierarchy in an adjacency table modelling business units in an organisation. I have another table associating people with (one single) business unit. I need to return all the people in each business unit in a cumulative manner i.e. a unit will include all people assigned to that unit and assigned to all child units too.Below is1) Set up code (in red)2) Initial query that failed on last data load due to the nature of the data changing and me not considering the ramifications of my initial solution properly3) My new soulution.My question is - is there a better way to accomplish this? I don't rate my code that highly and could do with this being as efficient as possible as at present I can't see it scaling to larger and larger data volumes all that well.USE tempdbgo----------------------------------------------------------------- Set up the structure & data...---------------------------------------------------------------CREATE TABLE dbo.org ( unit_code VARCHAR(10) NOT NULL , parent_code VARCHAR(10) NULL , CONSTRAINT pk_org PRIMARY KEY CLUSTERED (unit_code) WITH (FILLFACTOR = 100) )GO CREATE TABLE dbo.org_peeps ( unit_code VARCHAR(10) NOT NULL , person_code INT NOT NULL , CONSTRAINT pk_org_peeps PRIMARY KEY CLUSTERED (unit_code, person_code) WITH (FILLFACTOR = 100) , CONSTRAINT fk_org_peeps_other_org_peeps FOREIGN KEY (unit_code) REFERENCES dbo.org (unit_code) )GO CREATE VIEW dbo.org_peeps_parents--WITH SCHEMABINDINGAS SELECT org.unit_code , org.parent_code , org_peeps.person_code FROM dbo.org LEFT OUTER JOIN dbo.org_peeps ON org_peeps.unit_code = org.unit_codeGO INSERT INTO dbo.org (unit_code, parent_code)SELECT 'a', 'y' UNION ALLSELECT 'b', 'y' UNION ALLSELECT 'c', 'z' UNION ALLSELECT 'y', 'z' UNION ALLSELECT 'z', NULL--Insert people data (NOTE - the people are in units at the BOTTOM of the structure only)INSERT INTO dbo.org_peeps (unit_code, person_code)SELECT 'a', 1 UNION ALLSELECT 'c', 3 UNION ALL--These data go into intermediate levels of the organisation...SELECT 'y', 4 UNION ALLSELECT 'y', 5 UNION ALLSELECT 'y', 6---------------------------------------------------------------SELECT 'Original query. Because there is data in the intermediate tables --> ' + 'duplicate outputs....'---------------------------------------------------------------;WITH materialised_pathsAS ( SELECT unit_code , parent_code , person_code , unit_path = '/' + CAST(unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org_peeps_parents WHERE parent_code IS NULL UNION ALL SELECT all_people.unit_code , all_people.parent_code , all_people.person_code , mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org_peeps_parents AS all_people INNER JOIN materialised_paths AS mp ON mp.unit_code = all_people.parent_code )SELECT parents.unit_code , children.person_codeFROM materialised_paths AS childrenCROSS APPLY --Correlated derived table - get the child records per unit ( SELECT unit_code , parent_code FROM dbo.org AS parents_sub WHERE children.unit_path LIKE '%/' + parents_sub.unit_code + '/%' ) AS parentsWHERE children.person_code IS NOT NULLORDER BY person_code , unit_code-----------------------------------------------------------------SELECT 'This query returns the correct results but man it is ugly. '+ 'Can it be refined optimised?'-----------------------------------------------------------------;WITH materialised_pathsAS ( SELECT unit_code , parent_code , unit_path = '/' + CAST(unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org WHERE parent_code IS NULL UNION ALL SELECT all_orgs.unit_code , all_orgs.parent_code , mp.unit_path + CAST(all_orgs.unit_code AS VARCHAR(MAX)) + '/' FROM dbo.org AS all_orgs INNER JOIN materialised_paths AS mp ON mp.unit_code = all_orgs.parent_code )SELECT all_orgs.unit_code , org_peeps.person_codeFROM dbo.org_peepsINNER JOIN ( SELECT org.unit_code , mp.unit_path FROM materialised_paths AS mp CROSS APPLY ( SELECT unit_code , parent_code FROM dbo.org WHERE mp.unit_path LIKE '%/' + org.unit_code + '/%' ) AS org ) AS all_orgsON all_orgs.unit_path LIKE '%/' + org_peeps.unit_code + '/'ORDER BY person_code , all_orgs.unit_code--Clean upIF EXISTS (SELECT NULL FROM sys.views WHERE object_id = OBJECT_ID('dbo.org_peeps_parents')) BEGIN DROP VIEW dbo.org_peeps_parentsENDIF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org_peeps')) BEGIN DROP TABLE dbo.org_peepsENDIF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org')) BEGIN DROP TABLE dbo.orgENDAs ever kudos and lavish thanks to anyone that can help :DOh - I nearly forgot - accounting for the Rudy clause - desired output:unit_code person_code---------- -----------a 1y 1z 1c 3z 3y 4z 4y 5z 5y 6z 6

View 14 Replies View Related

Calculate Cumulative Amount From Table

Sep 2, 2014

I need to calculate cum amount from the following table.

CREATE TABLE #TotalRevenue_Investments
( [Month] INT,[Year] INT,TotalRevenue INT,Descr VARCHAR(100),Company VARCHAR(100))
INSERT INTO #TotalRevenue_Investments
( Month ,
Year ,
TotalRevenue ,

[Code] ....

AND so ON ..

I need the OUTPUT AS FOR example

SELECT 1 AS Month,2014 AS Year,12 AS cumAmt,'Late Sales' AS Descr,'US Late Sales' AS Company

View 3 Replies View Related

T-SQL (SS2K8) :: How To Calculate Cumulative Numbers

Feb 6, 2015

I want to show cumulative numbers, but don't know how to calculate them.

Here is an example of the source and the wanted result:

Source:

[Week] [Count]
1 15
2 5
3 6
4 10
(until 52)

Result:

[Week] [Count]
1 15
2 20
3 26
4 36

Is this possible, and how?

TestData:

USE TestDb /*SqlServer 2005*/
CREATE TABLE Test(
[Week] [int] NOT NULL,
[Count] [int] NOT NULL
)
GO
INSERT INTO Test ([Week], [Count]) VALUES (1, 15)
INSERT INTO Test ([Week], [Count]) VALUES (2, 5)
INSERT INTO Test ([Week], [Count]) VALUES (3, 6)
INSERT INTO Test ([Week], [Count]) VALUES (4, 10)

View 8 Replies View Related

Cumulative Related Records From Hierarchy

May 29, 2008

Oh hai

This is closely related to this problem where Ryan & Peter helped me out loads (thanks again guys):
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=101989

I now have a slightly different problem. Instead of returning the cumulative counts of people related to a business unit in the hierarchy I now need to return the actual people records. I had some code, derived from the above, that worked fine until I loaded some new data. It took a while but eventually I figured out the (now obvious) reason for the error. I have tried several changes to the query and not got anywhere. Please could someone have a look and see if you can suggest the required alteration(s)?

USE tempdb
go

---------------------------------------------------------------
--Set up the structure & data...
---------------------------------------------------------------
CREATE TABLE dbo.org
(
unit_codeVARCHAR(10)NOT NULL
, parent_codeVARCHAR(10)NULL
, CONSTRAINT pk_orgPRIMARY KEY CLUSTERED (unit_code) WITH (FILLFACTOR = 100)
)
GO

CREATE TABLE dbo.org_peeps
(
unit_codeVARCHAR(10)NOT NULL
, person_codeINTNOT NULL
, CONSTRAINT pk_org_peepsPRIMARY KEY CLUSTERED (unit_code, person_code) WITH (FILLFACTOR = 100)
, CONSTRAINT fk_org_peeps_other_org_peepsFOREIGN KEY (unit_code) REFERENCES dbo.org (unit_code)
)
GO

CREATE VIEW dbo.org_peeps_parents
--WITH SCHEMABINDING
AS
SELECT org.unit_code
, org.parent_code
, org_peeps.person_code
FROMdbo.org
LEFT OUTER JOIN
dbo.org_peeps
ONorg_peeps.unit_code= org.unit_code
GO

INSERT INTO dbo.org (unit_code, parent_code)
SELECT 'a', 'y'UNION ALL
SELECT 'b', 'y'UNION ALL
SELECT 'c', 'z'UNION ALL
SELECT 'y', 'z'UNION ALL
SELECT 'z', NULL

--Insert people data (NOTE - the people are in units at the BOTTOM of the structure only)
INSERT INTO dbo.org_peeps (unit_code, person_code)
SELECT 'a', 1UNION ALL
SELECT 'c', 3

---------------------------------------------------------------
SELECT'This works great....'
---------------------------------------------------------------
;WITHmaterialised_paths
AS
(
SELECTunit_code
, parent_code
, person_code
, unit_path= '/' + CAST(unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents
WHEREparent_code IS NULL
UNION ALL
SELECTall_people.unit_code
, all_people.parent_code
, all_people.person_code
, mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents AS all_people
INNER JOIN
materialised_paths AS mp
ONmp.unit_code= all_people.parent_code
)

SELECTparents.unit_code
, children.person_code
, children.unit_path
FROMmaterialised_paths AS children
CROSS APPLY--Correlated derived table - get the child records per unit
(
SELECTunit_code
, parent_code
FROMdbo.orgAS parents_sub
WHEREchildren.unit_path LIKE '%/' + parents_sub.unit_code + '/%'
) AS parents
WHEREchildren.person_code IS NOT NULL
ORDER BY person_code
, unit_code


--Add data to INTERMEDIATE levels of organisation
INSERT INTO dbo.org_peeps (unit_code, person_code)
SELECT 'y', 4UNION ALL
SELECT 'y', 5UNION ALL
SELECT 'y', 6

---------------------------------------------------------------
SELECT'Since there is now data in the intermediate tables there are ' +
'duplicate outputs....'
---------------------------------------------------------------
;WITHmaterialised_paths
AS
(
SELECTunit_code
, parent_code
, person_code
, unit_path= '/' + CAST(unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents
WHEREparent_code IS NULL
UNION ALL
SELECTall_people.unit_code
, all_people.parent_code
, all_people.person_code
, mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents AS all_people
INNER JOIN
materialised_paths AS mp
ONmp.unit_code= all_people.parent_code
)
SELECTparents.unit_code
, children.person_code
, children.unit_path
FROMmaterialised_paths AS children
CROSS APPLY--Correlated derived table - get the child records per unit
(
SELECTunit_code
, parent_code
FROMdbo.orgAS parents_sub
WHEREchildren.unit_path LIKE '%/' + parents_sub.unit_code + '/%'
) AS parents
WHEREchildren.person_code IS NOT NULL
ORDER BY person_code
, unit_code

---------------------------------------------------------------
SELECT'This is the output I want - but I can''t simply apply distinct - the volumes of data preclude this'
---------------------------------------------------------------
;WITHmaterialised_paths
AS
(
SELECTunit_code
, parent_code
, person_code
, unit_path= '/' + CAST(unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents
WHEREparent_code IS NULL
UNION ALL
SELECTall_people.unit_code
, all_people.parent_code
, all_people.person_code
, mp.unit_path + CAST(all_people.unit_code AS VARCHAR(MAX)) + '/'
FROMdbo.org_peeps_parents AS all_people
INNER JOIN
materialised_paths AS mp
ONmp.unit_code= all_people.parent_code
)
SELECTDISTINCT
parents.unit_code
, children.person_code
, children.unit_path
FROMmaterialised_paths AS children
CROSS APPLY--Correlated derived table - get the child records per unit
(
SELECTunit_code
, parent_code
FROMdbo.orgAS parents_sub
WHEREchildren.unit_path LIKE '%/' + parents_sub.unit_code + '/%'
) AS parents
WHEREchildren.person_code IS NOT NULL
ORDER BY person_code
, unit_code


--Clean up
IF EXISTS (SELECT NULL FROM sys.views WHERE object_id = OBJECT_ID('dbo.org_peeps_parents')) BEGIN
DROP VIEW dbo.org_peeps_parents
END

IF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org_peeps')) BEGIN
DROP TABLE dbo.org_peeps
END
IF EXISTS (SELECT NULL FROM sys.tables WHERE object_id = OBJECT_ID('dbo.org')) BEGIN
DROP TABLE dbo.org
ENDJust paste and run the code and hopefully it should be reasonably clear. If you need any further info please let me know

View 5 Replies View Related

Update Table - Running Cumulative Sum

Dec 18, 2013

How can I update a table to have a running cumulative sum?

For Example:

Update Table1 Set Cumulative_Sum = Row_Sum + Previous_Row_Sum

It should look something like this:

Row_Sum Cumulative_Sum
1 1
2 3
3 6
4 10

View 6 Replies View Related

Analysis :: Drilling Down On Cumulative Measures

Oct 1, 2015

I have a cumulative measure in Tabular, and when I filter by a date in SQL it brings back all rows up to that date. However, when I drill down on any of the numbers, it only brings back rows related to the filtered date, and not the cumulative rows. Is there any way round this at all? Major obstacle for me at the moment...

View 5 Replies View Related

Cumulative Upgrade 3 Hotfix Missing ?

Oct 1, 2007

Dear all,

I have recently applied the latest cumulative upgrade 3 for SP2 for SQL Server 2005 (KB939537) to have all the hotfixes needed since the SP2, and to correct a specific one : the 50001440 (SQL Server may fail to generate a plan for a complex query that involves cursors and error 8623 occurs - KB940128).

But it is not included in this latest cumulative upgrade package. I read the new policy about CU but I can not know if the 50001440 hotfix is candidate for the CU :

Cumulative update (CU)






€¢
The update can be requested by any customer, regardless of their support offering.

€¢
The update is released every 2 months.

€¢
The update contains the following:



€¢
All previous critical on-demand hotfixes to date.


Fixes for issues that meet hotfix acceptance criteria. These criteria include workaround availability, customer effect, reproducibility, the complexity of the code that must be changed, and so on.



Another bug, the 50001317 (You may receive error messages when you try to log in to an instance of SQL Server 2005 and SQL Server handles many concurrent connections - KB937745) : it is included in the upgrade 2 for SP2 but not in the upgrade3.

So, is it needed to apply each cumulative upgrade or only the latest CU ? And if it is only the latest CU, why are there missing hotfix ?

Thank you very much

Regards,
Emmanuel

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved