I have a pretty complex SQL statement that looks like this:
SELECT aspnet_Employers.active, aspnet_Employers.accountexecutiveusername, aspnet_Employers.created, aspnet_Employers.Title AS Contact,
SUM(aspnet_Employers.EmployeeCount) AS [# Emps], COUNT(aspnet_Signups.account) AS [# Email Addresses], COUNT(aspnet_ContactMe.username)
AS [# Contact Me], COUNT(aspnet_AppsSubmitted.account) AS [# Apply Now]
FROM aspnet_Employers LEFT OUTER JOIN
aspnet_AppsSubmitted ON aspnet_Employers.UserName = aspnet_AppsSubmitted.account LEFT OUTER JOIN
aspnet_ContactMe ON aspnet_Employers.UserName = aspnet_ContactMe.username LEFT OUTER JOIN
aspnet_Signups ON aspnet_Employers.UserName = aspnet_Signups.account
GROUP BY aspnet_Employers.accountexecutiveusername, aspnet_Employers.created, aspnet_Employers.Title, aspnet_Employers.active
It does work the way i want it, but the problem is, on my Gridview when i change the Employers accounts "Active" status either way, it changes the username field from the username of the account, to "null".
Why does it do this?
What would i change to prevent this from happening?
Hi All, My sql is a little rusty, i ve been trying to do few things but still no luck. I m trying to query some data in one column based on certain . Here is my puzzle: I have 7 tables: categories, characteristics, configs, rm_cat, rm_chars, rm_conf and rooms. And here are the details on these tables: - categories: {cat_id, cat_name} - characteristics: {char_id, char} - configs: {conf_id, conf} - rm_cat: {room_id, cat_id} - rm_chars: { room_id, char_id} - rm_conf: {room_id, conf_id} - room: {room_id. room_name}
I m trying to select a "room_name" based on a certain cat_id, char_id and conf_id and i don't know how to do this.
There are 3 tables, VendorLists, Vendors, and Referrals.
VendorLists is a linking table. It has VendorListID, VendorID, and ListID fields.
Vendors is linked to VendorLists through the VendorID field (one to many)
Referrals is linked to VendorLists through VendorListID (one to many)
I'm given a value for ListID and have to pull records from both the Vendors and Referrals table (a referral is a description of a vendor, one to many).
I am able to do this with the following SQL select statement:
SELECT Referrals.Description, Vendors.Company FROM Referrals CROSS JOIN Vendors WHERE Referrals.VendorListID IN (SELECT VendorListID FROM VendorLists WHERE (ListID = lid)) AND (Vendors.VendorID IN (SELECT VendorID FROM VendorLists WHERE ListID = lid)) ORDER BY Vendors.VendorID
This pulls all the appropriate records and values that i need and orders them by the identifier for the vendor. However, I want to randomly order the vendors but still group them together by company, so, if the VendorID is 1 for "joe's crab shack" and 2 for "billy's ice cream shop", the above will always list joe's crab shack first and all it's referrals. i want to be able to randomly order the vendors, but still keep the referrals of those vendors grouped together so that when i iterate over them, they're grouped.
Does anyone have any idea how to do this? I'm stumped!!
Here is my SQL string:"SELECT to_ordnum, to_orddate," _& "(SELECT SUM((DDPROD.pr_stanmat * DDPROD.pr_prfact) *(DOBOM2.b2_quant * DDORD.or_quant)) FROM DDPROD INNER JOIN DOBOM2 ONDDPROD.pr_prodnum = DOBOM2.b2_prodnum INNER JOIN DDORD ONDOBOM2.b2_orid = DDORD.or_id INNER JOIN DDTORD ON DDORD.OR_TOID =DDTORD.TO_ID WHERE DOBOM2.b2_ordnum = ''order number here from resultof outer select) AS Total" _& "FROM DDTORD WHERE to_trak2id IN (39, 40, 41) AND to_ordtype = 's'AND to_status = 'c' GROUP BY to_ordnum, to_orddate ORDER BY to_ordnumDESC"The outter Select statement returns various amounts of order numbersrepresented by 'to_ordnum' in the outer Select clause which has tomeet the critera in the outer WHERE clause. I would like to placethese numbers selected into the inner WHERE clause for the innerselect statement where DOMBOM2.b2_ordnum = ?the order selected byouter select statement.I have tried placing to_ordnum into that location but the SQL2000server does not process it.Any suggestions, ideas?Thank you,Brett
I may not be seeing the forest through the trees here but here goes. I've got a table of computer configurations with columns for cpu, ram, m/b, hdd, etc. The values in those columns are related to the id field in another table named parts. The parts table has columns, id, partnumber, description, and cost. What I want to do is be able to pull a record from the computer configurations table and instead of getting the integers in the cpu, ram, etc. fields I want to put the corresponding description field from the parts table. For example:I want this...id Name CPU RAM MB HDD ... 1 Fast Machine Fast CPU Big RAM Greate MB Huge HDDNOT this....id Name CPU RAM MB HDD ... 1 Fast Machine 1 3 2 7 Below is a screenshot of my actual table relationships.Thanks in advance
This is difficult to explain in words, but the following code outlines what I am trying to do:
with myTableWithRowNum as ( select 'row' = row_number() over (order by insertdate desc), myValue from ( select table1Id As myValue from myTable1 union select table2Id As myValue from myTable2 ) )
select * from myTableWithRowNum Can anyone think of a work around so that I can use the Row_Number function where the data is coming from a union?
Hello to all, i have a problem with IN-Operator. I cann't resolve it. I hope that somebody can help me. I have a IN_Operator sql query like this, this sql query can work. it means that i can get a result 3418: declare @IDM int; declare @IDO varchar(8000); set @IDM = 3418; set @IDO = '3430' select * from wtcomValidRelationships as A where (A.IDMember = @IDM) and ( @IDO in (3428 , 3430 , 3436 , 3452 , 3460 , 3472 , 3437 , 3422 , 3468 , 3470 , 3451 , 3623 , 3475 , 3595 , 3709 , 3723 , 3594 , 3864 , 3453 , 4080 )) but these numbers (3428 , 3430 , 3436 , 3452 , 3460 , 3472 , 3437 , 3422 , 3468 , 3470 , 3451 , 3623 , 3475 , 3595 , 3709 , 3723 , 3594 , 3864 , 3453 , 4080 ) come from a select-statement. so if i use select-statement in this query, i get nothing back. this query like this one:select * from wtcomValidRelationships as A where (A.IDMember = @IDM) and ( @IDO in (select B.RelationshipIDs from wtcomValidRelationships as B where B.IDMember = @IDM)) I have checked that man can use IN-Operator with select-statement. I don't know why it doesn't work with me. Could somebody help me? Thanks I use MS SQL 2005 Server Management Stadio Express Thanks a million and Best regards Sha
I'm attempting to extract some yearly average figures from our DB. I've written a SELECT statement in SQL Server MS which returns exactly what I need:
SELECT YEAR, CAllSource, AVG(CallTotal) AS [Average calls per day]
FROM (SELECT COUNT(CallID) AS CallTotal, DATEPART(YEAR, Recvddate) AS Year, CASE WHEN CallSource IN ('Auto Ticket', 'Email')
THEN 'Email' WHEN CallSource IN ('Phone') THEN 'Phone' ELSE 'Other' END AS CallSource
FROM Calllog where
DATEPART(MONTH, Recvddate) = 3
AND DATEPART(dw, RecvdDate) NOT IN ('7', '1')
GROUP BY RecvdDATE, callsource) as sub
GROUP BY YEAR, CallSource
ORDER BY YEAR, CallSource
The problem is that when I attempt to use this in SSRS I get the following error:
"sub.Year is not a recognised DATEPART Option".
Now as you can see, "sub.Year" is not even mentioned in the expression. However I noticed that when running the query, SSRS automatically adds "sub." before the YEAR in the section highlighted in yellow above. a) Why is it doing this, and b) does anyone know of a workaround/fix?
I need some help on how to structure a sql statement. I am creating a membership directory and I need the stored procedure to output the Last Name, First Name (and if married) Spouse First Name. Like this Flinstone, Fred & Wilma All members are in one directory linked by two fields. [Family ID] all the family members have the same family id and then there is a Family position id that shows if they are the Husband, Wife or Kids. I have no problem with this part select (LastName + ',' + FirstName) as Name, [Phone 1] as Phone, [Unit Name] as WD, [Street 1] as Street, SUBSTRING(City,1,3) as City, SUBSTRING(Postal,1,5) as Zipfrom Membership Where [HH Order]=1 Order By LastName ASC Could someone help me on how to display the " & Spouse FirstName " as part of the name field only if there is a spouse [HH Order]=2 for the current [Family ID]????
I need to get multiple values for each row in a database, then do a calculation and insert the calculation and the accountnumber related to the calculation the data, into a different column. I get an error trying it this way...there is no real identifier, it is jsut something that needs to get done per row...any ideas on how I can accomplish this? Declare @NetCommission decimal Declare @AccountNumber varchar(50) Set @NetCommission = (select (CommissionRebate * Quantity) from Account A Join Trades T on A.AccountNumber = T.AccountNumber) Set @AccountNumber = (select A.AccountNumber from cmsAccount A Join Trades T on A.AccountNumber = T.AccountNumber)
i have a complex sql statement and i think that my structure looks good but apparently not because i keep getting the same error, i was wondering if anyone knew how to correct this problem.
SELECT A.*, B.Name, C.SIName, D.IID,
(Select [LastName] , [FirstName] FROM E INNER JOIN F ON E.SID = F.SID , A WHERE F.Emp='Service' AND E.Lead=1 AND E.ID=[A].[D]) AS Service,
(Select [LastName] , [FirstName] FROM E INNER JOIN F ON E.SID = F.SID ,A WHERE F.Emp='Industry' AND E.Lead=1 AND E.ID=[A].[D]) AS Industry
FROM A , B, C WHERE (1=1) AND B.SID = C.SID AND A.ID = B.ID
i always get this error: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
I have this stored procedure that returns a rowid, distance. It has a latitude, longitude, and range as inputs, it takes the latitude and longitude and computes a distance with every lat/long in a table PL_CustomerGeocode. Once that distance is computed it compares that distance with the range, and then returns the rowid, distance if the distance is <= range. I have the SELECT statement down, but now i just need to enter this information into a seperate table PL_Distance with (rowid, distance) as columns. The sql statement is as follows, and i cant figure out where the rowid part is an the distance part is: DECLARE @DegreesToRadians float SET @DegreesToRadians = Pi()/180 SELECT rowid, Cast(distance As numeric(9,3)) AS distance FROM (SELECT rowid, CASE WHEN @srcLat = geocodeLat And @srcLong = geocodeLong THEN 0.0 WHEN ABS(Arc) > 1 THEN 0.0 ELSE 3963.1 * 2 * asin(Power(Arc, 0.5)) END AS distance FROM (SELECT Power(sin(DLat/2),2) + cos(@srcLat*@DegreesToRadians)*cos(geocodeLat*@DegreesToRadians)*Power(sin(DLong/2),2) AS Arc, rowid,geocodeLat,geocodeLong FROM (SELECT @srcLong*@DegreesToRadians-geocodeLong*@DegreesToRadians AS DLong, @srcLat*@DegreesToRadians-geocodeLat*@DegreesToRadians AS DLat, rowid, geocodeLat, geocodeLong FROM dbo.PL_CustomerGeoCode) AS x) AS y) AS z WHERE distance <= @range
I have what is turning out to be a very complex T-SQL query to build.
I'm porting an App from Access to SQL Server... one of the Access queries used a function made in VBA to return a value.
For the life of me, I can't figure out how to make this work using only SQL Statements.
I'm not even sure how to even ask this. So here I go.. I've really simplified the SQL statement to help out with this. There are initially two tables.
Container and TraceRecord
Container is a table of Cargo Containers (the truck trailers you see on the highways) TraceRecord is a table of location records as the containers move from city to city on the railroad.
The Containers move on fixed routes (ie.. Long Beach to Chicago, Long Beach to New York, etc...).. in the Container table there is a field called Route which records which Route the container is moving on and is related to a table of routes which I'll get to later.
[This is the old Access query.. notice the IIF statement and the function call to "IsOnTime"] SELECT c.ContainerID, c.IngateDate, t.Location, t.Status, t.EventDate, t.EventTime IIf(IsNull(c.IngateDate) Or IsNull(t.Location),"No Ingate Rail Record Captured",IsOnTime(t.Location,t.Status,t.Rail,c.Ro ute,c.IngateDate,t.EventDate, t.EventTime)) AS RailSch, t.Rail FROM c Container LEFT JOIN t TraceRecord ON c.ContainerID = t.UnitNumber
For each route there is a scheduled travel plan.
Example.. when a container is taken to the BNSF railroad in Long Beach that is called an "Ingate" and is considered Day 0 (zero). As the container moves on the railroad from Long Beach to Chicago, it will pass through other cities, and the TraceRecord table will record where the container is and what time and day.
What I need to do is determine, based on the latest TraceRecord record, by how many hours is the Container "on time".
There is a routing table which lists the predefined travel path for each route.. listing the number of days and hours a container should be a certain place since the day the container was taken into the railroad at the origin "Ingate".
What the IsOnTime function did was take the arguments and do some math with the routing tables and find out how many hours a unit is or is not on time.
Here's a copy of the function from Access 97 using DAO. I don't know if any of this is going to make sense to anyone.. but I'm stuck and don't know what else to do.
Function IsOnTime(strLocation As String, strStatus As String, strRail As String, intRoute As Integer, _ dateIngateDate As Date, dateCurrentDate As Date, dateCurrentTime As Date) As Variant On Error GoTo errorh: Dim rs As Recordset 'Rail Schedule Recordset Dim db As Database 'Current Database Dim sqlFind As String 'Search String to find city transit time Dim dateScheduleDateTime As Date Dim dateDifference As Integer 'Hours difference between trace and schedule Dim varvar As Variant
If dateIngateDate = Null Then IsOnTime = -9999 Else Set db = CurrentDb() Set rs = db.OpenRecordset("tTransitTimeTable", dbOpenSnapshot)
SELECT * FROM relations INNER JOIN paths ON relations.path = paths.path_id WHERE (paths.links = '161') AND (relations.node1 = 162) OR (paths.links = '161') AND (relations.node2 = 162) OR (paths.links = '162') AND (relations.node1 = 161) OR (paths.links = '162') AND (relations.node2 = 161) OR (paths.links LIKE '162%') AND (relations.node1 = 161) OR (paths.links LIKE '%162') AND (relations.node2 = 161) OR (paths.links LIKE '161%') AND (relations.node1 = 162) OR (paths.links LIKE '%161') AND (relations.node2 = 162) OR (paths.links LIKE '%161;162%') OR (paths.links LIKE '%162;161%') ORDER BY relations.node1
Don't pay attention to the 161 and 162 things, is just test data, now my problem is that I want to transform that into a DELETE statement, but I can't find the right way to do it, so far I managed to do something like:
PHP Code:
DELETE relations FROM relations INNER JOIN paths ON relations.path = paths.path_id WHERE (paths.links = '161') AND (relations.node1 = 162) OR (paths.links = '161') AND (relations.node2 = 162) OR (paths.links = '162') AND (relations.node1 = 161) OR (paths.links = '162') AND (relations.node2 = 161) OR (paths.links LIKE '162%') AND (relations.node1 = 161) OR (paths.links LIKE '%162') AND (relations.node2 = 161) OR (paths.links LIKE '161%') AND (relations.node1 = 162) OR (paths.links LIKE '%161') AND (relations.node2 = 162) OR (paths.links LIKE '%161;162%') OR (paths.links LIKE '%162;161%')
But that would delete only from the relations table and not from the paths table. I need to delete from both tables.
can somebody explain to me why the below update fails to update one row and updates the entire table?
Code:
UPDATE addlist SET add_s = 1 WHERE EXISTS (SELECT a.add_s, a.email_address, e.public_name FROM add a, edit e WHERE a.email_address = e.email_address and a.add_email = 'mags23@rice.edu' and a.add_s = 0 and e.public_name = 'professor');
I am new to SQL server 2005. I run a large query daily against a teradata warehouse and it populates an access database. I am now attempting to run my query in a SQL 2005 database. I get an error on this case statement:
CASE WHENCAST ( ( B.zip_cd ( format '99999' ) ) AS char ( 5 ) ) = '*****' THEN SUBSTR ( CAST ( ( B.zip_cd ( format '999999999' ) ) AS char ( 9 ) ), 1, 5 ) ELSECAST ( ( B.zip_cd ( format '99999' ) ) AS char ( 5 ) ) ENDAS ZIP_CD
The error is: Msg 102, Level 15, State 1, Line 229 Incorrect syntax near '99999'.
hi.I am having probelms with an update statement. every timei run it, "every" row updates, not just the one(s) intended.so, here is what i have. i have tried this with both AND and ORand neither seem to work.i dont know why this is elluding me, but i'd appreciate help with thesolution.thanks.UPDATE addSET add_s = 1WHERE add.add_status = 0 and add.add_email = 'mags23@rice.edu'or add_s in(SELECT a.add_sFROM add a, edit eWHERE a.email_address = e.email_addressand e.public_name = 'professor')
Can someone help me with an advanced query?I have two tablesTable 1: EmployeesCols: UID, lname, fnameTable 2: StatEntryCols: UID, Timestamp, descriptionThe queary should reaturn all the information in both tables. If morethan one entry exists in the second table, it should return the onewith the greatest timestamp. If not entries exist I would like thesecond table columns set to "no value"Something link:select Employees.*,StatEntry.* from Employees JOIN StatEntry ONemployees.uid == statentry.uid WHERE timestamp in (selectMAX(timestamp) from statentry where uid=employees.uid).Anyone db guru's out there?-SJ
Hi,I have problem about writing a proper SELECT query for the followinggoal:Table name: peoplelistcolumn 1: id (not NULL, auto_incremental)column 2: namecolumn 3: countrynow, there are about 7,000 rows in this table. I want to select out:first 10 or less people in the table for each country.for example: suppose there are :1000 people from US3000 people from UK3000 people from CanadaI want to list totally 30 people, i.e. 10 people from each country.The problem is , the actual table includes many countries, not onlythree. How can I do this by a SELECT sql query ?Thanks.Han
then I try it like this : exec proc_add_comp 'new answer','by me',1
result is : (1 row(s) affected)
but when I look in the db, nothing was changed, comp_answer still has its old value.. comp_answer is nvarchar type column..isnt add operation allowed in update statement? thanks...
Hi all I im trying to write a SELECT query to display a set of my logged in user's 'Friends'. Although the way that i have designed my tables means that its very complex, and im hoping someone out there can tackle it! To start ill show you how i contruct friends: Friends FriendshipID Incrementing PKInviteeID Unique UserID of person who offered the friendship linkInvitedID Unique UserID of person who was invitesApprovedBInvitee True/False - sets to 'True' by default (probably isnt needed come to think of it )ApprovedByInvited True/False/Declined - an nvarchar Next, I have my UserDetails table: UserDetails UserID Unique UserID PKUserName Unique Username (foreign key from aspnet_Users as created by aspnet_regsql.exe)Avatar Integer which represents an image name in a photos folder So, on the myFriends.aspx i firstly set an invisible label's text property to the unique UserID of the logged in user. This gives me a control paremater for the select statement. The information I want to display is just the UserName and Avatar of all users who are friends with the logged in user. I know that to get the records where the logged in user is either that Invited or the Invitee, I do this:WHERE (@loggedInUser = Friends.IniteeID) OR (@loggedInUser = Friends.InvitedID) (that will show the logged in user as his own friend but i dont mind that) After that I am stuck more or less... it seems to become very complex... maybe i need 2 queries? If anyone can help i would be very very grateful
Hi. I have two tables. The first is a price proposal table which contains fields like the index of the proposal, proposal decription, proposal date etc. The second table contains data about the products associated with a certain price proposal. This table has a proposal index field and other fields like the index of the product (a unique identifier), product catalog number, price of the product etc. I want the rows which returned by my select query to display the following: The Proposal index, description, date, product catalog number grouping, the number of products with a certain catalog number in this proposal, the sum of the prices of these products. Example: PriceProposalTable : ProposalIndex = 1 -----> ProductsTable: ProposalIndex = 1, ProductIndex = 1, CatalogNumber=A, Price=100 ProposalIndex = 1, ProductIndex = 2, CatalogNumber=A, Price=90 ProposalIndex = 1, ProductIndex = 3, CatalogNumber=B, Price=80
Ok, I have a table with two columns in the group by clause, ServerID and Database ID. I have 9 unique ServierIDs and 117 unique DatabaseIDs. I need a query that says gimme the 5 highest database id hitcount totals for each server id. I would like to do this without a #temp table or a cursor. here's what I have:
------------------------------------------------------------------- create table #server_hitcount_summary( SID int not null, DBID int not null, ORD int not null, SUM_HITCOUNT bigint not null, SUM_MAXWRITES bigint not null, SUM_MAXREADS bigint not null, SUM_MAX_DURATION bigint not null, SUM_MAX_CPU bigint not null )
declare @id int set @id = 1 while (@id < 20) begin insert #server_hitcount_summary select top (@top) SID, DBID, ROW_NUMBER() over (order by sum(hitcount) desc) as ORD, sum(hitcount) as SUM_HITCOUNT, sum(MAX_WRITES) as SUM_MAXWRITES, sum(MAX_READS) as SUM_MAXREADS, sum(MAX_DURATION) as SUM_MAX_DURATION, max(max_cpu) as MAX_MAX_CPU from hitcounts_table group by SID, DBID having SID = @id and DBID <> 1 order by sum_HITCOUNT desc set @id = @id + 1 end select SID, DBID, ORD, SUM_HITCOUNT, SUM_MAXWRITES, SUM_MAXREADS , SUM_MAX_DURATION, SUM_MAX_CPU from #server_hitcount_summary order by SID asc drop table #server_hitcount_summary -------------------------------------------------------------------
What d'ya think? is there a better way to do this?
-The Universe is naturally cold. It takes the power of a star to change that.
can insert statement works fine in case when function
for example
case when condition1=true then (first insert statement based on some condition) when condition2=true then (second insert statement based on some other condition) end
WHERE (student_id LIKE '%') AND (register_id LIKE '%') AND (register_group LIKE '%') AND
week_no = Case @Week when null Then '#' Else @Week End
the idea is if they don't enter a number it would bring up all records. This works in mangaement studio but c# brings up the error sql server doesn't support udt on excecution of the sql. This is sql server 2000. Any ideas why this doesn't work and how to fix it.
hi! i have two tables: Pictures (PictureID, UserName, UserID, DateAdded, Comments int) and UserVisits (VisitID, UserName, UserID, PictureID, NewComment bit) if a new comment is added on a picture with PictureID = 4, i update NewComment from UserVisits with 1 (true) where PictureID = 4 to all rows, and if a user visits a picture with PictureID = 5, NewComment will be set to 0 back where pictureID = 5 (something like asp.net, when a reply is added to a therad) i need to make a stored procedure with UserName input parameter witch selects ALL pictures from Pictures table and selects NewComment (true or false) from UserVisits witch corresponds with that UserName !!! Is possible that in UserVisits to not have yet any column where UserName corresponds with the user who visits if the user did not visited that picture yet (this stored procedure will be used on a Repeater witch lists all the pictures) if i was not clear please tell me, sorry i am verry bad at T-SQL language thanks in advance
Please help I'm trying to do a select command but doesn't return any record I have two tables one is "lists" another one is "list_records" in the liss table I have 4 records and in the list_records I have only one record which is tell who is already visited the site so I created a query to get people who is NOT visited the site
Here is my query (I got 0 record return)
SELECT *FROM lists list_reccords WHERE NOT EXISTS (SELECT * FROM lists, list_records WHERE list_records.is_visited = 1 AND lists.list_id = list_records.list_id)