I am in doubt if its possible to make a select statement which enables me to consolidate multiple lines in the same table.
I have a table with a lot of companies and figures for each company.
Some of the companies owns some of the other companies in the table and in reverse, some of the companies are owned by some of the companies in the table.
I have a lot of columns, but basically the most important columns are:
Company Name, Company Mother , Company Daughter.
Each company has also a revenue column.
What I want to do is to consolidate all figures for absolute mothers e.i. companies which are not owned by another company in the list.
I therefore need a select statement which says something like:
Get the revenue of companies not owned by another company (e.i. absolute mother). Add to this, the revenue of all its daughters. Add to this the revenue of all the daughters daughters etc. until there are no daughters left.
In other words - aggregate the revenue for all the companies in the group under the name of the ultimate parent company.
I can easily select and add the revenue for the first level of direct daughters, but I dont know how many more daughters the daughters has etc.
writing the query for the following, I need to collapse the continuity. If the termdate for an ID is one day less than the effdate of the next id (for the same ID) i need to collapse the records. See below example .....how should i write the query which will give me the desired output. i.e., get min(effdate) and max(termdate) if termdate is one day less than the effdate of next record.
Hi I have this select: SELECT MemberID, FirstName, LastName, City, (SELECT TOP 1 FamilyID FROM MemberFamily WHERE (MemberID = Members.MemberID)) AS FamilyID, (SELECT TOP 1 FamFirstName FROM MemberFamily AS MemberFamily_3 WHERE (MemberID = Members.MemberID)) AS FamFirstName, (SELECT TOP 1 FamLastName FROM MemberFamily AS MemberFamily_2 WHERE (MemberID = Members.MemberID)) AS FamLastName, (SELECT TOP 1 Relation FROM MemberFamily AS MemberFamily_1 WHERE (MemberID = Members.MemberID)) AS RelationFROM Members Can I change it to something like this? (I get a syntax error when I try to run it) SELECT MemberID, FirstName, LastName, City, (SELECT TOP 1 FamilyID, FamFirstName, FamLastName, Relation FROM MemberFamily WHERE (MemberID = Members.MemberID)) AS FamilyID, FamFirstName, FamLastName, RelationFROM Members I thought I would ask first before I begin banging my head against a wall trying to do something that's not possible.Thanks!Jason
How can I combine two data files (i.e .mdf and .ndf). We had two data file in our old server due to disk limitation. In the new server we don't have such limitation so we like to consolidate the two file in one. What is the best way to accomplish that?
I need to make a query that counts installed developer software for all our developers (from the sccm database), for licensing purposes. The trick here is that a license should only be counted once per. developer and that should be the highest version. But in the database, the developers can have different versions of the software installed (upgrades) on the same computer and they often use several computers with different software versions.
So for example: A source table with two developers
------------------------------------------------------------------- | dev1 | comp1 | Microsoft Visual Studio Ultimate 2013 | dev1 | comp1 | Microsoft Visual Studio Professional 2010 | dev1 | comp2 | Microsoft Visual Studio Premium 2010 | dev2 | comp3 | Microsoft Visual Studio Professional 2010 | dev2 | comp4 | Microsoft Visual Studio Premium 2012 --------------------------------------------------------------------
I want the result to be: ----------------------------------------------------- | dev1 | Microsoft Visual Studio Ultimate 2013 | dev2 | Microsoft Visual Studio Premium 2012 ------------------------------------------------------
I have created a query using cursors that give me the correct result, but it's way to slow to be acceptable (over 20 min..). I also toyed with the idea of creating some sort of CRL proc or function in C# that does the logic, but a SCCM consultant from MS said that if I create any kind of custom objects on the SCCM SQL Server instance, we loose all support from them. So I'm basically stuck with using good old fashioned T-SQL queries.
My idea now, is to use a CTE table and combine it with a Temp table with the software and a rank. I feel that I'm on the right track, but I just can't nail it properly.
This is how far I have come now:
IF OBJECT_ID('tempdb..#swRank') IS NULL CREATE TABLE #swRank(rankID int NOT NULL UNIQUE, vsVersion nvarchar(255)) INSERT INTO #swRank(rankID, vsVersion) VALUES (1, 'Microsoft Visual Studio Ultimate 2013'), (2, 'Microsoft Visual Studio Ultimate 2012'),
We have about a dozen SQL server 2000 Enterprise Edition servers in house. Our goal is to set up a cluster SQL server 2005 and consodiate the existing dozen servers to a few servers for easy manage and maintainence. So there are 3 things that we want to accomplish:
1. upgrade to SQL server 2005,
2. Consolidate existing servers
3. Make a cluster server to get high availability
But I'm sure what's the right order to acheive them. To upgrade each server to 2005 and then move them to cluster server? or set up the cluster server in 2005 and restore existing dbs to the cluster server. upgrade first or cluster first? upgrade first or consolidate first? pros and cons? upgrade or backup/restore? What do you recommend? We have lots of stored procedures, views and triggers, DTS packages and some replications. Any insight will be greatly appreciated.
Hey all,I am having some serious trouble getting the correct syntax for a select statement to work the way I need it, any help I could get on this would be greatly appreciated.I have a table called Units which stores computers and a table called Software which stores software. I have a bit field in Units called OEM, when this is set to true I don't want the select statement to pull this unit down when I am assigning software to other units.Here is my select statement: SELECT Software.SID, Software.SN, Software.Name, Users.First + ' ' + Users.Last AS 'Assigned User', Units.Make + '-' + Units.Model AS 'Assigned Unit' FROM dbo.Software LEFT JOIN dbo.Units ON Software.SN = Units.SN LEFT JOIN dbo.Users ON Units.UID = Users.UID WHERE (Units.OEM = 'FALSE') AND (Software.SN LIKE '%' + @SearchString + '%')Everything works as expected, unless of course the unit has no software assigned to it yet, it won't return it because its not tied to a Units.OEM field. Is there anyway to have it return ALL records that even arn't joined OR are joined but have OEM set to false?Thanks, let me know if I need to clear anything up.-Matthew
I am in the process of migrating 300+ reports and 200ish subreports to SharePoint 2013 hosted. I wanted to avoid the duplication of creating copies of all the subreports across 9 different folders.
I'm looking for a way of taking a query which returns a set of date time fields (probable maximum of 20 rows) and looping through each value to see if it exists in a separate table.
E.g.
Query 1
Select ID, Person, ProposedEvent, DayField, TimeField from MyOptions where person = 'me'
Table
Select Person, ExistingEvent, DayField, TimeField from MyTimetable where person ='me'
Loop through Query 1 and if it finds ANY matching Dayfield AND Timefield in Query/Table 2, return the ProposedEvent (just as a message, the loop could stop there), if no match a message saying all is fine can proceed to process form blah blah.
I'm essentially wanting somebody to select a bunch of events in a form, query 1 then finds all the days and times those events happen and check that none of them exist in the MyTimetable table.
I'm at a bit of a loss here. My T-SQL skills are not up to the task at hand here :(
I've got company records in one table and SIC codes that correlate to the companies linked by the company ID. So, I can run the query, but the output I get is multiple records for each company, because some companies have multiple SIC codes associated with them.
I understand how to get only one record, but what I want to do is create a result set that has all the SIC codes associated with one company. Possibly in a comma seperated list, that would count as one field.
Anyone have any idea how to bring back all the SIC codes for one company as one variable (or multiple variables, but in one record)?
I am trying to join seperate records into one return set. IE. select accountNum, flag1, flag2, flag3 from MyDB where flag1='A' or flag2='B' or Flag3='C'
The problem is that there could be 2 records with the same account number but flag1 ='A' Flag2='B' ect.
This would return to lines. Is there a way that I can have all return sets show up on one line only. Eliminating duplicate return sets???
I am new at sql programming and I need all the help i can possibly get..Im using SQL Server 2000 and I have been given an assignment which follows:
- i have to add 100 new records at once to an existing table. I have to do it through SQL Server only( query analizer,i suppose) and I am not allowed to use any other languages to achieve this. Now, my question is how can i do it through sql only? What is the code i have to write to make this thing work? I simply dont know where and how to start...
Dear ALL, I have two tables with named Reports and Backup_Reports with same fields. Id(numeric), MobileNumber(varchar), SmsBody(varchar),date(datetime),Status(char). Here what I want is, if I am searching some records by entering the mobile number then the sql query first will search on the first table Reports then it will show the related records and again the query will search on the second table Backup_Reports then will show related records from this table also. What I mean is, if I am searching some records by mobilenumber first will search on the Reports and then will go to second table Backup_Reports and will show all the related records together. How can I handle this?
I have a query that returns multiple identical records, however it shouldonly return one. Indeed there is only one record for the OrderActionTypecodeof 'P' yet there are two orderactions so it returnd both.Oddly the second query returns only the desired single record but wihtoutall the additional fields I need. Does the Inner join somehow mess with thequery?ThanksQuery 1SELECT Orders.OrderID, Orders.TicketID, A.AttemptID, E.EventID,E.AssetCode AS Asset, Orders.FK_Prod_Alias AS Alias, Orders.ContractCode,L.OrderLegCode AS OrderLeg, M.MarketActionName ASAction, Orders.OrderVolume AS Volume, Orders.OrderPrice AS Price,T.OrderTypeName AS OrderType, S.StatusName AS Status,Orders.FilledVolume AS Filled, Orders.OriginalOrderDateTime,Orders.PlaceOrderDateTime,Orders.MonitorFlagFROM Orders INNER JOINOrderAction OA ON Orders.OrderID = OA.OrderID INNERJOINAttempt A ON Orders.AttemptID = A.AttemptID INNER JOINEvent E ON A.EventID = E.EventID INNER JOINMarketAction M ON Orders.MarketActionCode =M.MarketActionCode INNER JOINOrderLegs L ON Orders.OrderLegCode = L.OrderLegCodeINNER JOINOrderType T ON Orders.OrderTypeCode = T.OrderTypeCodeINNER JOINOrderState S ON Orders.Status = S.Status ANDOrders.OrderID =(SELECT OrderIDFROM ORDERACTIONWHERE ORDERACTIONID =(SELECTMAX(ORDERACTIONID)FROMORDERACTIONWHEREOrderActionTypeCode = 'P'))Query 2SELECT OrderID, TicketIDFROM OrdersWHERE (OrderID =(SELECT OrderIDFROM ORDERACTIONWHERE ORDERACTIONID =(SELECTMAX(ORDERACTIONID)FROMORDERACTIONWHEREOrderActionTypeCode = 'P')))
Hi, I am a rookie at sql and asp.net. I have another post is the asp.net section http://forums.asp.net/thread/1589094.aspx. Maybe I posted it in the wrong section. I am collecting multiple rows from a gridview. I validated/confirmed I am capturing the correct values. How ever, I am having major problems passing these to an sql database. The problems that I know of is declaring my parameters correctly and then adding the values through a for each statement. I added the post over 30 hours ago with only me as the replier trying to refining or clarifying the problem. Part 1 is the code that works, part 2 is my problem, I have tried may different ways to resolve this but no luck. Regards! Protected Sub Botton1_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click**************** PART1 **************************Dim gvIDs As String = ""Dim ddIDs As String = ""Dim chkBox As Boolean = FalseDim chkBox1 As Boolean = False'Navigate through each row in the GridView for checkbox items ddIDs = DropDownList1.SelectedValue.ToStringFor Each gv As GridViewRow In GridView1.RowsDim addChkBxItem As CheckBox = CType(gv.FindControl("delCheckBox"), CheckBox)Dim addChkBx1Item As CheckBox = CType(gv.FindControl("CheckBox1"), CheckBox) If addChkBxItem.Checked Then chkBox = True gvIDs = CType(gv.FindControl("TestID"), Label).Text.ToString Response.Write(ddIDs + " " + gvIDs + " ") If addChkBx1Item.Checked Then chkBox1 = True Response.Write("Defaut Item") End If Response.Write("<br />")End IfNext******************** Part 2 *****************************************************Dim cn As SqlConnection = New SqlConnection(SqlDataSource1.ConnectionString)If chkBox ThenTry Dim insertSQL As String = "INSERT INTO testwrite (TestLast, test1ID, TestDefault) VALUES (@TestLast, @test1ID, @TestDefault)" Dim cmd As SqlCommand = New SqlCommand(insertSQL, cn) cmd.Parameters.AddWithValue("@TestLast", DropDownList1.SelectedValue.ToString) cmd.Parameters.AddWithValue("@test1ID", CType(gv.FindControl("TestID"), Label).Text.ToString) cmd.Parameters.AddWithValue("@TestDefault, CType(gv.FindControl("CheckBox1"), CheckBox)) cn.Open() For Each ..... Problems here also Next cmd.ExecuteNonQuery()Catch err As SqlException Response.Write(err.Message.ToString)Finally cn.Close()End TryEnd If
I have the Temporary table:ItemDetailID (int)FieldID (int)FieldTypeID (int)ReferenceName (Varchar(250))[Value] (varChar(MAX))in one instance Value might equal: "1, 2, 3, 4"This only happens when FieldTypeID = 5.So, I need an insert query for when FieldTypeID = 5, to insert 5 rows into the Table FieldListValues(ItemDetailID, [value])I have created a function to split the [Value] into a table of INTs Any Advice?
I need to insert records in two tables, one is main table and another is child table. From my aspx page I need to pass info. for one records in main table, insert that record into main table, get the is of the inserted table.
Then insert 15 records in the child table.
Everything must be in a transaction, either everything works or everything fails. Should I do it with aspx or should I pass arrays to a stored procedure?
I have table with format : ID Name ParentID1 England 02 Canada 03 Manchester 14 Chelsi 15 Arsenal 16 Canada_1 27 Canada_2 28 MU_1 39 MU_2 310 MU_1_1 8.... Now , I write a function which to get information ,such as : England ---- Manchester ----MU_1----MU_1_1 (*)My Function : Function GetInformation(ID as int16) as string ' my code here End function My problem : (With ID=10)When i pass this ID , i have to get string which format : (*)So , what is " my code here " ?Thank any suggestions ,any advices ....And thank you very much.
Is it possible to do an update on multiple records. I have fields CusOrderID and CusCreditAmt in table CusOrder; and fields CusOrderID and CreditAmt in table CusCredits. I would like to update the value in the CusCreditAmt field in CusOrder to equal the CreditAmt field in CusCredits where CusOrderID is the same in both tables.
I tried doing this in a stored procedure based on a View with an inner join between the 2 tables as follows:
Update View1 Set CusCreditAmt = CreditAmt
I received an error that the subquery returned more than one value. Is there anyway to do something like this and make it work?
i am facing a problem with multiple submissions. From end is ASP and database is SQL server. When i test the application on production system it works fine. But when it goes on the web and say 500 odd ppl accessing simultenously it starts submitting multiple records. This behaviour in random .. i mean it doesent happend with all the records. I change the cursor type to adUseClient still the same error persists... Then i submitted the Insert query directly to connection object without using a recordset .. still the problem persists .. anyu clues abt this
What I need is the start and end time of each task, but the issue is there is no unique task number to bind them together.. So for instance the task starts with 'Open-Submitted' and ends with 'Task Approved'. The issue is there can be multiple occurrences in the same file number. I need to be able to split these into multiple tasks with the associated start and stop times.
File IDDatetimesTask Event StatusTask Event NameTask IDEvent ID File 16/3/13 16:33Open-SubmittedTask is retrievedTSK-12345612345 File 16/3/13 16:44Open-ApprovedTask ApprovedTSK-12345623456 File 16/20/13 18:11Open-SubmittedTask is retrievedTSK-12345634567 File 16/21/13 14:42Open-ApprovedTask ApprovedTSK-12345645678
I've tried something like this but since I'm referencing trans_type I get a message that trans_type must be in Group by. doing that give me multiple records.
select cus_no, Inv_no, Sum(Amount_Invoiced_DC) AS InvAmt, case trans_type when 'Sales Inv' then sum(Amount_Paid_DC) else 0 end as AmtPaid, case when trans_type = 'Discount' and sum(Amount_Paid_DC)<0 then sum(Amount_Paid_DC) else 0 end as DiscountAmt FROM BI50_BankTransactions_AR_InvcDt_H where cus_no is not null group by cus_no, Inv_no
I know how to query up duplicate records, here is what I am using to do so:
Select PhoneNum, Count(PhoneNum) as NumOccurances From Tester Group By PhoneNum Having (Count(PhoneNum) > 1)
when the duplicates arise, I expect them to have unique CallResultCode values, and I would like to make a priority of which value stays and which one gets dumped, keep in mind that I am a SQL noob.
The following statement gives the error that multiple records are returned. I am attempting to pick one weight out of a group of three, the three have the same ResidentID and different dates in the table variable @WeightReportRaw. If I hard code the ResidentID, ResidentID = 6, it works fine. The variable @intMonth3 passes in a month number ans dosen't seem to be a problem.
What am I missing, Thanks in advance for any help.
update tblResidentWeightsTemp set FirstWeight =
(select RWeight from @WeightReportRaw as W where ResidentID = W.ResidentID and month(W.RWeightDate) = @intMonth3)
I discovered wherein lies our troubles. Our input file has a header record, followed by several detail records... and then, at some point, another header record, followed by more detail records.
Apparently, SSIS doesn't like this set up and so we're having to rewrite everything in C#.
I have two questions:
1 - How hard would it be for SSIS to split the input file into several input files, breaking at every header record to start a new file? 2 - Is this really something that SSIS has a problem with? Has anyone ever had to deal with/work around this?
I have a really simple query I'm trying to execute. I want to replace all instances of int X (8) in Column A (LastActivityID) with int Y (27) but the following SQL returns the said error. I understand the error, but not sure how to script the SQL differently to get the intended result. Thanks in advance.
Code Block
UPDATE Item SET LastActivityID = 27 WHERE LastActivityID = 8 Error: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
I have searched in length and cant seem to find a specific answer.I have a tmptable to hold user "shoppingcart" ( internal supplies)What i want is to take when the user clicks order to take that table pull the records with that user and populate the order and order details tablesThe order table has a PK of orderID and the orderdetails has a FK of orderIDI know how to insert to the main table, but dont know how to populate the details at the same timeI have this.Insert into supplyordersselect requestor from tmpordercart where requestor = &name so how do i also take from the tmpordercart the itemno and quanity and put them into the orderdetails so that it links back to order table?