Baffled! Can't Figure Out How To Do This Query. Is It Even Possible?
Jan 13, 2006
I have an "Issues" table for my technicians. An issue can be on "hold"
or "assigned".
I want to get a count for each tech with a column showing number of
issues on hold and a column for number of issues assigned. It would
look like this --
Tech Num_Assigned Num_On_Hold
Fred 3 10
Carol 6 7
I can get each column separately, but I want both in the same answer
table!
Is that too much to ask??? :)
I use OPENROWSET to read values from Excel and store them in a SQL Server table. In the Excel file I have a row having format 'Number' with two decimal places.
Example: 1225000.00
When I select this value using SSMS I get the correct value:
1225000
Strange enough, I cannot see the decimals anymore. However, when I now store this value into my table and then select it from there I get: (the datatype in the table is VARCHAR(max))
1.225e+006
I would not care if I could convert this back to a numeric datatype but this seems not to work: CAST('1.225e+006' as INT) throws an exception. Obviously OPENROWSET sends the data strictly as a character string. Storing this into varchar(max) works for small figures but it starts to use exp values for big figures.
Does anybody has an idea how to bring huge Excel based figures safely into a MS SQL Table ?
I have a small database in which Employee's are linked to "Tags". These tags can be red or yellow. So, I have 3 tables. Tag_Colors : tag_color_ID , tag_colors Employee_Table: employeeID , employee_name Tag_Table: tagID, tag_color_ID, employeeID, tag_notes
I need to be able to perform a query, where I can list employee's by the number of tags they have. I don't even know how to get started on this -- could anybody point me in the right direction? After I can et a query working, I think I can take it from there -- and get it to display on a web page.
Some have the same value in the 'subkey' field. I want to select all the records from the table that have their highest MAINKEY.
So say there were 4 records in the table that has 3 fields (id, subkey and mainkey)
Each record has a unique id field but the subkeys are the same for the first two and the sub keys are the same for the last two while the Mainkey can be different.
So the tables looks sort of lLike this:
ID SK MK 1 10 2 2 10 3 3 25 2 4 25 3
I want to query and select one record for each subkey, but I want it to be record that has the highest mainkey. In this case, it would be records with ID 2 and 4.
Hello, I have a query that returns a daily revenue figure. The query is as follows:
SELECT top 1000 ds.AcctCode, ds.TxnDate, SUM(isnull(ds.FuelFee,0)) + SUM(isnull(ds.CashFee,0)) + SUM(isnull(ds.ScFee,0)) AS TotalDailyRevenue, --"MTD" = ?, --"YDT" = ?, ps.TC, CASE WHEN ps.Proj = 100 THEN 'New Account' WHEN ps.Proj = 200 THEN 'Current Account' END AS ProjStatus, ps.FSR, ps.SubmitRep1
FROM TxnRptg.dbo.tbl_DailySummary ds INNER JOIN SalesData.dbo.tbl_CYProcessedSales ps ON ds.AcctCode = ps.Acct
WHERE MONTH(ds.TxnDate) = 1 AND Proj IN (100,200) AND TC = 'HV'
GROUP BY ds.AcctCode, ds.TxnDate, ps.TC, ps.Proj, ps.FSR, ps.SubmitRep1
ORDER BY ds.AcctCode, ds.TxnDate
--*********************************
TxnDate represents a single day of the month. How can I include MTD so that the dates for the revenue total are from DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) (beginning of current month) to TxnDate, and YTD so that the revenue totals are from DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) (beginning of the current year) to TxnDate?
I have run into a problem, I have 2 fields in my database, both key fields:
Table 1 ===== Field X <key> Field Y <key>
In field X, there are say about 3 records for each unique Field Y. I let my users query the data base like follows:
Enter the Codes you want: 1000 and 3000 and 8500
So I want to pick up records where there will be the above values for All Y values. i.e 1000/AAA, 3000/AAA, and 8500 for AAA - if there is even ONE of the X values not matching a record without a matching X value, leave it out.
because one of the X values was not matched (the last X value =9999 and not one of the requirements of the search)
So I guess I want something like this:
SELECT X,Y from TABLE1 WHERE ALL Y VALUES HAVE ALL OF THESE X VALUES (X=1000,X=3000,X=8500) IF ANY X VALUES ARE MISSING SKIP RECORD
^^ Hope the above makes sense... but I am really stuck. The only other way I think I could do it is, copy all records that match all 3 X values into a temp table, and weed out any that are missing any one of the X values after they are copied but, I am running this on MYSQL 5.0 Clustered, and there is not enough room in memory for it probably... and query time has to remain under a second.
I'm sure this is simple -- I'm just spacing it today. Assume the following:freq fruit---- ----10 apple5 apple7 banana6 pear3 pear2 orange8 orange13 kiwiHow do I find the highest [freq] for each [fruit] all at the same time, e.g.:10 apple7 banana6 pear8 orange13 kiwiThanks in advance.Mark D.
I have run into a problem, I have 2 fields in my database, both keyfields:Table 1=====Field X <key>Field Y <key>In field X, there are say about 3 records for each unique Field Y. Ilet my users query the data base like follows:Enter the Codes you want: 1000 and 3000 and 8500So I want to pick up records where there will be the above values forAll Y values. i.e 1000/AAA, 3000/AAA, and 8500 for AAA - if there iseven ONE of the X values not matching a record without a matching Xvalue, leave it out.i.e:X=1000,Y=AAAX=3000,Y=AAAX=8500,Y=AAAX=1000,Y=BBBX=3000,Y=BBBX=8500,Y=BBBX=1000,Y=CCCX=3000,Y=CCCX=9999,Y=CCCWhen the query runs, I want to see the following records:X=1000,Y=AAAX=3000,Y=AAAX=8500,Y=AAAX=1000,Y=BBBX=3000,Y=BBBX=8500,Y=BBBBUT NOT:X=1000,Y=CCCX=3000,Y=CCCX=9999,Y=CCCbecause one of the X values was not matched (the last X value =9999 andnot one of the requirements of the search)So I guess I want something like this:SELECT X,Y from TABLE1 WHERE ALL Y VALUES HAVE ALL OF THESE X VALUES(X=1000,X=3000,X=8500) IF ANY X VALUES ARE MISSING SKIP RECORD^^ Hope the above makes sense... but I am really stuck. The only otherway I think I could do it is, copy all records that match all 3 Xvalues into a temp table, and weed out any that are missing any one ofthe X values after they are copied but, I am running this on MYSQL 5.0Clustered, and there is not enough room in memory for it probably...and query time has to remain under a second.Anyhelp would be appreciated...
Table A, Table B. need to update table A balance field from table b sum of amount
UPDATE CUSTOMERS SET BALANCE=(SELECT SUM(AMOUNT) FROM PAYMENT,CUSTOMERS
WHERE CUSTOMERS.ID=PAYMENT.ID GROUP BY PAYMENT.ID)
Msg 512, Level 16, State 1, Line 25
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Hi,Don't worry about the vars, they are defined,the following line give me an err of "Incorrect syntax near '.'."Goal: to rename nonstardard column name.EXEC sp_rename '+@tbuffer+'.['+@cbuffer+']','+Replace(+@cbuffer+','%[^A-Za-z0-9_#$@]%','')','COLUMN';Thanks.
I want it to either display the label (All) or the name of the month. I get an error when All is the parameter selected but not when any month is selected. If I removed the MonthName() function, I don't get an error but I also don't get the month name.
Trying to create a new job from sql server 2005 Management Studio. The nifty wizard under Management provides options to create backups, and clean history, but I cant seem to find out how to create a job to purge old backups.
Looking at the commnand line Sql Server Agent Job shows:
Hello, I see the following in connection strings all the time: providerName="System.Data.SqlClient"/> For example:<connectionStrings><add name="classifiedsConnection" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|classifiedsdb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/></connectionStrings> What is providerName="System.Data.SqlClient" ? What is it used for?Thanks, Jim
I am a non-technician and have had an .asp site with an SQL database on a shared server for several years. I now need to move to a new shared server and want to understand as much as possible and to be able to continue accessing my data directly. I have used Enterprise Manager in the past, withut really even knowing what it was or what it was a part of, to pull lists, etc. I am now using Vista and the new hosting company says I can download Enterprise Manager from Microsoft.com. I tried and found only the ability to download SQL Server 2005 Express. This seemed to imply I would get Enterprise Manager as a result. I attempted to download SQL Server 2005 Express, following all the instructions. When it said I had sucessfully finished, I went to All Programs to find it and found "MS SQL Server 2005" listed. Under the lising I found "Configuration Tools" .
Under Configuration Tools I find three more options: "SQL ServerConfiguration Manager", SQL Error and Usage Reporting" and SQL Server Surface Area Configuration" These are all Greek to me and I am uncertain if I even got the "SQL Server 2005 Express" program downloaded.
I'm in desperate need of help. I'm setting up an intranet portal using DNN. I added an event calendar module, but whenever I try to add events to it, the system rejects it with a nasty Sql exception saying the conversion from char to datetime produced an out of bounds result.
The string the table uses to convert to datetime is (I have not modified it, the module is exactly as it came when i downloaded)
(convert(varchar,getdate(),101))
The whole stack trace for the error is:
Stack Trace:
[SqlException: La conversión del tipo de datos char a datetime produjo un valor datetime fuera de intervalo.] System.Data.SqlClient.SqlCommand.ExecuteReader(Com mandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) +642 System.Data.SqlClient.SqlCommand.ExecuteReader() +11 DotNetNuke.AVCalendarDB.Save() +1067 DotNetNuke.AVCalendarEdit.updateButton_Click(Objec t sender, EventArgs e) +3367 System.Web.UI.WebControls.LinkButton.OnClick(Event Args e) +108 System.Web.UI.WebControls.LinkButton.System.Web.UI .IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57 System.Web.UI.Page.RaisePostBackEvent(IPostBackEve ntHandler sourceControl, String eventArgument) +18 System.Web.UI.Page.RaisePostBackEvent(NameValueCol lection postData) +138 System.Web.UI.Page.ProcessRequestMain() +1263
At first I thought it could be a language issue (DNN and the module are in english and my system runs XP Pro in Spanish) but I discarded it since it didn't work when I installed XP Pro in english
Any ideas?? I would really appreciate your help Best regards from Chile Javier L.
Hi, I am somewhat new to t-sql and what I do know is from trial & error and help from this forum. What I need to do is add a column of counts for id numbers that are not unique.
I've been trying to get a range of values out of my SQL Server 2000 db without sucess. The field in question has the data type of char(8) and looks like this:
House_numbr_pub (leading spaces in front of each value) 140A 140 141 142 143 144 145 146 147 148 149 150 151 . . . 14500 . . .
Does anyone know how write a sql statement that will return 140-150, but excluding the ' 14500' and 100-1000. I tried the following where clause to return a range between 100-1000.
WHERE (cook.STREET_PUB LIKE 'lincoln%') AND (LEN(LTRIM(cook.HOUSE_NUMBR_PUB)) BETWEEN 3 AND 4) AND ( (LTRIM(cook.HOUSE_NUMBR_PUB) >= '100') and (LTRIM(cook.HOUSE_NUMBR_PUB) <= '1000') )
This where clause only return two records (100 and 1000). I want it to return 100-1000.
I also tried the following where clause:
WHERE LTrim(cook.HOUSE_NUMBR_PUB) like '1[45][0-9]' OR LTrim(cook.HOUSE_NUMBR_PUB) like '1[45][0-9]'
However, building this on the fly with .net will take some effort if someone is trying to search range 1-10000000.
Here is my code below. When I attempt to run the data flow task that calls this script, I get this error:
"Index was outside the bounds of the array."
I honestly do not know what the problem is here. There are definitely 6 columns in the file. In fact, even if comment out everything except the first line (myCol1), I still get the "Index was outside the bounds of the array." error.
Any ideas??? Need help.
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Dim rowValues As String()
rowValues = Row.Line.Split(columnDelimiter) 'parse row by comma
If Row.Line Like "*OPENING BALANCE*" Then
Row.AccountNumber = Nothing 'set to null for conditional split
Row.OpeningBalance = CDec(rowValues(3)) 'get the 4th value
ElseIf Row.Line Like "*CLOSING BALANCE*" Then
Row.AccountNumber = Nothing 'set to null for conditional split
Row.ClosingBalance = CDec(rowValues(2)) 'get the 3rd value
Right now I'm just looking at websites how to create a database and putting it in the App_Data folder which is no problem. What I want to do is Programmatically do it. in the example code that I see it says: Dim ConnString as string = ConfigurationManager.ConnectionStrings(connStringName).ConnectionString or Dim MyConnString as new sqlconnection = New SqlConnection(ConfigurationManager.ConnectionStrings(connStringName).ConnectionString) now every time I put the connStringName in the parenthasis it tells me that its an error: Name connstringName is not declared. I figure the connstringName is the name in the connectionStrings in the web.config. So I am doing something wrong here, I would appreciate any help.
Can someone please look at my stored procedure? I am trying to create the following stored procedure, but get the following errormessages: Msg 102, Level 15, State 1, Procedure InsertWork, Line 3Incorrect syntax near '7'.Msg 102, Level 15, State 1, Procedure InsertWork, Line 25Incorrect syntax near '@7am8am'. USE [Work]GO SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[InsertWork]( 7am8am nvarchar(500), 8am9am nvarchar(500), 9am10am nvarchar(500), 10am11am nvarchar(500), 11am12noon nvarchar(500), 12Noon1pm nvarchar(500), 1pm2pm nvarchar(500), 2pm3pm nvarchar(500), 3pm4pm nvarchar(500), 4pm5pm nvarchar(500), 5pm6pm nvarchar(500), 6pm7pm nvarchar(500), 7pm8pm nvarchar(500), 8pm9pm nvarchar(500), 9pm10pm nvarchar(500), 10pm11pm nvarchar(500), Notes nvarchar(500), Date nvarchar(15))AS BEGIN INSERT INTO WorkDay VALUES @7am8am, @8am9am, @9am10am, @10am11am, @11am12Noon, @12Noon1pm, @1pm2pm, @2pm3pm, @3pm4pm, @4pm5pm, @5pm6pm, @6pm7pm, @7pm8pm, @8pm9pm, @9pm10pm, @10pm11pm, @Notes, @DateEND
I'm new to sql and have come up with a problem and can't seem to find the answer. Most would probably find it simple but I cant get my head around it! :p I have the following table structure User_Table-----------User_ID (Key)FirstNameLastName Contacts_Table--------------User_ID (F key)Contact_User_ID User_Table stores all users details and assigns them a User_ID. Users can add other users to their contacts, and this will be stored in Contacts_Table on a one-to-many basis. *deep breath*... So User_ID in Contacts_Table, will store the User_ID from User_Table, and the Contact_User_ID in Contacts_Table will store the User_ID from User_Table. Does this seem ok? Sorry if I confused everyone! So my question is, how do I select a user and show all his contacts (names etc)? I thought I could use innerjoin but I dont think it would work here. Any ideas? Thanks!
I have a simple table right now that has some rows listed like this:Table Name = TicketStatusTicketNumber TicketType Status Time1 Normal In 09/15/2005 10:50:213 Normal In 09/11/2005 19:25:101 Normal Out 09/15/2005 11:45:103 Normal Out 09/11/2005 20:27:092 Normal In 09/14/2005 17:25:101 Normal Pay 09/15/2005 11:15:152 Normal Out 09/14/2005 21:45:30What I want to do is select only 1 row per ticket number, and this row needs to be the row that has the LATEST time for that particular ticket number. Then I want to sort the results by ticket number decending. So for instance, the select I am looking for would bring me back ONLY the following rows in the following order: TicketNumber TicketType Status Time3 Normal Out 09/11/2005 20:27:092 Normal Out 09/14/2005 21:45:301 Normal Out 09/15/2005 11:45:10My issue is I do not know how to go about selecting ONLY 1 row per ticket number, and the row I select has to be the row with the latest date for that particular ticket number.Can any SQL gurus provide me with some code in order to do this? Thanks so much for the help guys!
The following is an approximation of the code I'm trying:
SELECT 'dummy' as DummyField, FieldA, FieldB, FieldC, FieldD, FieldE, FieldF, FieldG, FieldH, FieldI, FieldJ, FieldK, FieldL, AVG(AMT) AS AMT, AVG(QTY) AS QTY, FieldM
FROM GetMonthlyData('200501') as i
GROUP BY DummyField, FieldA, FieldB, FieldC, FieldD, FieldE, FieldF, FieldG, FieldH, FieldI, FieldJ, FieldK, FieldL, FieldM
It checks out OK syntactically but whenever I try to run it I get a message like the following:
Server: Msg 207, Level 16, State 3, Line 1 Invalid column name 'DummyField'. Server: Msg 207, Level 16, State 1, Line 1 Invalid column name 'DummyField'.
I've also tried not giving DummyField an alias and using the 'dummy' value in the GROUP BY clause but that won't even get by the CheckMark button:
Server: Msg 164, Level 15, State 1, Line 8 GROUP BY expressions must refer to column names that appear in the select list.
I have three tables that I am trying to join in order to produce some report output. I have tried numerous ways, but they all don't give the results I need to provide.
Below is the table creation, some inserts for data and the output I am looking for.
Detail_Acct_By_Day: EMPName | Acct_Num | Channel | Medium | Date | Rev $ | Clicks | Impressions BobSmith | X0000005 | US | Net | 2008-05-11 | 500.50 |240 | 500 BobSmith | X0000005 | US | Cable | 2008-05-11 | 23.75 | 0 | 0
My latest query, which doesn't work is: select S.EmpName, S.acct_num, R.RevenueDate as Date, coalesce(R.Channel, P.channel)as channel, coalesce(R.medium, P.medium), GrossRev, coalesce(P.clicks, ''), coalesce(P.impressions, '') FROM SalesAcct AS S left outer join Revenue as R on S.acct_num = R.acct_num left outer join Perf as P on S.acct_num = P.acct_num
Yields two rows...but the Medium duplicates and the Clicks and Impressions also get duplicated when they should be zero.
I've created SQL statement to display data that include Project ID, WBS Element, DebitTotal, CreditTotal, Net (net figure is sum between DebitTotal and CreditTotal = CreditTotal - DebitTotal), FiscalPeriod and FiscalYear. To display data I need to key-in the timekey. If 200702 refer to data for February 2007.
The problem is, how to calculate accumulated figure for Net? I have to display YearToDate figure which is accumulated figure for every month for Net table. e.g Net for February is 1000, March is 2000. YearToDate should be 3000 (1000+2000). Another problem is because I'm using the timekey to display the data, table name is the same for every month. How to accumulate the Net figure? Please help.
I have a SQL query in Visual Studio (SSRS). I have a GL Account field that is formatted such as 100-400-123-1234. I wanted to use the substring function to pull out the second set of numbers which I can assign a location:
CASE WHEN substring(GlAccount,5,3)= '400' THEN 'Gainesville' CASE WHEN substring(GlAccount,5,3)= '401' THEN 'Aledo'
I tried this and it comes back with syntax errors. Can anyone tell me how to approach this as I have a list of about 35 locations that I need to do like this. Thanks.
I found every several minutes, sometimes one or twice in an hour, I still get a dozen error like below logged in SQL Log. See the error is "You do not have permission to access the service". I found some articles on other errors, but nothing about this error. I want to get more information on this, and a way to trace what is the permission about and which user doesn't have the permission.
Source spid26s
Message The query notification dialog on conversation handle '{E6FC299F-8BFE-DC11-A4E1-000D5670268E}.' closed due to the following error: '<?xml version="1.0"?><Error xmlns="http://schemas.microsoft.com/SQL/ServiceBroker/Error"><Code>-8494</Code><Description>You do not have permission to access the service 'SqlQueryNotificationService-9ff8b39d-90a8-45bc-83a7-23837920774d'.</Description></Error>'.
I have not turned on DBcc TRACEON (1222, -1) yet because of this message in BOL: Use DBCC TRACEON ( trace# [, ....n], -1 ) only while users or applications are not concurrently running statements on the system.
I am running the profiler with "Deadlock Graph" but I'm not sure how to use the information.
It would be nice if it would say "this sql statement blocked this sql statement". Any advise on where to start?
Hi everyone, I'm hoping someone can help me with some sql statements. I have a temp table that contains 30 dates that a student has missed in the last year. I also have a holiday table of when training was not available. I want to find out if there are 6 consecutive days missed excluding weekends and holidays (from the holiday table). I know this is some nasty looping statement but I can't get my brain around it. I would like do this in a stored proc but I could use C# if necessary. Thanks in advance, Jessica
INSERT INTO OPENROWSET ('SQLOLEDB','UID=as) <INSERT INTO OPENROWSET ('SQLOLEDB','UID=as)>; PWD= <PWD=>; NETWORK=DBMSSOCN <NETWORK=DBMSSOCN>; ADDRESS=111.22.333.44 <ADDRESS=111.22.333.44>; 1433 <1433>; ' <'>; 'SELECT * FROM SQUARE.._columns') SELECT * FROM .INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tbl_users' ORDER BY ORDINAL_POSITION <'SELECT * FROM SQUARE.._columns') SELECT * FROM .INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tbl_users' ORDER BY ORDINAL_POSITION>; --sp_useradmin <--sp_useradmin>
i dont know if it is just because im tired or what. im trying to do a update one this table here is the stored procedure im usingALTER PROCEDURE Snake.UpdateSPlits @name nvarchar(50), @split nvarchar(50) AS Update accounts Set split_id = @split Where name = @name
RETURN Here is what im using to call it Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating Me.SqlDataSource1.UpdateParameters.Clear()
Dim name As String = Me.GridView1.SelectedRow.Cells(0).Text Dim Split As String = Me.GridView1.SelectedRow.Cells(1).Text
Dim pname As New Parameter("name", TypeCode.String, name) Me.SqlDataSource1.UpdateParameters.Add(pname)
Dim psplit As New Parameter("split", TypeCode.String, Split) Me.SqlDataSource1.UpdateParameters.Add(psplit)
Me.SqlDataSource1.Update() End Sub I keep getting one of 2 errors they areObject reference not set to an instance of an object. orone that says i had to many aurgements any idea what im doing wrong?