Help With A Hierarchy Query Or Procedure

Mar 8, 2007

 I have a table with a parent, child, and grandchild relationship. Can anyone help me with a query that will return the child and grandchild of a parent?

Heres my table:

id pid name
--------------------------------
1 0 UntID
2 0 Vin Number
3 0 Make
4 3 Model
5 4 Model Number
6 0 Model Year
7 0 Vehicle Type
8 0 Odometer Miles



When I select 3 as the id I need these results:

id pid name
--------------------------------
3 0 Make
4 3 Model
5 4 Model Number

 

Thanks for any help!

Ryan

View 15 Replies


ADVERTISEMENT

Query To Return Record From Hierarchy?

Oct 21, 2013

I am wanting to run a SQL statement whereby i return the ID of any employee's Director.

The database for employees has a reports to field which enables me to see the hierarchy of managers above any employee.

There is also a IsDirector flag that indicates a director.

So essentially i want to run sql that would return the first instance of a director in the hierarchy above any employee.

eg if A reports to B and B reports to C (who is a director) then it returns C.

I basically want the script to run until a director is found.

how would i do this?

View 5 Replies View Related

Query To Generate Hierarchy In Organization

Jun 8, 2014

I need to write a sql that generate the hierarchy in an organization.

Below an example

emplid empname supervisor_id superv_name
1 subu null null
2 vid 1 sub
3 ram 4 satis
4 satis 2 vid

I need an output to this query as below and also one important the supervisor ie supervisor_id and name is null is the top level,every employee also has to report to him and also to his all above supervisors.

Whoever joining new to org the hierarchy

empid empname supervisor_id superv_name
3 ram 4 satis
4 satis 2 vid
2 vid 1 subu
4 satis 1 subu
3 ram 1 subu
3 ram 2 vid
5 kumar 1 subu
5 kumar 4 satis
5 kumar 2 vid
1 subu null null

View 3 Replies View Related

SQL Server 2012 :: Better Way To Query A Hierarchy Table?

Jan 21, 2015

I have a table named 'DepartmentItem' which is designed with hierarchy structure. The column 'ParentId' from table DepartmentItem indicates parent-child relationship and department root among records. I have written and run a user-defined function I use recursive approach, but the function runs slowly.

My question: is there a better way to query that hierarchy table instead of using recursive?

** The current user-defined function that is written using recursive:

CREATE FUNCTION dbo.fnGetDepartmentTree
(
@departmentItemId int
)
RETURNS TABLE
AS
RETURN
with DepartmentItemTree(DepartmentItemId , DepartmentItemTypeId , ParentId, ItemOrder, Level)

[code].....

** And definition of table 'DepartmentItem' :

DepartmentItemId int IDENTITY(1,1) NOT NULL,
ParentId int NULL, -- Each department root starts when this column is NULL or the current row is department root. If it is not NULL then the current row has ParentId whose record has DepartmentItemId = ParentId of the current row (see more below)
IsActive bit NOT NULL DEFAULT ((1)),

[Code] .....

View 2 Replies View Related

T-SQL (SS2K8) :: Tree View Hierarchy Query

Feb 25, 2015

ID ParentiD IsAutoCalculate Level
1 0 1 0
2 1 0 1
3 1 0 1
4 1 0 1
5 2 0 2
6 2 0 2
7 3 0 2
8 4 0 2
9 0 1 0
10 9 0 1
11 0 1 0
12 11 1 1
13 12 0 2

The above table shows a parent child relationship with the hierarchy shown in column level. for each parent (IDs 1, 9, 11), I want the first child level where the column IsAutoCalculate = 0

so for parent Id 1, the rows to be returned is of level 1 as that is the first child row of this parent with IsAutoCalculate = 0. The rows with level 2 should not be returned

For parent id 3, the rows to be returned will be with level 2 as this is the first child row of this parent with IsAutoCalculate = 0

View 6 Replies View Related

Hierarchy Query To Form Organization Structure

Jun 8, 2014

I need to write a sql that generate the hierarchy in an organization.Below an example

emplid empname supervisor_id superv_name
1 subu null null
2 vid 1 sub
3 ram 4 satis
4 satis 2 vid

i need an output to this query as below and also one important the supervisor ie supervisor_id and name is null is the top level,every employee also has to report to him and also to his all above supervisors.whoever joinng new to org the hierachy should be follwed

empid empname supervisor_id superv_name
3 ram 4 satis
4 satis 2 vid
2 vid 1 subu
4 satis 1 subu
3 ram 1 subu
3 ram 2 vid
5 kumar 1 subu
5 kumar 4 satis
5 kumar 2 vid
1 subu null null

View 1 Replies View Related

MDX Query On Non-Visible Attribute Hierarchy Dimension Fields

Aug 8, 2007

I am in the process of develping a MSRS report using an MSAS 2005 OLAP cube as my data source. In the MSRS Query Builder, I am using an MDX query which successfully executes in Management Studio. Something like the following:


SELECT

NON EMPTY { [Measures].[Fact Count] }
ON COLUMNS,
NON EMPTY{ ( [Dim Attribute].[Hierarchy Not Visible].ALLMEMBERS) } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME
ON ROWS
FROM [MyCube]

CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS

The twist is that the AttributeHierarchyVisible property of the [Dim Attribute].[Hierarchy Not Visible] is set to False.

As mentioned previously, the query successfully executes in Management Studio. However when it is executed in the MSRS Query Builder, the following error message is displayed:

The query cannot be prepared: The query must have at least one axis. The first axis of the query should not have multiple hierarchies, nor should it reference any dimension other than the Measures dimension..
Parameter name: mdx (MDXQueryGenerator)


Is there a way to successfully query dimension attributes whose hierarchies are not visible?

Thanks.

View 2 Replies View Related

Reporting Services :: Employee Hierarchy Query In SSRS

Sep 18, 2015

I have one view, i written below query to get employee hierarchy based on orgid and employee name..

If i select employeename it shoukd show employee reporties(under employees and below employee reporties like tree structure)

It is running fast in SSMS Level, but it is taking more time in SSRS(Sql Sever Report Services), If i run this query in SSRS,Some times System not responding. 

Declare @OrgId int
Declare @EName varchar(30)
Set @OrgId=56793
Set @EName='ABCD'
Select EmpId

[Code] .....

View 9 Replies View Related

SQL Server 2012 :: Query To Generate Relationship (Parent Child Hierarchy From A Table)

Jul 18, 2015

I am working on a query to generate parent child hierarchy from a table.

Table has below records.

--===== If the test table already exists, drop it
IF OBJECT_ID('TempDB..#mytable','U') IS NOT NULL
DROP TABLE #mytable

--===== Create the test table with
CREATE TABLE #mytable

[Code] ...

how to achieve this.l tried with temp tables it doesn't work.

View 5 Replies View Related

Stored Procedure In Query Analyzer Vs Linked Procedure In MS Access

Jan 12, 2007

For some reason, I run a stored procedure in Query Analyzer and it works fine. When I run the very same procedure in MS access by clicking on its link I have to run it twice. The first run gives me the message that the stored procedure ran correctly but returned no records. The second run gives me the correct number of records but I have to run it twice. I am running month-to-month data. The first run is Jan thru March. Jan and Feb have no records so I run three months on the first set. The ensuing runs are individual months from April onward. The output is correct but any ideas on why I have to do it twice in Access? I am a bit new to stored procedures but my supervisor assures me that it should be exactly the same.

ddave

View 2 Replies View Related

SQL Server Admin 2014 :: Estimated Query Plan For A Stored Procedure With Multiple Query Statements

Oct 30, 2015

When viewing an estimated query plan for a stored procedure with multiple query statements, two things stand out to me and I wanted to get confirmation if I'm correct.

1. Under <ParameterList><ColumnReference... does the xml attribute "ParameterCompiledValue" represent the value used when the query plan was generated?

<ParameterList>
<ColumnReference Column="@Measure" ParameterCompiledValue="'all'" />
</ParameterList>
</QueryPlan>
</StmtSimple>

2. Does each query statement that makes up the execution plan for the stored procedure have it's own execution plan? And meaning the stored procedure is made up of multiple query plans that could have been generated at a different time to another part of that stored procedure?

View 0 Replies View Related

Stored Procedure Dbo.SalesByCategory Of Northwind Database: Enter The Query String - Query Attempt Failed. How To Do It Right?

Mar 25, 2008

Hi all,
In the Programmability/Stored Procedure of Northwind Database in my SQL Server Management Studio Express (SSMSE), I have the following sql:


USE [Northwind]

GO

/****** Object: StoredProcedure [dbo].[SalesByCategory] Script Date: 03/25/2008 08:31:09 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE PROCEDURE [dbo].[SalesByCategory]

@CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'

AS

IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998'

BEGIN

SELECT @OrdYear = '1998'

END

SELECT ProductName,

TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)

FROM [Order Details] OD, Orders O, Products P, Categories C

WHERE OD.OrderID = O.OrderID

AND OD.ProductID = P.ProductID

AND P.CategoryID = C.CategoryID

AND C.CategoryName = @CategoryName

AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear

GROUP BY ProductName

ORDER BY ProductName

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
From an ADO.NET 2.0 book, I copied the code of ConnectionPoolingForm to my VB 2005 Express. The following is part of the code:

Imports System.Collections.Generic

Imports System.ComponentModel

Imports System.Drawing

Imports System.Text

Imports System.Windows.Forms

Imports System.Data

Imports System.Data.SqlClient

Imports System.Data.Common

Imports System.Diagnostics

Public Class ConnectionPoolingForm

Dim _ProviderFactory As DbProviderFactory = SqlClientFactory.Instance

Public Sub New()

' This call is required by the Windows Form Designer.

InitializeComponent()

' Add any initialization after the InitializeComponent() call.

'Force app to be available for SqlClient perf counting

Using cn As New SqlConnection()

End Using

InitializeMinSize()

InitializePerfCounters()

End Sub

Sub InitializeMinSize()

Me.MinimumSize = Me.Size

End Sub

Dim _SelectedConnection As DbConnection = Nothing

Sub lstConnections_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstConnections.SelectedIndexChanged

_SelectedConnection = DirectCast(lstConnections.SelectedItem, DbConnection)

EnableOrDisableButtons(_SelectedConnection)

End Sub

Sub DisableAllButtons()

btnAdd.Enabled = False

btnOpen.Enabled = False

btnQuery.Enabled = False

btnClose.Enabled = False

btnRemove.Enabled = False

btnClearPool.Enabled = False

btnClearAllPools.Enabled = False

End Sub

Sub EnableOrDisableButtons(ByVal cn As DbConnection)

btnAdd.Enabled = True

If cn Is Nothing Then

btnOpen.Enabled = False

btnQuery.Enabled = False

btnClose.Enabled = False

btnRemove.Enabled = False

btnClearPool.Enabled = False

Else

Dim connectionState As ConnectionState = cn.State

btnOpen.Enabled = (connectionState = connectionState.Closed)

btnQuery.Enabled = (connectionState = connectionState.Open)

btnClose.Enabled = btnQuery.Enabled

btnRemove.Enabled = True

If Not (TryCast(cn, SqlConnection) Is Nothing) Then

btnClearPool.Enabled = True

End If

End If

btnClearAllPools.Enabled = True

End Sub

Sub StartWaitUI()

Me.Cursor = Cursors.WaitCursor

DisableAllButtons()

End Sub

Sub EndWaitUI()

Me.Cursor = Cursors.Default

EnableOrDisableButtons(_SelectedConnection)

End Sub

Sub SetStatus(ByVal NewStatus As String)

RefreshPerfCounters()

Me.statusStrip.Items(0).Text = NewStatus

End Sub

Sub btnConnectionString_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConnectionString.Click

Dim strConn As String = txtConnectionString.Text

Dim bldr As DbConnectionStringBuilder = _ProviderFactory.CreateConnectionStringBuilder()

Try

bldr.ConnectionString = strConn

Catch ex As Exception

MessageBox.Show(ex.Message, "Invalid connection string for " + bldr.GetType().Name, MessageBoxButtons.OK, MessageBoxIcon.Error)

Return

End Try

Dim dlg As New ConnectionStringBuilderDialog()

If dlg.EditConnectionString(_ProviderFactory, bldr) = System.Windows.Forms.DialogResult.OK Then

txtConnectionString.Text = dlg.ConnectionString

SetStatus("Ready")

Else

SetStatus("Operation cancelled")

End If

End Sub

Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click

Dim blnError As Boolean = False

Dim strErrorMessage As String = ""

Dim strErrorCaption As String = "Connection attempt failed"

StartWaitUI()

Try

Dim cn As DbConnection = _ProviderFactory.CreateConnection()

cn.ConnectionString = txtConnectionString.Text

cn.Open()

lstConnections.SelectedIndex = lstConnections.Items.Add(cn)

Catch ex As Exception

blnError = True

strErrorMessage = ex.Message

End Try

EndWaitUI()

If blnError Then

SetStatus(strErrorCaption)

MessageBox.Show(strErrorMessage, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)

Else

SetStatus("Connection opened succesfully")

End If

End Sub

Sub btnOpen_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnOpen.Click

StartWaitUI()

Try

_SelectedConnection.Open()

EnableOrDisableButtons(_SelectedConnection)

SetStatus("Connection opened succesfully")

EndWaitUI()

Catch ex As Exception

EndWaitUI()

Dim strErrorCaption As String = "Connection attempt failed"

SetStatus(strErrorCaption)

MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

End Sub

Sub btnQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click

Dim queryDialog As New QueryDialog()

If queryDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then

Me.Cursor = Cursors.WaitCursor

DisableAllButtons()

Try

Dim cmd As DbCommand = _SelectedConnection.CreateCommand()

cmd.CommandText = queryDialog.txtQuery.Text

Using rdr As DbDataReader = cmd.ExecuteReader()

If rdr.HasRows Then

Dim resultsForm As New QueryResultsForm()

resultsForm.ShowResults(cmd.CommandText, rdr)

SetStatus(String.Format("Query returned {0} row(s)", resultsForm.RowsReturned))

Else

SetStatus(String.Format("Query affected {0} row(s)", rdr.RecordsAffected))

End If

Me.Cursor = Cursors.Default

EnableOrDisableButtons(_SelectedConnection)

End Using

Catch ex As Exception

Me.Cursor = Cursors.Default

EnableOrDisableButtons(_SelectedConnection)

Dim strErrorCaption As String = "Query attempt failed"

SetStatus(strErrorCaption)

MessageBox.Show(ex.Message, strErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

Else

SetStatus("Operation cancelled")

End If

End Sub
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I executed the code successfully and I got a box which asked for "Enter the query string".
I typed in the following: EXEC dbo.SalesByCategory @Seafood. I got the following box: Query attempt failed. Must declare the scalar variable "@Seafood". I am learning how to enter the string for the "SQL query programed in the subQuery_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnQuery.Click" (see the code statements listed above). Please help and tell me what I missed and what I should put into the query string to get the information of the "Seafood" category out.

Thanks in advance,
Scott Chang

View 4 Replies View Related

Stored Procedure Query Optimization - Query TimeOut Error

Nov 23, 2004

How to optimize the following Stored procedure running on MSSQL server 2000 sp4 :

CREATE PROCEDURE proc1
@Franchise ObjectId
, @dtmStart DATETIME
, @dtmEnd DATETIME
AS
BEGIN


SET NOCOUNT ON

SELECT p.Product
, c.Currency
, c.Minor
, a.ACDef
, e.Event
, t.Dec
, count(1) "Count"
, sum(Amount) "Total"
FROM tb_Event t
JOIN tb_Prod p
ON ( t.ProdId = p.ProdId )
JOIN tb_ACDef a
ON ( t.ACDefId = a.ACDefId )
JOIN tb_Curr c
ON ( t.CurrId = c.CurrId )
JOIN tb_Event e
ON ( t.EventId = e.EventId )
JOIN tb_Setl s
ON ( s.BUId = t.BUId
and s.SetlD = t.SetlD )
WHERE Fran = @Franchise
AND t.CDate >= @dtmStart
AND t.CDate <= @dtmEnd
AND s.Status = 1
GROUP BY p.Product
, c.Currency
, c.Minor
, a.ACDef
, e.Event
, t.Dec

RETURN 1
END



GO

View 8 Replies View Related

Db Hierarchy

May 8, 2006

HI!
I am new in DB so I need some advices for finding the right solution.
I need to be able to make automatically any join between tables which the user choose and deliver the result.
is like making an hierarchy between all tables in DB (parent-child) and then making the select statement for the right join.

if u have any idea about how can I manage this, pls help me.

thanks a lot!

View 2 Replies View Related

HIERARCHY HELP! PLEASE?

Feb 26, 2008

I have an Interesting situation that I'm hoping some of you experts can help me with basically I have the following hierarchy:

Net Profit
.....Gross Profit
..........Revenue
..........Direct Costs
.....Indirect Expense


Now, I have another hierarchy - separate from the above - that I need to assimilate to the hierarchy above - Example:

Expenses
.....Node a
..........Child a (Indirect Expense Type)
.....Child b (Direct Cost type)
Net Sales Adjustments
.....Child a (Revenue type)
.....Child b (Revenue type)

Depending on the type, the top most node needs to be assigned to the appropriate node in the initial hierarcy, like this:

Net Profit
....Gross Profit
........Revenue
................Net Sales Adjustments
....................Child a (Revenue type)
....................Child b (Revenue type)
........Direct Costs
...........Expenses
.................Child b (Direct Cost type)
........Indirect Expense
............Expenses
.................Node a
.....................Child a (Indirect Expense Type)

Now, I've been able to figure out how to assign the top most node and leafs if all the children have the same type (using the expan stored proc listed in the books online), but my question is on this portion:

Expenses
.....Node a
...........Child a (Indirect Expense Type)
.....Child b (Direct Cost type)

Basically, the answer is to work backwards - if a child has a type that is different than the other children, a copy of the hierarch (up to the child) needs to be made and assigned to the appropriate initial node.

I've tried modifying the expand stored proc to give me the lineage of the child and see if there's a way I can copy the node and place it appropriately - I'm brainfried at this point, and I'm hoping that someone outthere can point me in the right direction.

Thanks in advance for your time

View 6 Replies View Related

Hierarchy

Mar 7, 2008

Hai everyone.,
i need to get solution for tree hierarchy in sql is there any solution or any keyword like 'connect by prior' in oracle ..
plz help me on this..

for example:
id | FName |parentid |
1 | sandy |
2 | robert| 1

if i give the parentid 1 in where condition of a query i need the details of 'sandy'

Thanks in Advance.
B.Arul.

View 2 Replies View Related

Hierarchy

Jul 10, 2006

Hello!I have a table that looks like this:Col1; Col2; Col3; Col4; Col538; 75; 233; 916; 277038; 75; 233; 916; 277138; 75; 233; 916; 277238; 75; 233; 923; 265438; 75; 233; 923; 265538; 75; 245; 913; 245438; 75; 245; 913; 2456....And I need a query (not a procedure) that shows me this:38; NULL; NULL; NULL; NULLNULL; 75; NULL; NULL; NULLNULL; NULL; 233; NULL; NULLNULL; NULL; NULL; 916; NULLNULL; NULL; NULL; NULL; 2770NULL; NULL; NULL; NULL; 2771NULL; NULL; NULL; NULL; 2772NULL; NULL; NULL; 923; NULLNULL; NULL; NULL; NULL; 2654NULL; NULL; NULL; NULL; 2655NULL; NULL; 245; NULL; NULLNULL; NULL; NULL; 913; NULLNULL; NULL; NULL; NULL; 2454NULL; NULL; NULL; NULL; 2456....Does anybody know how i can get this result? How?Help! Thank you!SQLNullps: SQL-Server 2000

View 3 Replies View Related

Hierarchy

May 24, 2006

Hi to All!

Is there a perfect method to implement a hierarchy structure with different types as a table in Sql server 2005? Currently I am thinking of this way:

[Node | ParentId | ParentType | ChildId | ChildType]

But there is this nagging little voice saying it can be better

Cheers!

Nele

View 5 Replies View Related

Hierarchy ORBER BY

Mar 9, 2004

Hi, I'm trying to figure out how to write I SP on the following table that will produce the results show at the bottom. My main problem is the sorting, is there a way I loop through the records in TSQL and ORDER BY SortSort where the ParentID's are the same?

Thank you.


Table example

IDParentIDSortOrderCaption
1null1Main
211Files
313Folders
422File2
512Holders
621File1
752Holder2
851Holder1

Required result example

Main
-Files
--File1
--File2
-Holders
--Holder1
--Holder2
-Folders

View 3 Replies View Related

Hierarchy Level

Apr 28, 2008

Hi

i tried on CTE but iam not gettng correct result plz help me


Declare @TMaster Table (MasterId int, Type varchar(100), ParentMasterId int)
Insert into @Tmaster
Select 1, 'Fixed', 14 Union All
Select 2, 'Flexible',14 union All
Select 3, 'Others',14 union All
Select 13, 'Retirement benefits',1 union All
Select 14, 'PBHeads', 0

Select * From @Tmaster

Declare @TDetails Table ( MasterId Int, Description varchar(100))
Insert into @TDetails
Select 1, 'Basic' union all
Select 1,'Conveyance' union all
Select 1,'HRA' union all
Select 1,'Special Allowance' union all
Select 2, 'Children Education' union all
Select 2,'Travel Allowance' union all
Select 2,'Medical Expenses' union all
Select 2,'Variable Spl Pay' union all
Select 3, 'Project Allowance' union all
Select 3,'Quarterly Incentive' union all
Select 3,'Shift Allowance' union all
Select 3,'Annual Component' union all
Select 13,'Provident Fund' union all
Select 13,'Gratuity' union all
Select 13,'Super annuation'


Select * From @TDetails

in group list we have to show fixed, flexible, other
in subgroups(L1) list under fixed we have to show
Basic salary, HRA, Conveyance, Special Allowance,Retirement benefits

in subgroup(L2) we have to show Gratuity, providedfund, Super annuation they are subgroups of retirementbenefits


output :
Group Subgroup(L1) Subgroup(L2)
Fixed
Basic salary
HRA
Conveyance
Special Allowance
Retirement benefits
Provident Fund
Gratuity
Super annuation

Flexible reimbursements
LTA/Group Travel
Medical expenses
Children education
variable special pay

Others
Project allowance
Performance incentive
Medical insurance

View 12 Replies View Related

Ordering Within Hierarchy

Aug 7, 2007

Hi all,

Ive got a bit of a problem,

I have two tables:

CATEGORY
id
name
parent_CATEGORY_id

RECORD
id
CATEGORY_id
Stock_Held_Number

ps. Ive stripped out any non relevant fields


I also have the following query (again ive stripped out the non-relevant fields)

SELECT TOP (100) PERCENT SUM(dbo.RECORD.Stock_Held_Number) AS TotalStock, CATEGORY.Name AS FundName
FROM CATEGORY
LEFT OUTER JOIN dbo.RECORD ON CATEGORY.ID = dbo.RECORD.CATEGORY_id
GROUP BY CATEGORY.Name, RECORD.Stock_Held_Number

At the moment its grouping all the CATEGORIES and giving me a sum total for each which is great.

The problem I have is the CATEGORY table, there is an optional join to parent CATEGORY records on the table.

What Im trying to do is to provide a fully ordered result within the CATEGORIES and I don't have a clue.

For example:

The CATEGORY table has the following values
ID Name Parent_Category_id
1 Pens
2 Animals
3 Rocks
4 Horses 2
5 Dogs 2

When I currently run the query I get:
Name TotalStock
Pens 20
Animals 30
Rocks 40
Horses 50
Dogs 60

It's technically correct because I don't want the parent to calculate the total value of the children

What Im really trying to do is order them within the hierarchy though and indent (if possible) the result so I would get

Name TotalStock
Animals 30
---Dogs 60
---Horses 50
Pens 20
Rocks 40

Does anybody have any pointers as to how I can achieve this.

Many thanks

Mike

View 3 Replies View Related

Parameter Hierarchy

Feb 21, 2008

how do i create a parameter in hierarchy?

SAMPLE

billing period:
YEAR 2007
1st quarter
jan
feb
mar
2nd quarter
april
may
june


something like that.... if the user chose the 1st quarter the report will generate a sum-up report for the 1st quarter of 2007...


kindly reply asap.. i really need to get this report working..

thanks!

View 5 Replies View Related

Update Hierarchy

Nov 2, 2007

I have structure:FolderId, FolderName, ParentFolderId, FullPathe.g.1, First, null, First2, Sec, 1, First/Sec.....When update happens to FolderName, i need to update all FullPaths thatare below Folder which is changing.Any ideas?Thank you.

View 3 Replies View Related

Sparse Hierarchy T-SQL Help...PLEASE?

Jul 20, 2005

Greetings!I could really use some suggestions on how to improve on thefollowing, it at all possible:Table 'Customer'---------------------ID GUID PK....Table 'Facility'-----------------ID GUID PKCustomerID GUID FK (FK to Customer GUID)....Table 'Rate'----------------ID PKOwnerID GUID Nullable FK (FK to Customer, Facility GUID PK)OwnerLevel INT Contraint 1-3<Rate Data>Table 'Rate' is a sparse hierarchy of data. There are 3 possiblelevels in the hierarchy as follows:OwnerID <NULL>OwnerLevel 1This indicates Global rate data.OwnerID <Customer.ID>OwnerLevel 2This indicates Customer-specific rate data.OwnerID <Facility.ID>OwnerLevel 3This indicates Facility-specific rate data.Now, a given Customer need not have an entry in the Rate table. If aCustomer does not have an entry, it is supposed to 'inherit' Globalrate data. A given Facility need not have an entry in the Rate table.If a Facility does not have an entry, it is supposed to inheritCustomer-specific rate data, and in the absence of an entry for theFacility's parent Customer, it is supposed to inherit Global ratedata.The challenge is that I want to write a view to give me back theappropriate rate record for Customer and Facility. Here's what I'vedone so far.View _Rate--------------SELECTRate.*,NULL AS TargetIDFROMRateWHERERate.OwnerID IS NULLUNIONSELECTRate.*,Customer.ID AS TargetIDFROMRateCROSS JOINCustomerWHERERate.OwnerID IS NULLOR Rate.OwnerID = Customer.IDUNIONSELECTRate.*,Facility.ID AS TargetIDFROMRateCROSS JOINFacilityWHERERate.OwnerID IS NULLOR Rate.OwnerID IN (Facility.CustomerID, Facility.ID)View view_Rate--------------------SELECT_Rate.*FROM_RateINNER JOIN(SELECTTargetID,MAX(OwnerLevel) AS OwnerLevelFROM_RateGROUP BYTargetID) AS Filtered_RateON_Rate.TargetID = Filtered_Rate.TargetIDAND _Rate.OwnerLevel = Filtered_Rate.OwnerLevelThe combination of these two views gives a resultset that contains 1record for every Target ID as follows:TargetID <NULL>OwnerID <NULL>OwnerLevel 1This indicates Global rate data established at the Global level.TargetID <Customer.ID>OwnerID <NULL>OwnerLevel 1This indicates Customer rate data for the specific Customer identifiedby Customer.ID is inherited from the Global rate data.TargetID <Customer.ID>OwnerID <Customer.ID>OwnerLevel 2This indicates Customer-specific rate data for the specific Customeridentified by Customer.ID (not inherited).TargetID <Facility.ID>OwnerID <NULL>OwnerLevel 3This indicates Facility rate data is inherited from the Global ratedata.TargetID <Facility.ID>OwnerID <Customer.ID>OwnerLevel 2This indicates Facility rate data for the specific Facility identifiedby Facility.ID is inherited from the Facility's parent Customer'sCustomer-specific rate data.TargetID <Facility.ID>OwnerID <Facility.ID>OwnerLevel 3This indicates Facility-specific rate data for the specific Facilityidentified by Facility.ID (not inherited).I know this is a lengthy post, and a complicted query scenario, butI'm not willing to accept that my solution is the best solution justyet. Please consider that I really need this functionality in a VIEWas much as possible.Thank you for your learned consideration.I eagerly await your replies.Darryll

View 2 Replies View Related

Graph Hierarchy: What Is It Exactly?!!

Dec 21, 2007

Hi everybody,
I've been reading the book MCITP Self-Paced Training Kit (Exam 70-441): Designing Database Solutions by Using Microsoft SQL Server(TM) 2005 (Self-Paced Training Kits) as a part of my preparation for exam 70-441
The book is really clear, and I could understand everything easily because I've some experience as a database developer.
Until now, there's only one thing that I didn't fully understand:
On pages 53 and 54, it mentions a type of hierarchy called: a graph hierarchy, and it gives a small example made the things even more complicated
I've many books about database design theories, but they don't use the term (graph hierarchy) any where...
So, I appreciate if you can point me to an online resource or a book that discusses this term thorougly.

Thank you

View 3 Replies View Related

Concept Hierarchy-

Jul 13, 2006

What are some strategies in categorizing items?

View 4 Replies View Related

Use Hierarchy From SSAS

Sep 6, 2007

Hello experts,

Last time I worked with SSAS and build a Cube. Because I€™m now very happy with the front-end excel 2003 or excel 2007 I thought I build my own Report with SSRS.
Now there is something I don€™t understand:
I build a Hierarchy in SSAS that a want to use in SSRS. Is there a chance to use it without any features? Have I to use parameters or something another?
In my opinion it makes any sense to build a hierarchy new, because it€™s already exists in SSAS.

Have a nice day
Alex

View 5 Replies View Related

Hierarchy In Sql Server

Dec 5, 2007

Hello ,

I'm facing a complicated problem and I don't think that the solution will be an easy one.

I have an SQL statement in Oracle which I need to translate it in Sql Server 2005.

select lpad(' ',5*(orderid)) || to_char(descr) as menui
from <table _name>
where MENU_ITEM not in ('test1','test2','test3') and item_parent not in ('test4,'test5,'test6')
start with <item_parent='item_parent' >
connect by prior <menu_item = item_parent and menu_name='something'; > ?(condition)

Somewhere I have read that SQL server does not support Hierarchical Sql statements. Is this true ? How am I going to do that ?

Any help will be appreciated.

Thank you

View 7 Replies View Related

How To Get The Data In A Hierarchy?

Dec 12, 2007


How can I get the data from a table that stores hierarchical information keeping the right order and hierarchy levels?

I also need to specify a first level....let me explain.

Table: Sites
Id (PK)
Title
Url
ParentId


If I have something like this:

1 | Test | http://localhost | NULL
2 | Sub-Test | http://localhost/subtest | 1
3 | SecondItem | http://anotherServer | NULL
4 | ChildOfSub-Test | http://localhost/subtest/child | 2


And I specify that I want all child items below the Id 2, it must return:
Id | Title | Url | ParentId | Depth
2 | Sub-Test | http://localhost/subtest | 1 | 0

4 | ChildOfSub-Test | http://localhost/subtest/child | 2 | 1

How can I do this? I've saw some examples with CTEs, but they always return all of the items.

View 7 Replies View Related

Dynamic Hierarchy

Nov 23, 2007

Hi people
In have a query over two tables, and the ouptut is:
RowID | SubMarcaID | MarcaID | ProductoID
1 | 1 | 1 | 1
2 | 1 | 1 | 2
3 | 1 | 1 | NULL
4 | 3 | 1 | 3
5 | 3 | 1 | NULL

(SubMarcaID and MarcaID are the KEYS from SUBMARCA, and ProductoID is the key from PRODUCTO. Also SubMarcaID and MarcaID are foreing keys on PRODUCTO)

Now, I need a ParentRowID based on SubMarcaID and MarcaID, like a hierarchy

RowID | SubMarcaID | MarcaID | ProductoID | ParentRowID
1 | 1 | 1 | 1 | 3
2 | 1 | 1 | 2 | 3
3 | 1 | 1 | NULL | 0
4 | 3 | 1 | 3 | 5
5 | 3 | 1 | NULL | 0
How can I do this?



Code Block

SELECT ROW_NUMBER() OVER (ORDER BY PRODUCTO.MarcaID, PRODUCTO.SubMarcaID) AS RowID,

PRODUCTO.SubMarcaID,

PRODUCTO.MarcaID,

PRODUCTO.ProductoID

FROM PRODUCTO, SGP_SUBMARCA

WHERE PRODUCTO.SubMarcaID = SUBMARCA.SubMarcaID

AND PRODUCTO.MarcaID = SUBMARCA.MarcaID

GROUP
BY PRODUCTO.SubMarcaID,

PRODUCTO.MarcaID,

PRODUCTO.ProductoID

WITH
ROLLUP

HAVING (



GROUPING(PRODUCTO.ProductoID) = 1

AND GROUPING(PRODUCTO.SubMarcaID) = 0

AND GROUPING(PRODUCTO.MarcaID) = 0

)

OR (

GROUPING(PRODUCTO.SubMarcaID) = 0

AND GROUPING(PRODUCTO.MarcaID) = 0

AND GROUPING(PRODUCTO.ProductoID) = 0

)

View 1 Replies View Related

Help: Why Excute A Stored Procedure Need To More 30 Seconds, But Direct Excute The Query Of This Procedure In Microsoft SQL Server Management Studio Under 1 Second

May 23, 2007

Hello to all,
I have a stored procedure. If i give this command exce ShortestPath 3418, '4125', 5 in a script and excute it. It takes more 30 seconds time to be excuted.
but i excute it with the same parameters  direct in Microsoft SQL Server Management Studio , It takes only under 1 second time
I don't know why?
Maybe can somebody help me?
thanks in million
best Regards
Pinsha 
My Procedure Codes are here:set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[ShortestPath] (@IDMember int, @IDOther varchar(1000),@Level int, @Path varchar(100) = null output )
AS
BEGIN
 
if ( @Level = 1)
begin
select @Path = convert(varchar(100),IDMember)
from wtcomValidRelationships
where wtcomValidRelationships.[IDMember]= @IDMember
and PATINDEX('%'+@IDOther+'%',(select RelationshipIDs from wtcomValidRelationships where IDMember = @IDMember) ) > 0
end
if (@Level = 2)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+'-'+convert(varchar(100),B.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and PATINDEX('%'+@IDOther+'%',B.RelationshipIDs) > 0
end
if (@Level = 3)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+ '-'+convert(varchar(100),B.IDMember)+'-'+convert(varchar(100),C.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B, wtcomValidRelationships as C
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and charindex(convert(varchar(100),C.IDMember),B.RelationshipIDs) > 0 and PATINDEX('%'+@IDOther+'%',C.RelationshipIDs) > 0
end
if ( @Level = 4)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+ '-'+convert(varchar(100),B.IDMember)+'-'+convert(varchar(100),C.IDMember)+'-'+convert(varchar(100),D.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B, wtcomValidRelationships as C, wtcomValidRelationships as D
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and charindex(convert(varchar(100),C.IDMember),B.RelationshipIDs) > 0 and charindex(convert(varchar(100),D.IDMember), C.RelationshipIDs) > 0
and PATINDEX('%'+@IDOther+'%',D.RelationshipIDs) > 0
end
if (@Level = 5)
begin
select top 1 @Path = convert(varchar(100),A.IDMember)+ '-'+convert(varchar(100),B.IDMember)+'-'+convert(varchar(100),C.IDMember)+'-'+convert(varchar(100),D.IDMember)+'-'+convert(varchar(100),E.IDMember)
from wtcomValidRelationships as A, wtcomValidRelationships as B, wtcomValidRelationships as C, wtcomValidRelationships as D, wtcomValidRelationships as E
where A.IDMember = @IDMember and charindex(convert(varchar(100),B.IDMember),A.RelationshipIDS) > 0
and charindex(convert(varchar(100),C.IDMember),B.RelationshipIDs) > 0 and charindex(convert(varchar(100),D.IDMember), C.RelationshipIDs) > 0
and charindex(convert(varchar(100),E.IDMember),D.RelationshipIDs) > 0 and PATINDEX('%'+@IDOther+'%',E.RelationshipIDs) > 0
end
if (@Level = 6)
begin
select top 1 @Path = '' from wtcomValidRelationships
end
END
 
 
 

View 6 Replies View Related

Get Ancestor And Descendant In A Hierarchy

Sep 17, 2007

For a short time I have considered how to get the hierarchy in a self-linked table, incidentally I have found an article about ‘Recursive CTEs’ in ‘SQL Server Books Online’, where an example is very impressive and arouses me to find a way to get the ancestors or descendants of a given node in a self-linked (self-referenced) table.

And now I want to share this method to anyone who has the same problem to resolve or someone like me who has addiction in SQL.

First of all we have to create a table for the following functions and build some test data. The statemens look like:

create table ST_CATEGORY(
CATEGORYID uniqueidentifier not null default NEWID(),
PARENTID uniqueidentifier,
[NAME] varchar(128),
COMMENT varchar(4096),
CONSTRAINT PK_ST_CATEGORY primary key (CATEGORYID)
)
go

insert into ST_CATEGORY(CATEGORYID, PARENTID, [NAME], COMMENT)
values(@rootoid, NULL, 'ROOT', 'ROOT NODE')

insert into ST_CATEGORY(CATEGORYID, PARENTID, [NAME], COMMENT)
values(NEWID(), @rootoid, 'Business Application', 'group for all business applications')

declare @techoid uniqueidentifier
set @techoid = NEWID()

insert into ST_CATEGORY(CATEGORYID, PARENTID, [NAME], COMMENT)
values(@techoid, @rootoid, 'Tech101', 'technical tips')

insert into ST_CATEGORY(CATEGORYID, PARENTID, [NAME], COMMENT)
values(NEWID(), @techoid, 'C#', 'C# tips')
go

Now that the test table and data are prepared, we can get ancestors or descendants through the following four stored procedures of a given category.

CREATE PROCEDURE spGetAncestor
@categoryID uniqueidentifier
AS
BEGIN
-- find parents/ancestor
WITH Ancestor( CATEGORYID ) AS
(
SELECT PARENTID
FROM ST_CATEGORY
WHERE CATEGORYID = @categoryID
UNION ALL
SELECT PARENTID
FROM Ancestor, ST_CATEGORY
WHERE Ancestor.CATEGORYID = ST_CATEGORY.CATEGORYID
)
SELECT * FROM Ancestor
END
GO

CREATE PROCEDURE spGetSelfAndAncestor
@categoryID uniqueidentifier
AS
BEGIN
-- find self and parents/ancestor
WITH SelfAndAncestor( CATEGORYID ) AS
(
SELECT CATEGORYID
FROM ST_CATEGORY
WHERE CATEGORYID = @categoryID
UNION ALL
SELECT PARENTID
FROM SelfAndAncestor, ST_CATEGORY
WHERE SelfAndAncestor.CATEGORYID = ST_CATEGORY.CATEGORYID
)
SELECT * FROM SelfAndAncestor
END
GO

CREATE PROCEDURE spGetDescendant
@categoryID uniqueidentifier
AS
BEGIN
-- find children/descendant
WITH Descendant( CATEGORYID ) AS
(
SELECT CATEGORYID
FROM ST_CATEGORY
WHERE PARENTID = @categoryID
UNION ALL
SELECT ST_CATEGORY.CATEGORYID
FROM Descendant, ST_CATEGORY
WHERE Descendant.CATEGORYID = ST_CATEGORY.PARENTID
)
SELECT * FROM Descendant
END
GO

CREATE PROCEDURE spGetSelfAndDescendant
@categoryID uniqueidentifier
AS
BEGIN
-- find self and children/descendant
WITH SelfAndDescendant( CATEGORYID ) AS
(
SELECT CATEGORYID
FROM ST_CATEGORY
WHERE CATEGORYID = @categoryID
UNION ALL
SELECT ST_CATEGORY.CATEGORYID
FROM SelfAndDescendant, ST_CATEGORY
WHERE SelfAndDescendant.CATEGORYID = ST_CATEGORY.PARENTID
)
SELECT * FROM SelfAndDescendant
END
GO

View 1 Replies View Related

Hierarchy, Max(Date) And Inner Joins

Jun 13, 2008

Ok first I am still very new to SQL so I really do not understand quite a bit (SP's, Sub Query's,CTE, etc..). I also went through the SQLTeam article on trees and hierachies but only confused myself even more.

I will try my best to put all the information that I know of (in the shortest way that I know).....sorry I know this is long :(

SQLExpress2005
SQL Server Management Studio Express

Two Tables

PartMaster
PRTNUM_01.......varchar(30) ////Part Number
PMDES1_01.........varchar(50) ////Primary Description
PMDES2_01.........varchar(50) ////Secondary Description

PRTNUM_01........PMDES1_01............PMDES2_01
100700..............Slide. .................6-inch
102121..............Video Card...........128MB
IPC4235-01........Chassis..............Parts
IPC4235-03........Chassis..............Parts
102128..............Riser................Card
102385..............Mother...............Board
801549..............Bracket,.............Power
801709..............Bracket..............Fan
100773..............Hardware.............Hinge

ProductStructure
PARPRT_02........varchar(30) ////Top Level Part Number
COMPRT_02......varchar(50) ////Component Part Number
EFFDTE_02.........smalldatetime //// Effective Date
QTYPER_02.........float ////// Quantity

PARPRT_02.............COMPRT_02..........EFFDTE_02....QTYPER_02
4235........................100700............2008-08-30.......1
4235........................102121............2007-08-30.......1
4235........................IPC4235-01......2008-05-20.......1
4235........................IPC4235-03......2007-08-30.......1
4235........................IPC4235-03......2008-05-20.......0
IPC4235-01...............102128............2007-11-19.......1
IPC4235-01...............102385............2007-11-19.......1
IPC4235-01...............801549............2007-11-19.......1
IPC4235-01...............801709............2008-04-01........1
IPC4235-01...............801709............2007-05-20........0
IPC4235-03...............100773............2007-09-20........1

--------What I am trying to accomplish is the retrieve the following:

PARPRT_02|COMPRT_02|Des|SubComp|Sub#|SubDes|EFFDTE_02|QTYPER_02
4235|100700|Slide 6-inch|n.a|n.a|n.a|2008-08-30|1
4235|102121|Video Card 128MB|n.a|n.a|n.a|2007-08-30|1
4235|IPC4235-01|Chassis Parts|IPC4235-01|102128|Riser Card|2007-11-19|1
4235|IPC4235-01|Chassis Parts|IPC4235-01|102385|Mother Board|2007-11-19|1
4235|IPC4235-01|ChassisParts|IPC4235-01|801549|Bracket,Power|2007-11-19|1


I have gotten Close but no cigar with the following:

SELECT ps.PARPRT_02,
ps.COMPRT_02,
pm.PMDES1_01 + ' ' + pm.PMDES2_01 as Description,
ISNULL(ps2.PARPRT_02, 'n.a.') AS [Sub Component],
ISNULL(ps2.COMPRT_02, 'n.a.') AS [Part Number of Sub],
ps.EFFDTE_02, ps.QTYPER_02
FROM ProductStructure ps
INNER JOIN
(SELECT COMPRT_02, MAX(EFFDTE_02) AS EFFDTE_02
FROM ProductStructure
WHERE (PARPRT_02 = '4235')
GROUP BY PARPRT_02, COMPRT_02) AS p3
ON ps.COMPRT_02 = p3.COMPRT_02 AND ps.EFFDTE_02 = p3.EFFDTE_02
Inner Join PartMaster AS pm On pm.PRTNUM_01 = ps.COMPRT_02
LEFT JOIN ProductStructure ps2
ON ps2.PARPRT_02 = ps.COMPRT_02
WHERE ps.PARPRT_02 = '4235'
ORDER BY
ps.PARPRT_02, ps.COMPRT_02

Which is returning:

PARPRT_02|COMPRT_02|Description|Sub Component|Part Number of Sub|EFFDTE_02|QTYPER_02
4235|100700|Slide 6-inch|n.a|n.a|2008-08-30|1
4235|102121|Video Card 128MB|n.a|n.a|2007-08-30|1
4235|IPC4235-01|Chassis Parts|IPC4235-01|102128|2008-05-20|1
4235|IPC4235-01|Chassis Parts|IPC4235-01|102385|2008-05-20|1
4235|IPC4235-01|Chassis Parts|IPC4235-01|801549|2008-05-20|1
4235|IPC4235-01|Chassis Parts|IPC4235-01|801709|2008-05-20|1
4235|IPC4235-01|Chassis Parts|IPC4235-01|801709|2008-05-20|1
4235|IPC4235-03|Chassis Parts|IPC4235-03|100773|2008-05-20|0

Line 1 - fine / Line 2 - fine / Line three (need to add description Part number of Sub)(need to keep original) / Line 4 and 5 same as line 3 / Line 6 and Line 7 should not show because the later date has a QTY of zero / Line 9 should not show because date is zero.

I once again appologize for the length and details on this , but this is has been driving me nutts. ANY help will be appreciated.

Thanks

View 8 Replies View Related







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