Union Two Tables With Relational Ordering / Grouping?

Jul 16, 2012

I have two tables with data that I need to get and display in a combobox. What I want to do is have the parent table listed in the combobox with all of its children indented. Sorted by parent then by child.

This SQL seems to be more complex than I have done previously

I can get all of the records from both tables easily:

Code:
SELECT strName, ID FROM tblParents as pp
INNER JOIN tblChildren as cc
ON cc.pID = pp.uiGUID
UNION (SELECT strName FROM tblChildren as c
INNER JOIN tblParents as p
ON c.pID = p.ID)

However, this simply returns a list that is not ordered in any fashion. I'd like to have all of the parent's children shown under the parent name (there is only 1 parent per child and multiple children per parent)

View 2 Replies


ADVERTISEMENT

Union Ordering

Sep 6, 2006

Hello,

I'm attempting to run three separate queries and have them returned as one recordset. I need to show the top 10 customers based on the number of orders they placed for each of three months, then combine them to give a representation of which customers have been within the monthly top 10 for the overall period of three months. My problem is when I run a count on the number of orders they have placed and order by that count, it is in ascending order which in escence shows me the bottom 10, not the top 10. To resolve this issue, I can specify descending order. This works fine with one query, but when I run all three queries using union statements, I can only have one order by which returns incorrect results. Here is my query. In this example, I get the combination of the three recordsets as expected, but each of the individual queries is not ordering descending, so I get the wrong end of the table. I am not bound to union, but do not know where to go. I do not believe I can use joins or concatenate queries because I have multiple where clauses. Any help would be greatly appreciated.

Please note that I am using a view to convert the cryptic field names which are used by a third party software tool into more friendly names. We will call this view Friendly_View for this example.

USE MyDB

SELECT TOP 10 CustName, Location, Phone, COUNT(Orders) AS TotalOrders
FROM Friendly_View
WHERE MONTH([Order Date]) = MONTH(GETDATE())-1 AND YEAR([Order Date]) = YEAR(GETDATE())
GROUP BY CustName, Location, Phone

UNION

SELECT TOP 10 CustName, Location, Phone, COUNT(Orders) AS TotalOrders
FROM Friendly_View
WHERE MONTH([Order Date]) = MONTH(GETDATE())-2 AND YEAR([Order Date]) = YEAR(GETDATE())
GROUP BY CustName, Location, Phone

UNION

SELECT TOP 10 CustName, Location, Phone, COUNT(Orders) AS TotalOrders
FROM Friendly_View
WHERE MONTH([Order Date]) = MONTH(GETDATE())-3 AND YEAR([Order Date]) = YEAR(GETDATE())
GROUP BY CustName, Location, Phone

ORDER BY COUNT(Orders) DESC

View 8 Replies View Related

Ordering, Grouping - HELP!

Jul 23, 2005

Having recently had excellent service here (many thanks, Erland!),here's another wee problem.SQL 2000I need to get a report which will display the movement of people thus:ID DIRECTION NAME DATE VEHICLE REGISTRATIONThe value of DIRECTION can be either "Inbound" or "Outbound"I need to have the data grouped by ID, with the "Outbound" row first.For example1 "Outbound" Smith 10/02/2005 ABC1231 "Inbound" Smith 11/02/2005 ABC1235 "Outbound" Jones 14/02/2005 XYZ7895 "Inbound" Jones 15/02/2005 DEF456This is the SQL so far.SELECTfldPersonID,tblMovementType.fldType AS [MovementType],'Outbound' AS [Direction],fldMovementDate AS [Date],CASE WHEN tblPerson.fldForenames IS NULLTHEN fldSurnameELSE fldSurname + ', ' + fldForenames END AS [Name],'Outbound ' + fldVehicleOut AS VehicleRegistrationFROMtblPersonINNER JOIN tblMovementTypeON tblMovementType.fldMovementTypeID = tblPerson.fldMovementTypeWHERE((fldMovementDate BETWEEN @FromDate AND @ToDate) AND(fldStatus = 1))UNION ALLSELECTfldPersonID,tblMovementType.fldType AS [MovementType],'Inbound' AS [Direction],fldMovementDate AS [Date],CASE WHEN tblPerson.fldForenames IS NULLTHEN fldSurnameELSE fldSurname + ', ' + fldForenames END AS [Name],'Inbound '+ fldVehicleRtn AS VehicleRegistrationFROMtblPersonINNER JOIN tblMovementTypeON tblMovementType.fldMovementTypeID = tblPerson.fldMovementTypeWHERE((fldMovementDate BETWEEN @FromDate AND @ToDate) AND(fldStatus = 1))What I need is the way to Order or Group it so that I can just put therows into a report without any grouping on the report itself (CrystalReports aarrggh!) - if this is possible!Edward--The reading group's reading group:http://www.bookgroup.org.ukThanks

View 1 Replies View Related

Grouping And Ordering Dates

Apr 20, 2000

Hello,
I am trying to solve this....when I run this query
select convert(varchar,date,100) from temp3
where date between convert(varchar,getdate() - 1.0,101) and
convert(varchar,getdate(),101)
result is:
Apr 19 2000 12:45PM
Apr 19 2000 12:46PM
Apr 19 2000 12:47PM
Apr 19 2000 12:48PM
Apr 19 2000 12:49PM
Apr 19 2000 12:49PM
Apr 19 2000 12:52PM
Apr 19 2000 12:53PM
Apr 19 2000 12:56PM
Apr 19 2000 12:57PM
Apr 19 2000 12:57PM
Apr 19 2000 12:58PM
Apr 19 2000 12:59PM
Apr 19 2000 12:59PM
Apr 19 2000 12:59PM
Apr 19 2000 12:59PM
Apr 19 2000 1:00PM
Apr 19 2000 1:01PM
Apr 19 2000 1:02PM
Apr 19 2000 1:02PM
Apr 19 2000 1:03PM
Apr 19 2000 1:04PM
Apr 19 2000 1:05PM
Apr 19 2000 1:06PM
Apr 19 2000 1:06PM
Apr 19 2000 1:10PM
Apr 19 2000 1:11PM
Apr 19 2000 1:11PM
this is what I am expecting. but when I try to group it

select convert(varchar,date,100) from temp3
where date between convert(varchar,getdate() - 1.0,101) and
convert(varchar,getdate(),101)
group by convert(varchar,date,100)

result is:
Apr 19 2000 1:00PM
Apr 19 2000 1:01PM
Apr 19 2000 1:02PM
Apr 19 2000 1:03PM
Apr 19 2000 1:04PM
Apr 19 2000 1:05PM
Apr 19 2000 1:06PM
Apr 19 2000 1:10PM
Apr 19 2000 1:11PM
Apr 19 2000 12:45PM
Apr 19 2000 12:46PM
Apr 19 2000 12:47PM
Apr 19 2000 12:48PM
Apr 19 2000 12:49PM
Apr 19 2000 12:52PM
Apr 19 2000 12:53PM
Apr 19 2000 12:56PM
Apr 19 2000 12:57PM
Apr 19 2000 12:58PM
Apr 19 2000 12:59PM

result is correct but I would like it to be displayed like
the first one. I will really appreciate Any clues,
suggestions, How to at this point. Thanks a lot.
HP

View 5 Replies View Related

Ordering A UNION Select With Subquery

Jun 26, 2006

I have a select such as this:

select COLUMNS from TABLE where WHERE_CLAUSE1
union
select COLUMNS from TABLE where WHERE_CLAUSE2

Now, I want to order the result set by COLUMNS. When I try the following query, the SQL fails.

select * from
(
select COLUMNS from TABLE where WHERE_CLAUSE1

union

select COLUMNS from TABLE where WHERE_CLAUSE2

) as T
order by COLUMNS

Any idea how this can be done?

Thanks

View 4 Replies View Related

Relational Tables Are Not Relational After Exported From My Sql Server To Host Sql Server

Dec 25, 2007

hello,
I am beginner for asp.net and sql server. I used Sql server manegement studio full version and I exported my aspnetdb which was created by VS2005 to my host sql server. I have a question: 
relational tables are not relational no longer. I noticed that when I created database diagram. what is wrong by exporting?
thanks for your helps...

View 3 Replies View Related

Designing Relational Tables

Sep 22, 2007

Hi, not sure if this is the right forum for this question.
 I am creating relational tables for the first time in sql server express. I will have an orderItems table and an orders table. the MenuItems table is the problem. It is a catalogue of books. There will be about ten columns. all are unique to each book. i.e isbn number, title, author, publisher etc. but ten columns seems to be quite cumbersome. it may be easier to break the table down into two tables (i.e. primary details and secondary details perhaps) However to populate the table in the first place it would be easier to have it as one table instead of opening and closing 2 tables Adding the odd book to the two tables in the future would not be a problem. so the question is can i create a table and then brak it into two relational tables afterwards. If so how do i do this. this is my foirst go at relational tables and i am still trying to get a handle on visualising them. If my logic is up the wall please let me know....
Nick

View 2 Replies View Related

Insert On Relational Tables

Apr 7, 2008

I understand the basics for doing an insert. Their seems to be many ways of achieving the same thing in .net. I have used the tableadpaters and sqlcommand functionality to achieve this. My one question is how foregin keys should be created in associated tables. EG so if i create a new record entry in one table and the primary key for that entry is a foreign key in another table, do I need to call 2 table adapters, or run 2 sqlcommands(taking the primary key from the first traction and use this in the next transaction)?

Any help or direction for some good tutorials on this would be much appreciated.

Thanks

Mark

View 4 Replies View Related

What Are The Properties Of The Relational Tables?

Mar 4, 2008



Hello friends .....What is the answer for this question in frame of SQL 2005 Management Studio or SQL Server 2000 ?

What are the properties of the Relational tables?

View 1 Replies View Related

Need To Insert Data Into 2 Tables, Relational Having Problems

Mar 7, 2007

Ok, I have a page on my website where we can add products to our database.  We are a music store, and most products have different versions or colors.  I've created 2 tables, Products and Subproducts.  The products table may hold info like Fender Stratocaster, and the subproducts would hold colors (Blue, Sunburst, etc).  The subproducts table has an integer field called MainProductID, which is linked to the mainproducts table field RecordID. So far the page uses a wizard where if first creates the main product using an sql datasource.  After the data has been added to the main products table, my page gives you the opportunity to add different sub products.  The problem I am having is actually feeding in the RecordID from the main products table to my insert parameter on the sub products data source.  This is what I have tried so far: There is a formview on the page that is bound to the main products table, after the entry is created I can physically see the info on my screen, so I know the data is there at my disposal SubProductsDataSource.InsertParameters.Add("@MainProductID", Formview1.datakey.item("RecordID"))SubProductsDataSource.Insert()Using this adds the data to the table, but the MainProductID is nullalso is there a cheap little way to refresh a page, because when I upload the product images I have it go to the next step where you are supposed to be able to see the images you uploaded, I don't see them which makes me think that the page is loading faster than the images are uploading.  Thanks   

View 1 Replies View Related

Insert/Update Relational Tables Using Dataadapter

May 2, 2008

Hi!

I am trying to insert data into 2 different tables. I am using dataadapter and dataset.

Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
Call ConnectionString()

Dim insertSQL As New SqlCommand()
insertSQL.Connection = sqlConn
insertSQL.CommandText = "SELECT location.CountryName, location.CityName, location.BuildingName, location.FloorID, rooms.name, rooms.FloorID AS Expr1 FROM location INNER JOIN floors ON location.FloorID = floors.id INNER JOIN rooms ON floors.id = rooms.FloorID"

Dim ds As New DataSet()
Dim da As New SqlDataAdapter()

da.SelectCommand = insertSQL
Dim scb As New SqlCommandBuilder(da)

Try
da.Fill(ds)
Dim ndr = ds.Tables("location").NewRow
Dim ndr2 = ds.Tables("rooms").NewRow

ndr("FloorID") = FloorIDDDL.SelectedValue
ndr("CountryName") = CountryNameTextBox.Text
ndr("CityName") = CityNameTextBox.Text
ndr("BuildingName") = BuildingNameTextBox.Text
ndr2("name") = RoomNameTextBox.Text
ndr2("FloorID") = FloorIDDDL.SelectedValue
ds.Tables("location").Rows.Add(ndr)
ds.Tables("room").Rows.Add(ndr2)
da.Update(ds)
ErrMsgLbl.Text = "Information saved successfully"
Catch ex As Exception
ErrMsgLbl.Text = ex.ToString
End Try

sqlConn.Close()
End Sub

The above code does not throw any error. It also does not update the tables.

Your help will be appreciated.

Thanks!

View 5 Replies View Related

Guidance Needed: Loading Hierarchical XML Into Relational Tables

Aug 8, 2007

I've got a lot of XML like this (simplified):




Code Snippet





... 8 MORE


... 9 MORE TIMES






I need to get this into three existing SQL Server 2005 tables, each with identity columns for their primary keys:




Code Snippet
CREATE TABLE ELEMENT1 (

[ID] INT IDENTITY
)

CREATE TABLE ELEMENT2 (

[ID] INT IDENTITY,
[ELEMENT1_ID] INT
)

CREATE TABLE ELEMENT3 (

[ID] INT IDENTITY,
[ELEMENT2_ID] INT
)





With primary and foreign keys as you'd expect, and, of course, many more columns!

How would I get this into tables through SSIS, preferably in a high-performance manner (there may be several gigabytes of XML to load).

The issue, of course, is that in order to insert an ELEMENT2 row, I need the ID from the coresponding ELEMENT1, etc.

Any ideas or pointers to articles would be welcome.

View 14 Replies View Related

SQL XML :: Shred To Relational Tables - Creating Foreign Keys

Oct 7, 2015

I'm shredding the below xml into relational tables. Each element of the xml has it's own table and there is a foreign key to join the tables, you can see this in the below picture. The process I follow is each relational table I always bring the nesecary xml and store it in the table and when shredding I always look at the parent table.So for example when processing the seat table, I use seat xml from the parent route table, also taking the ROUTEID from the route table. The reason I do this is all about taking the id from the previous step to create the relationships between the tables. without taking the xml down to the tables?The problem with this approach is I have xml stored in most tables and the tables are becoming very large.

<Route Type="OneWay" >
<Seat Type="FirstClass">
<Prices>
<Price Price="10" />
<Price Price="11" />
</Prices>

[code]....

View 4 Replies View Related

Load Ordering For Dimension And Fact Tables

Sep 22, 2006

Hi ,

I have situation where I get data from SRC Flat file and have to load Dimensional table and also fact table, using same data flow(have no other choice since I have to unpivot some src data). Since I have to load both tables in same data flow, I have to have a way to put load ordering constraint (I know informatica allows that). Does any one have any idea on how this can be done in SSIS?

I would be really grateful.

Thanks

View 3 Replies View Related

Create A Relational Diagram From Non-relational Database

Aug 4, 2005

Hi all,
I am trying to create a diagram for our database, during the creating, I create some of the relationships which were not there(basically our original database is not relational database, that's why I am doing it)
So sometimes I have to chage data type in order to create a relationship for the coloumns in different tables. i.e. change char(16) to varchar(7) (I checked the field that make sure all the data in this field is <= 7 characters)

But when I saved the diagram, there is an error message that state:
Errors were encountered during the save process. Some of your database objects are not saved on your diagram.

'agent' table saved successfully
'VisitUSA' table
- Unable to create relationship 'FK_VisitUSA_agent'.
ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]ALTER TABLE statement conflicted with COLUMN FOREIGN KEY constraint 'FK_VisitUSA_agent'. The conflict occurred in database 'CMC', table 'agent', column 'AgentCode'.

What does that mean? is it caused by some of the agentcode data in VisitUSA table which is not in agent table?
Thanks!
Betty

View 3 Replies View Related

Selecting Rows From Two Tables With JOIN And Ordering Problem

Dec 8, 2007



Hi,

First the environment: two tables A and B.

Table A: ID (unique-identifier)
Table B: ID_A (unique-identifier to A.ID, relation)

DTime (datetime)

Rows (id1 and id2 are Id examples):
A: id1
id2
B: id1 and 12:00:00 (date not important)
id1 and 13:00:00
id2 and 12:00:00

Example:
SELECT A.ID, B.DTIME
FROM A
LEFT JOIN B ON B.ID_A = A.ID
WHERE B.DTime < '14:00:00'
ORDER BY NEWID()

When I run this, I get the three rows of table B. But what I want is to get each table A row once, and get the nearest datetime of WHERE expression from the relation of table B.
So, the result must been two rows, id1 and id2, and id1 with '13:00:00' row because this is the nearest value of '14:00:00'.

How can I do this? DISTINCT trying by A.ID of SELECT, but doesn't work. Also ORDER BY B.DTime will work, but not random by NEWID() anymore.

Thank you.

View 3 Replies View Related

UNION OF 2 TABLES - CAN'T GET SUM

Sep 7, 2005

I am trying to get a consolidated sum of all the columns of the two tables that I am Using the UNION on. I can not get the sum function to work or the group by.




SELECT T2.State,t2.Taxcode,
Taxable =
Case
When T1.TaxCode <> 'exempt' and T1.TaxStatus = 'Y' then T1.LineTotal - ((T0.DiscPrcnt/100) * T1.LineTotal)
Else 0
End,
'NonTaxable' =
Case
When T1.TaxCode = 'exempt' or T1.TaxStatus = 'N' then T1.LineTotal + T1.DistribSum - ((T0.DiscPrcnt/100) * T1.LineTotal)
Else T1.DistribSum
End,
T1.VatSum as 'Total Tax', (T1.LineTotal + T1.DistribSum - ((T0.DiscPrcnt/100) * T1.LineTotal) + T1.Vatsum) as 'Line Total'
FROM inv1 t1 inner JOIN oinv t0 ON T0.DocEntry = T1.DocEntry inner join CRD1 T2 on T0.Cardcode = T2.CardCode
WHERE T0.DocDate >='[%1]' AND T0.DocDate <='[%2]' and t2.address = T0.shiptocode and t2.adrestype = 's'
UNION ALL
SELECT t2.state,t2.taxcode,
Taxable =
Case
When T1.TaxCode <> 'exempt' and T1.TaxStatus = 'Y' then -(T1.LineTotal - ((T0.DiscPrcnt/100) * T1.LineTotal))
Else 0
End,
'NonTaxable' =
Case
When T1.TaxCode = 'exempt' or T1.TaxStatus = 'N' then -(T1.LineTotal + T1.DistribSum - ((T0.DiscPrcnt/100) * T1.LineTotal))
Else T1.DistribSum
End,
-T1.VatSum as 'Total Tax', -(T1.LineTotal + T1.DistribSum - ((T0.DiscPrcnt/100) * T1.LineTotal) + T1.Vatsum) as 'Line Total'
FROM RIN1 t1 inner JOIN ORIN t0 ON T0.DocEntry = T1.DocEntry inner join CRD1 T2 on T0.Cardcode = T2.CardCode
WHERE T0.DocDate >='[%1]' AND T0.DocDate <='[%2]' and t2.address = T0.shiptocode and t2.adrestype = 's'
order by T2.STATE

View 2 Replies View Related

Union And Join With Three Tables

Sep 17, 2007

Hi,
I have three tables named as BroadCastetails,PaymetMaster,MemberMaster.
 I have two query as mentioned below--
SELECT MemberMaster.FirstName, MemberMaster.LastName, BroadCastDetails.BroadCastName FROM BroadCastDetails INNER JOIN MemberMaster ON 5 = MemberMaster.MemberID AND BroadcastCreationDateTime between '01/01/2007' AND '12/12/2007'
SELECT BroadCastDetails.ScheduledStartDateTime, BroadCastDetails.TotalCalls FROM BroadCastDetails UNION SELECT PaymentTransaction.TransactionDate, PaymentTransaction.CallsToCredit FROM PaymentTransaction
 
I want the result of the above two query in a GridView.How can I do that ? Its urgent...

View 2 Replies View Related

Join Or Union Two Tables?

Nov 18, 2003

Hi,

I have an Orders Table and a Freeshipping Table.


ORDERS
======

CustomerId OrderDate Quantity
========== ========= ========
1000 01/01/2003 5
1000 01/04/2003 9
1000 01/08/2003 14
2000 01/01/2003 4
1000 06/03/2003 9
4000 05/02/2003 4


FREESHIPPING
=============

CustomerID FreeDate
========== ========
1000 01/01/2003
1000 01/03/2003


How can I write a query that will return the following result to show the order details for customerid 1000
for a date range between 01/01/2003 and 01/08/2003


OrderDate Quantity FreeShipping
========= ======== ============
01/01/2003 5 Y
01/03/2003 0 Y
01/04/2003 9 N
01/08/2003 14 N


Note that even if an order was not placed and the date was a freeshipping date, it is still displayed in the resultset

Thanks in advance,
-ron

View 2 Replies View Related

SQL 2000 2 Tables Using UNION

Mar 27, 2006

I have 2 Tables one called Reps and the other called STORES
I need to use a UNION statement but my Server is saying that the "UNION" is ERROR The Query Designer does not support the UNION SQL construct.

What command would I use to put these 2 tables together?
HELP!

View 5 Replies View Related

Union 2 Temp Tables

Nov 8, 2007

I have 2 temporary tables from a previous operation, Tab1 and Tab2, with the same dimensions. How do I create a third table Tab3 with the same dimensions containing the the combined rows of the 2 previous tables? TIA!

Tab1
Col1 Col2 Col3
A1 B1 C1
A2 B2 C2

Tab2
Col1 Col2 Col3
X1 Y1 Z1
X2 Y2 Z2
X3 Y3 Z3

After the required sql operation I should have

Tab3
Col1 Col2 Col3
A1 B1 C1
A2 B2 C2
X1 Y1 Z1
X2 Y2 Z2
X3 Y3 Z3

View 7 Replies View Related

WHERE Command On UNION Tables

Feb 19, 2008

Hi there, I have some identical tables that I want to query for a search Is there anyway I can execute the unions first then a where command on all the tables at once I have tried using go but it doesn't seem to work, so I put the where statemtents at the end of each union for now. Here's my code:


strSQL = "SELECT * FROM england WHERE company LIKE '%" & iKeyword & "%' OR address1 LIKE '%" & iKeyword & "%' OR address2 LIKE '%" & iKeyword & "%' OR address3 LIKE '%" & iKeyword & "%' OR address4 LIKE '%" & iKeyword & "%' OR address5 LIKE '%" & iKeyword & "%' OR postcode LIKE '%" & iKeyword & "%' " &_
"UNION ALL SELECT * FROM ni WHERE company LIKE '%" & iKeyword & "%' OR address1 LIKE '%" & iKeyword & "%' OR address2 LIKE '%" & iKeyword & "%' OR address3 LIKE '%" & iKeyword & "%' OR address4 LIKE '%" & iKeyword & "%' OR address5 LIKE '%" & iKeyword & "%' OR postcode LIKE '%" & iKeyword & "%' " &_
"UNION ALL SELECT * FROM wales WHERE company LIKE '%" & iKeyword & "%' OR address1 LIKE '%" & iKeyword & "%' OR address2 LIKE '%" & iKeyword & "%' OR address3 LIKE '%" & iKeyword & "%' OR address4 LIKE '%" & iKeyword & "%' OR address5 LIKE '%" & iKeyword & "%' OR postcode LIKE '%" & iKeyword & "%' " &_
"UNION ALL SELECT * FROM scotland WHERE company LIKE '%" & iKeyword & "%' OR address1 LIKE '%" & iKeyword & "%' OR address2 LIKE '%" & iKeyword & "%' OR address3 LIKE '%" & iKeyword & "%' OR address4 LIKE '%" & iKeyword & "%' OR address5 LIKE '%" & iKeyword & "%' OR postcode LIKE '%" & iKeyword & "%'"

View 15 Replies View Related

Merging Two Tables Then Grouping Them

Feb 14, 2005

I have two tables, one is named Employee and the other Job_title. I'm trying to combine the two tables so I can group certain columns.

This is what I thought of so far and please correct me if I'm wrong.

SELECT Last_name FROM Employee
UNION
SELECT Job_title_code FROM Job_title
GROUP BY Exempt_non_exempt
FROM Job_title

Now this is just a theory (obviously it doesn't work) but basiclly I'm trying to have columns from two tables and have the grouped.

View 6 Replies View Related

Order By In Union - Data In 2 Tables

Feb 10, 2015

This query works perfectly and orders by just as I need

Code:
Select
'1st' As [Type],
#Uno.ID
#Uno.Address,
#Uno.shippingInfo
FROM #Uno

[Code] ....

However, when I use it in a Union All so I can pull data from 2 diff tables, the order by statement no longer works. How can I order by data in 2 tables?

Code:
Select
'1st' As [Type],
#Uno.ID
#Uno.Address,
#Uno.shippingInfo
FROM #Uno

[Code] ....

View 1 Replies View Related

CTE - Union Hierarchy Tables By More Roots ID

Oct 4, 2013

I try to build some query on hierarchy data and after two days thinking about it i have null result. What I need is union more trees tables by root id to one table.

-- tree
-- this query is functional: OK
WITH tree (sid, parend_id, level) as
(
SELECT sid, parend_id, 0 as level

[Code] ....

But this query work with one root id (100); what can i do when i have more roots id ? -> generate each tree table separated by roots id and then all tables join to one (union).

View 1 Replies View Related

UNION 2 Tables Horizontally, To One Table

Aug 5, 2007

Is it possible to combine the following tables:

Table1:
id
1
2
3

Table2:
licenses
3
2
1


To one table, like this:

id licenses
1 3
2 2
3 1

-There is always the same number of rows in both tables.

Thanks a lot!

View 9 Replies View Related

Using Union All When Inerting Into Temp Tables

Oct 4, 2007

Hello,
I'm using SQL2005, SP2

I have multiple temp tables with the same column structure that I would combine into into a single temp table using Unions.
Is this possible?

Example:
Select * From #temp1
Union All
Select * From #temp2
Union All
Select * From #temp3

Into #Temp4


I thought I would ask while I continue to research this in case someone came back with the solution before I was able to track it down elsewhere.


Thanks!

View 1 Replies View Related

Standard Way To Union Tables In Different Databases?

Oct 17, 2007

What is the standard way to union tables with exactly the same schema that are in different databases?

For example:





Code Block

USE db1 SELECT * FROM table1
UNION
USE db2 SELECT * FROM table2

this will return the following error:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'use'.

View 3 Replies View Related

Join 2 Tables And Grouping Problem

Aug 4, 2005

Hello Everyone,

I have two tables
1.) Agenda
AgendaID, Agenda_Title, Agenda_ConfCode

2.)SubAgenda
subAgendaID, subAgenda_AgendaID, subAgenda_Title

Basically I need the sub agenda to display underneath its Agenda Title, based on AgendaID = subAgenda_AgendaID...but when i loop over the query, it displays the agenda as many times as the sub agenda. I Think i need to group it somehow, or use a nested select?

The output should look like this:

Agenda1
SubAgenda 1
SubAgenda 2
SubAgenda 3

Agenda 2
SubAgenda 1
SubAgenda 2

BUT this is what I Get

Agenda 1
SubAgenda 1
Agenda 1
SubAgenda 2
etc...

Please help!
Thanks.

View 3 Replies View Related

Aggregate SUM From Multiple Tables And Grouping

Oct 5, 2012

I have several tables that I need to summarize data from two tables based upon a dates passed in and group that data. I have attached my table layout, some sample data, and how I would like the results to look.

View 2 Replies View Related

Transact SQL :: Sum Values By Grouping Name From Two Tables

Nov 6, 2015

I have two tbles that have ItemName and their bill amount

a) tblLunch

which shows records like below

Invoice   Item                          Amount  
--------------------------------------------
1             COFFEE                       1000.00 
2             TEA                          2000.00
3             ICE CREAM                1000.00

b) tblDinner

which shows records like below

Invoice   Item                      Amount  
------------------------------------------------------------
1             COFFEE                  1000.00 
2             TEA                        2000.00
3             PASTA         1000.00

I want to perform a query that should SUM Amount Columns by Grouping the Item from both the tables, so we could get the following result

Item                      Amount  
------------------------------
COFFEE                  2000.00 
TEA                        4000.00
ICE CREAM           1000.00
PASTA                    1000.00

View 3 Replies View Related

Union Of 2 Tables With Differnt Number Of Rows

May 24, 2006

I have 2 tables

tblOpenSiteDates
Site: int
OpenDate: smalldate
Comment: VarChar


tblCloseSiteDates
Site: int
CloseDate: smalldate
Comments: VarChar
newLocationID: int

I am trying to get a view which would display a site with the open and close dates. Null is ok for a close date for those opens that are still open.. not every office has an open date and close date.. it is possible to have just a close date and not an open date (ie unsure of open date but I know its closing)

so the output would be

viewOpenCloseSites
Site: int
opendate: smalldate
closedate: smalldate

PLEASE HELP i just can not figure it out

thanks...

View 1 Replies View Related

Query Multiple Tables - Union/Order By

Oct 25, 2007

Hi!

I'm trying to get the results from three different tables, where they have some of the same results. I'm only interested in where they match and then trying to order by date (that's in three columns - M, D, Y). I read previous post in 9/07 but the result doesn't seem to order correctly. It does not have any rhyme or reason to the outputed results as it bounces back and forth through Oct, Nov and Dec posting and throughout all three tables. Here's my query below. Any ideas how I can get my ordering correct for all three tables to display all Oct, all Nov and all Dec?

Thanks so much

select date3, date2, date1, who, what
from
(
select date3, date2, date1, who, what from shows
union
select date3, date2, date1, who, what from shares
union
select date3, date2, date1, who, what from soiree
)
a order by date3, date2, date1

View 4 Replies View Related







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