T-SQL (SS2K8) :: Union Of Two Tables Returned Back To Main Query
Aug 18, 2014
Currently I have a standard query with a join to several tables. There are two additional tables MAS_CTB and MAS_STB. I would like to do a union between those two tables to get FIELDVALUE which will exist in either the CTB table or the STB table and then have that value be returned with the results of the original query.
I can of course write a UNION from the main query to the CTB and then to the STB table, however it's about 80 dummy fields I would have to replicate in the union which is why I was wondering if there was a more simple way.
Main Query:
SELECT Field1, Field2...Field80
From Table1
Join Table2
Union Portion:
Select FieldValue <------
From MAS_CTB
UNION
Select FieldValue <-----Return to main query above
From MAS_STB
View 3 Replies
ADVERTISEMENT
Mar 30, 2004
hi all
Any day, another question. I love you guys.
I want to select a subset of data from a dataset returned by either another subquery or a union.
e.g. this is how i would do it in oracle, but i have no idea how this can be done in mssql or whether it's possible at all.
select * from
(
select col1, col2, col3 from table1
union
select col1, col2, col3 from table 2
)
where col1 = 'blah'
in essence oracle treats the data returned by the subquery as a table that it would select from.
how would i do the same in mssql?
thank you
James :)
View 5 Replies
View Related
Nov 2, 2014
Team members appear twice or more if they belong to more than one team. I need to be able to show their name and main team. Team is not important at the moment but I just like to include all team members and display a team name against them.This is what I have at the moment:
SELECT SystemUser.systemuserid, FullName, TeamMembership.TeamID, TeamName
FROM Team
RIGHT OUTER JOIN TeamMembership ON Team.teamid = TeamMembership.teamid
LEFT OUTER JOIN SystemUser ON TeamMembership.systemuserid = SystemUser.systemuserid
order by FullName
View 3 Replies
View Related
Jun 12, 2014
SQL Server 2008 r2...
I have a query which does 3 selects and Union ALLs each to get a final result set. The performance is unacceptable - takes around a minute to run. If I remove the Union All so that the result sets are returned individually it returns all 3 from the query in around 6 seconds (acceptable performance).
Any way to join the result sets together without using Union All.
Each result set has exactly the same structure returned...
Query below [for reference]...
WITH cte AS (
SELECT A.[PoleID], ISNULL(B.[IsSpanClear], 0) AS [IsSpanClear], B.[SurveyDate], ROW_NUMBER() OVER (PARTITION BY A.[PoleID] ORDER BY B.[SurveyDate] DESC) rownum
FROM[UT_Pole] A
LEFT OUTER JOIN [UT_Surveyed_Pole] B ON A.[PoleID] = B.[PoleID]
[Code] .....
View 4 Replies
View Related
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
Jun 20, 2006
I have a strange problem. I have some code that executes a sql query. If I run the query in SQL server query analyzer, I get a set of data returned for me as expected. This is the query listed on lines 3 and 4. I just manually type it into query analyzer.
Yet when I run the same query in my code, the result set is slightly different because it is missing some data. I am confused as to what is going on here. Basically to examine the sql result set returned, I write it out to an XML file. (See line 16).
Why the data returned is different, I have no idea. Also writing it out to an XML file is the only way I can look at the data. Otherwise looking at it in the debugger is impossible, with the hundreds of tree nodes returned.
If someone is able to help me figure this out, I would appreciate it.
1. public DataSet GetMarketList(string region, string marketRegion)2. {3. string sql = @"SELECT a.RealEstMarket FROM MarketMap a, RegionMap b " + 4."WHERE a.RegionCode = b.RegionCode"; 5. DataSet dsMarketList = new DataSet();6. SqlConnection sqlConn = new SqlConnection(intranetConnStr); 7. SqlCommand cmd = new SqlCommand(sql,sqlConn);8. sqlConn.Open();9. SqlDataAdapter adapter = new SqlDataAdapter(cmd); 10. try11. {12. adapter.Fill(dsMarketList);
13. String bling = adapter.SelectCommand.CommandText;//BRG 14. dsMarketList.DataSetName="RegionMarket"; 15. dsMarketList.Tables[0].TableName = "MarketList"; 16. dsMarketList.WriteXml(Server.MapPath ("myXMLFile.xml" )); // The data written to 17. myXMLFile.xml is not the same data that is returned when I run the query on line 3&4 18. // from the SQL query 19. } 20. catch(Exception e) 21. { 22. // Handle the exception (Code not shown)
View 2 Replies
View Related
Sep 17, 2015
Table 1 has "Gender" field with "Male" and "Female" in it, table 2 has "Gender" field with "M" and "F" in it. a query to compare data and list the differences.
View 4 Replies
View Related
Oct 12, 2014
I get a red squiggle below the first IF statement. Can't figure out the correct syntax.
UNION ALL
IF ((SELECT Flexpool FROM Huizen WHERE IDHuis = @LOCATIECODE ) = 'WAAR')
SELECTM.LOCATIECODE, M.AfdelingZPT, DATEPART(ISO_WEEK, M.Begindatum) wk, M.DienstGroep, NULL Leeg, NULL Leeg, SUM(M.Hrs) AS Uren
FROMDRPHrsManual M
[Code] ....
View 2 Replies
View Related
Mar 19, 2014
I have three tables EmpIDs,EmpRoles and LatestRoles. I need to write a select Query to get roles of all employees present in EmpIDs table by referring EmpRoles and LatestRoles.
Where I stuck : The condition is first look into table EmpRoles and if it has more than one entry for a particular Employee ID than only need to get the Role from LatestRoles other wise consider the role from EmpRoles .
Example:
Create Table #EmpIDs (
EmplID int
)
Create Table #EmpRoles (
EMPID int,
[Code] ....
Employee ID 2 is having two roles defined in EmpRoles so for EmpID 2 need to fetch Role from LatestRoles table and for remaining ID's need to fetch from EmpRoles .
My Final Output of select query should be like below.
EmpID Role
1 Role1
2 Role2
3 Role1
View 5 Replies
View Related
May 8, 2014
I want to query my msdb job and jobschedule related tables to generate a list of runtimes for each of these jobs for the next day or any future date. This query should output JobID, Run_Date(YYYYMMDD), and Run_Time(HHMMSS).
If I have 3 jobs with...
Job#1 scheduled to run once every 4 hours between 6 AM and 10 PM
Job# 2 scheduled to run every 15 minutes between 11 AM and 1 PM
Job# 3 scheduled to run every minute between 4 PM and 4:15 PM
my output should look as below ....
View 1 Replies
View Related
Apr 4, 2014
In this selection when there is particular segment found in the selection then need to add 2 records per segment otherwise just selected results
--Drop table #list
CREATE TABLE #LIST ( email varchar(20),Segment varchar(20), Addr1 varchar(20), City varchar(20),ST varchar(20), Code int)
--Drop table #subject
CREATE TABLE #Subject (Segment varchar(20), Fname varchar(20), LName varchar(20))
[Code] ....
---Selection results
SELECT L.Segment , l.email, l.Addr1 , l.City ,l.ST, l.code, s.Fname , s.LName into #expectedresult FROM #LIST L JOIN #Subject S ON l.Segment =s.Segment
--Now here what i am trying to get, union the below two record to the above "selection Results" for only segment ='VEC_BAL' or segment = 'PPC_BAL'
--2 records
SELECT l.segment , l.email , Addr1, City, ST, 999 as Code,'' fname, ''lname from #LIST l where email ='mmm@m.com'
SELECT l.segment , l.email , Addr1, City, ST, 888 as Code, '' fname, ''lname from #LIST l where email ='lrk@m.com'
--- expected results please execute below block ( per each segment 2 records will insert if there is segment ='VEC_BAL' or 'PPC_BAL' ). If there is no Vec_Bal or PPC BAL then no additional inserts, if there is only VEC_BAL no PPC_BAL then only 2 records insert
SELECT L.Segment , l.email, l.Addr1 , l.City ,l.ST, l.code, s.Fname , s.LName into #expctresults1 FROM #LIST L JOIN #Subject S ON l.Segment =s.Segment
union
[Code] .....
View 3 Replies
View Related
Sep 12, 2014
How I can measure the volume of data created temporarily to replace usage of physical tables in an SQL query.
View 1 Replies
View Related
Nov 22, 2007
What we've found is that when you have two reports where one navigates to the other, if you click on the second page of the second report, it takes you to the second page of the original report. If you navigate over to the subreport again and click for the second page, it works appropriately. This is definitely a no-go for production code and this may delay our ship date because I would think this is definitely undesirable.
Conditions:
ASP.NET Report Viewer using Remote Reports
Report that links to another report
Both reports return more than one page
Reporting Services installed
Steps to Reproduce:
Download the source code here.
Follow the directions (near the bottom of the post) to get the project set up.
Run it and click on a link in the first report to go to the second report.
Click the arrow for page 2 of the second report.
Notice how it takes you back to page 2 of the first report (this doesn't happen when you are in preview mode in the Reporting Services project and I don't believe it does this in a smart client application).
Click on a link in the first report to go back to the second report.
Click the arrow for page 2.
Notice how it takes you to page 2 of the second report.
Here is a link with source code and a more detailed explanation: http://geekswithblogs.net/robz/archive/2007/11/21/Reporting-Services-2005-BUG-Report-Linking-and-Paging---ASP.NET.aspx
So what I am looking for is both a workaround for now and if this is determined to be a bug, to be fixed in the next service pack.
View 6 Replies
View Related
May 22, 2008
I have a query that gets a supplier, a month, a year, status and sum of recpits.
returning the following. but my problem is I also need a col of totals. i tried to put a sub grouped query
in the select statement but keep getting an error
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
AR162600 ARROW ELECTRONICS 10424 Early 1 2008 2007-12-31 23:59:59.997
AR162600 ARROW ELECTRONICS 516 Late 1 2008 2007-12-31 23:59:59.997
AR162600 ARROW ELECTRONICS 279603 On-Time 1 2008 2007-12-31 23:59:59.997
my qurey is below. how can I get another col called total it will be the same value on each row.
AR162600 ARROW ELECTRONICS 10424 290543 Early 1 2008 2007-12-31 23:59:59.997
AR162600 ARROW ELECTRONICS 516 290543 Late 1 2008 2007-12-31 23:59:59.997
AR162600 ARROW ELECTRONICS 279603 290543 On-Time 1 2008 2007-12-31 23:59:59.997
SELECT ot_ven_num, ot_ven_name, sum(ot_rec_qty) as ot_rec_qty,
ot_rec_stat, datepart(Month,ot_rec_dt) as mth,
datepart(year,ot_rec_dt) as ryear,
DATEADD(ms, - 3, DATEADD(mm, DATEDIFF(mm, 0, ot_rec_dt), 0)) as ot_rpt_date,
(SELECT ot_ven_num, ot_ven_name, sum(ot_rec_qty) as ot_rec_qty, 'Totals' as ot_rec_stat,
datepart(Month,ot_rec_dt) as mth,
datepart(year,ot_rec_dt) as ryear,
DATEADD(ms, - 3, DATEADD(mm, DATEDIFF(mm, 0, ot_rec_dt), 0)) as ot_rpt_date
FROM supplierOT where ot_ven_name = 'ARROW ELECTRONICS' and datepart(year,ot_rec_dt) > 2007
group by ot_ven_num, ot_ven_name, DATEADD(ms, - 3, DATEADD(mm, DATEDIFF(mm, 0, ot_rec_dt), 0)),
datepart(Month,ot_rec_dt),
datepart(year,ot_rec_dt)) as total
FROM supplierOT where ot_ven_name = 'ARROW ELECTRONICS' and datepart(year,ot_rec_dt) > 2007
group by ot_ven_num, ot_ven_name, ot_rec_stat, DATEADD(ms, - 3, DATEADD(mm, DATEDIFF(mm, 0, ot_rec_dt), 0)),
datepart(Month,ot_rec_dt),
datepart(year,ot_rec_dt)
View 9 Replies
View Related
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
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
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
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
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
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
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
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
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
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
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
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
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
View Related
Apr 2, 2008
I have got the following union statement:
SELECT plan2008.jahr, plan2008.monat, plan2008.kdkrbez, plan2008.kdgrbez, plan2008.abgrbez, plan2008.artnr,
FROM plan2008
GROUP BY plan2008.jahr, plan2008.monat, plan2008.kdkrbez, plan2008.kdgrbez, plan2008.abgrbez, plan2008.artnr
UNION
SELECT fsp_auftrag.jahr, fsp_auftrag.monatnr, fsp_auftrag.kundenkreis, fsp_auftrag.kundengruppe, fsp_auftrag.abnehmergruppe, fsp_auftrag.artnr
FROM fsp_auftrag
GROUP BY fsp_auftrag.jahr, fsp_auftrag.monatnr, fsp_auftrag.kundenkreis, fsp_auftrag.kundengruppe, fsp_auftrag.abnehmergruppe, fsp_auftrag.artnr
My problem is that each table contains additional values like art_amount, art_turnover etc... whereby the first table contains plan values while the second table contains actual values.
My goal is to get plan as well as the actual values in one row, how is that possible? If I put the values into each of the selects I get two rows, which is not the wished output.
Is it possible to join the tables after the union took place?
Thanks in advance!
View 8 Replies
View Related
Apr 1, 2008
HI, Guys:
I've some AT_DATE tables (eg: AT_20080401, AT_20080402, ...) in SQLServer DB, and these AT_XX table have same columns. but table count could be variant, so I have to query sysobjects to get all of these tables. like this:
select name from sysobject where name like 'AT_%'
Now I try to create a view AT which is the union of all these AT_XX tables, such as:
Code Snippet
Create View AT as
select * from AT_20080401
union
select * from AT_20080402
union ...
but since I'm not sure how many tables there, it would be impossible to write SQL as above.
though I could get this union result via stored-procedure, view couldn't be created on the resultset of a procedure.
Create View AT as
select * from AT_createView() <-- AT_createView must be a function, not procedure
I've checked msdn, there is Multi-statement table-valued function, but this function type seems to create one temporary table, I don't want to involve much of insert operation because there could be more than 1million records totally in these AT_XX tables.
So is there any way to achived my goal?
any reference would be appreciated, thanks !
View 8 Replies
View Related
Feb 18, 2008
I'm trying to summarize costs assigned to active jobs for a manufacturing business. I need to aggregate work in process (WIP) cost that resides in labor-transaction and part-transaction tables based on transaction types, and transaction dates. Some transactions increase the WIP cost of the job while others decrease WIP. The business needs to see how much $$ is tied up in each job as of a particular date -- the calculation is:
ToDate (cost of materials and labor assigned to job)
- ToInv (cost of materials returned to inventory)
- ToSales (cost of materials sold).
I developed this query incrementally and, so far, the #ToDate, #ToInv, and #ToSales temp tables seem to be populating with the correct data. My thought was to combine these three tables with a UNION and then extract the grand totals and here's where I started getting the following error:
------------------------------------------
Incorrect syntax near the keyword 'UNION'.
------------------------------------------
The problem is with the UNIONs going into #myTotal.
I would appreciate any help with this. Also, please let me know if you can suggest a better design for this. Thanks!
Below is a simplified version of my query:
--#ToDate
CREATE TABLE #ToDate (JobNum varchar(14), Cost decimal (16,2)
INSERT INTO #ToDate (JobNum, Cost)
--M&S To Date
SELECT pt.jobnum,
SUM(pt.extcost) AS Cost
FROM parttran pt
JOIN jobhead jh ON pt.jobnum=jh.jobnum
WHERE trantype IN ( <valid trans types> )
AND jh.JobReleased = 1
AND pt.TranDate < '2007-9-30'
GROUP BY pt.jobnum
UNION -- This one works ok.
--L&B To Date
SELECT jh.JobNum,
sum(l.LaborRate*l.LaborHrs) + sum(l.BurdenRate*l.BurdenHrs) AS Cost
FROM LaborDtl l
JOIN JobHead jh ON l.JobNum = jh.JobNum
WHERE jh.JobReleased = 1
AND l.PayrollDate < '2007-9-30'
GROUP BY jh.JobNum
--#ToInv
CREATE TABLE #ToInv (JobNum varchar(14), Cost decimal (16,2)
INSERT INTO #ToInv (JobNum, Cost)
SELECT pt.jobnum,
SUM(pt.extcost) AS ToInv
FROM parttran pt
JOIN jobhead jh ON pt.jobnum=jh.jobnum
WHERE trantype IN (<valid trans types>)
AND jh.JobReleased = 1
AND pt.TranDate < '2007-9-30'
GROUP BY pt.jobnum
--#ToSales
CREATE TABLE #ToSales (JobNum varchar(14), Cost decimal (16,2))
INSERT INTO #ToSales (JobNum, Cost)
SELECT pt.jobnum,
SUM(pt.extcost) AS ToInv
FROM parttran pt
JOIN jobhead jh ON pt.jobnum=jh.jobnum
WHERE trantype IN (<valid trans types>)
AND jh.JobReleased = 1
AND pt.TranDate < '2007-9-30'
GROUP BY pt.jobnum
--#myTotal
CREATE TABLE #myTotal (JobNum varchar(14), Cost decimal (16,2), Source varchar(9))
INSERT INTO #myTotal (JobNum, Cost, Source)
SELECT d.JobNum, SUM(d.Cost) AS Cost FROM #ToDate d GROUP BY d.JobNum ORDER BY d.JobNum
UNION -- Problem**********************
SELECT i.JobNum, SUM(-1*i.Cost) AS Cost FROM #ToInv i GROUP BY i.JobNum ORDER BY i.JobNum
UNION -- Problem**********************
SELECT s.JobNum, SUM(-1*s.Cost) AS Cost FROM #ToSales s GROUP BY s.JobNum ORDER BY s.JobNum
--Select grand total for each job
SELECT JobNum, SUM(Cost) FROM #myTotal ORDER BY JobNum
--Drop temp tables
DROP TABLE #ToDate
DROP TABLE #ToInv
DROP TABLE #ToSales
DROP TABLE #myTotal
View 3 Replies
View Related
Oct 30, 2006
I have successfully execute a union query. How can i create a make-table query to accomodate the resultset of the union query?
View 2 Replies
View Related
Jan 29, 2007
Hi,
I backed my sql server database on Fri at 3:15pm and then tried importing some tables individually from a different database and but that didnt work out too good, so is there a way i can just restore particular tables from the backup.
any help will be appreciated.
regards,
Karen
View 4 Replies
View Related
Sep 26, 2006
ok. the problem: some tables are empty, so i can't be sure why some are updating at the DB and some arent.
I have manually picked thru every line of the xml that i'm reading into the dataset here, and it is fine, data is all valid and everything.
the tables i'm most worried about are bulletins and surveys, but they all have to be imported from my upload, the code steps thru just fine and I've been thru it a million times. Did I miss something in my dataadapter configuration?. 'daBulletin ' Me.daBulletin.ContinueUpdateOnError = True Me.daBulletin.DeleteCommand = Me.SqlDeleteCommand17 Me.daBulletin.InsertCommand = Me.SqlInsertCommand17 Me.daBulletin.SelectCommand = Me.SqlSelectCommand25 Me.daBulletin.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "tblBulletin", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("BulletinID", "BulletinID"), New System.Data.Common.DataColumnMapping("ContractID", "ContractID"), New System.Data.Common.DataColumnMapping("Msg_Type", "Msg_Type"), New System.Data.Common.DataColumnMapping("DatePosted", "DatePosted"), New System.Data.Common.DataColumnMapping("Subject", "Subject"), New System.Data.Common.DataColumnMapping("B_Body", "B_Body"), New System.Data.Common.DataColumnMapping("I_Read_It", "I_Read_It"), New System.Data.Common.DataColumnMapping("DateRead", "DateRead")})}) Me.daBulletin.UpdateCommand = Me.SqlUpdateCommand16
here is my merge function: Private Function Merge(ByVal sFilename As String, ByVal User As String) As String
Dim connMerge As New SqlConnection(ConnectionString)
Dim dsNew As New dsBeetleTracks
Dim dsExisting As New dsBeetleTracks
Dim strResult As String
SetConnections(connMerge)
Dim idc As New System.Security.Principal.GenericIdentity(User)
Dim currentUser As BeetleUser = bu
dsNew.ReadXml(sFilename)
If currentUser.IsInRole("Admin") Or currentUser.IsInRole("QA") Then
If dsNew.tblBulletin.Count > 0 Then
daBulletin.Fill(dsExisting.tblBulletin)
dsExisting.Merge(dsNew.tblBulletin)
strResult += daHelipads.Update(dsExisting.tblBulletin).ToString + " Bulletins updated<br>"
End If
End If
If dsNew.tblHours.Count > 0 And (currentUser.IsInRole("Survey") Or currentUser.IsInRole("Admin")) Then
daHours.Fill(dsExisting.tblHours)
dsExisting.Merge(dsNew.tblHours)
strResult += daHours.Update(dsExisting.tblHours).ToString + " hours updated<br>"
End If
If dsNew.tblHeliPads.Count > 0 Then
daHelipads.Fill(dsExisting.tblHeliPads)
dsExisting.Merge(dsNew.tblHeliPads)
strResult += daHelipads.Update(dsExisting.tblHeliPads).ToString & " helipads updated "
End If
If dsNew.tblExpenses.Count > 0 Then
daExpenses.Fill(dsExisting.tblExpenses)
dsExisting.Merge(dsNew.tblExpenses)
strResult += daExpenses.Update(dsExisting.tblExpenses).ToString + " expenses updated<br>"
End If
If dsNew.tblPersons.Count > 0 And (currentUser.IsInRole("Survey") Or currentUser.IsInRole("FB") Or currentUser.IsInRole("Heli-burn")) Then
daPersons.Fill(dsExisting.tblPersons)
dsExisting.Merge(dsNew.tblPersons)
strResult += daPersons.Update(dsExisting.tblPersons).ToString + " persons updated<br>"
End If
If currentUser.IsInRole("Field") Then
daSurveys.SelectCommand.CommandText = "exec Surveys_Field_Select"
daSurveys.InsertCommand.CommandText = "exec Surveys_Field_Insert"
daSurveys.UpdateCommand.CommandText = "exec Surveys_Field_Update"
End If
If dsNew.tblSurveys.Count > 0 And (currentUser.IsInRole("Survey") Or currentUser.IsInRole("Field")) Then ' Or CurrentUser.IsInRole("Admin")) Then
daSurveys.Fill(dsExisting.tblSurveys)
dsExisting.Merge(dsNew.tblSurveys)
strResult += daSurveys.Update(dsExisting.tblSurveys).ToString + " surveys updated<br>"
End If
If dsNew.tblSurveyChecks.Count > 0 And (currentUser.IsInRole("QA") Or currentUser.IsInRole("Admin")) Then
daSurveyChecks.Fill(dsExisting.tblSurveyChecks)
dsExisting.Merge(dsNew.tblSurveyChecks)
strResult += daSurveyChecks.Update(dsExisting.tblSurveyChecks).ToString + " survey checks updated<br>"
End If
If dsNew.tblTreatments.Count > 0 And (currentUser.IsInRole("FB") Or currentUser.IsInRole("Heli-burn")) Then ' Or CurrentUser.IsInRole("Admin")) Then
daTreatments.Fill(dsExisting.tblTreatments)
dsExisting.Merge(dsNew.tblTreatments)
strResult += daTreatments.Update(dsExisting.tblTreatments).ToString + " treatments updated<br>"
End If
If dsNew.tblInternalQC.Count > 0 And (currentUser.IsInRole("FB") Or currentUser.IsInRole("Heli-burn") Or currentUser.IsInRole("Survey")) Then ' Or CurrentUser.IsInRole("Admin")) Then
daInternalQC.Fill(dsExisting.tblInternalQC)
dsExisting.Merge(dsNew.tblInternalQC)
strResult += daInternalQC.Update(dsExisting.tblInternalQC).ToString + " internalqc updated<br>"
End If
If dsNew.tblTreatmentChecks.Count > 0 And (currentUser.IsInRole("QA") Or currentUser.IsInRole("Admin")) Then
Try
daTreatmentChecks.Fill(dsExisting.tblTreatmentChecks)
dsExisting.Merge(dsNew.tblTreatmentChecks)
strResult += daTreatmentChecks.Update(dsExisting.tblTreatmentChecks).ToString + " treatment checks updated<br>"
Catch dbex As DBConcurrencyException
strResult += vbCrLf & dbex.Message
For x As Integer = 0 To dbex.Row.Table.Columns.Count - 1
strResult += vbCrLf & dbex.Row.GetColumnError(x)
Next
End Try
End If
If dsNew.tblHeliPiles.Count > 0 And (currentUser.IsInRole("Heli-burn")) Then ' Or CurrentUser.IsInRole("Planner")CurrentUser.IsInRole("QA") Or CurrentUser.IsInRole("Admin") Or
daHeliPiles.Fill(dsExisting.tblHeliPiles)
dsExisting.Merge(dsNew.tblHeliPiles)
strResult += daHeliPiles.Update(dsExisting.tblHeliPiles).ToString + " piles updated<br>"
End If
If dsNew.tblHeliCycles.Count > 0 And (currentUser.IsInRole("Heli-burn")) Then ' CurrentUser.IsInRole("Planner") Or Or CurrentUser.IsInRole("Admin")) Then
daHeliCycles.Fill(dsExisting.tblHeliCycles)
dsExisting.Merge(dsNew.tblHeliCycles)
strResult += daHeliCycles.Update(dsExisting.tblHeliCycles).ToString + " cycles updated<br>"
End If
If dsNew.tblHeliTurns.Count > 0 And (currentUser.IsInRole("Heli-burn")) Then 'CurrentUser.IsInRole("Admin") Or CurrentUser.IsInRole("Planner") Or
daHeliTurns.Fill(dsExisting.tblHeliTurns)
dsExisting.Merge(dsNew.tblHeliTurns)
strResult += daHeliTurns.Update(dsExisting.tblHeliTurns).ToString + " turns updated<br>"
End If
If dsExisting.HasChanges Then
dsExisting.Merge(dsNew)
End If
dsExisting.AcceptChanges()
'duh.
'If dsNew.HasChanges Then
' dsNew.AcceptChanges()
'End If
If dsExisting.HasErrors Then
Dim bolError As Boolean
Dim tempDataTable As DataTable
bolError = True
strResult += "<br>"
For Each tempDataTable In dsExisting.Tables
If (tempDataTable.HasErrors) Then
strResult += PrintRowErrs(tempDataTable)
End If
Next
End If
dsNew.Dispose()
dsExisting.Dispose()
connMerge.Close()
'edebugging will only track strresult
Dim fsError As New FileStream(Server.MapPath("./incoming/error.txt"), FileMode.Create, FileAccess.Write)
Dim swError As New StreamWriter(fsError)
swError.WriteLine("--==ERROR LOG==--")
swError.WriteLine(Now.Date.ToShortDateString)
swError.WriteLine("-----------------")
swError.WriteLine(strResult)
swError.Close()
fsError.Close()
Return strResult
End Function
View 2 Replies
View Related