I have 2 tables First is Student_detail and another is Employee_detail. Student_detail have 14 fields like (stud_Firstname,stud_Lastname...) and Employee_detail have 17 fields like(emp_Firstname,emp_Lastname...).there is no relationship between these two table and also not in a relationship with any other table in my database.This is a structure of my db. but i want to get the records from these two table whose first name is same for both the tables.as well as the result of this query will first show me Student_detail record first and then Employee_detail record.but not in a one row.it should be display in one by one.
How to write a sql to combine the 4 tables into one without repetitive records? The 4 tables have exactly the same fields.
The tables do not have primary key. The fields to identiry the rows is name and dob. In the case the name and dob is same for two records, the one with latest date_created is selected.
I have the following table;CREATE TABLE [x_Note] ([x_NoteId] [int] IDENTITY (1, 1) NOT NULL ,[Note] [varchar] (7200) COLLATE SQL_Latin1_General_Pref_CP1_CI_AS NOTNULL ,CONSTRAINT [PK_x_NoteId] PRIMARY KEY CLUSTERED([x_NoteId],) WITH FILLFACTOR = 90 ON [USERDATA] ,) ON [USERDATA]GOMy clients want me to take the contents of the Note column for each rowand combine them. In other words, they basically want:Note = Note [accumulated from previous rows] + Char(13) [because theywant a carriage return] + Note [from current record].What is the most efficient and relatively painless way to do this? Ithink it might require a cursor, but I'm not sure if there is a moreelegant set-based method to make this happen.
Hi all,We have an app that uses SQL 2000. I am trying to track when a code field(selcode) is changed on an order which then causes a status field (status)to change. I tried a trigger but the app may use 2 different updatestatements to change these fields depending on what the user does. When thetrigger fires (on update to selcode), the status field has already beenchanged. So my trigger to record the changes from inserted and deleted donot get the true 'before' value of the status field.The app does use a log table that tracks these changes. The problem I amhaving is that 2 records are created, one for the change to selcode andanother for the change to status.I am looking for help with a script to combine the existence of these 2 logrecords into 1 unique record or occurance that I can track.example:ordlog: table that logs order changesordernr: order numbervarname: name of field being changedold_value: contents of field before changenew_value: contents of field after changesyscreated: date/time of log entrySELECT ordernr, varname, old_value, new_value, syscreatedFROM ordlogwhere varname = 'selcode' and ordernr = '10580'SELECT ordernr, varname, old_value, new_value, syscreatedFROM ordlogwhere varname = 'status' and ordernr = '10580' and old_value = 'A' andnew_value = 'O'So I need a way to combine these 2 log entries into a unique occurance. Theordernr and syscreated could be used to link records. syscreated alwaysappears to be the same for the 2 log entries down to the second. Selcodecan change from NULL to a number of different values or back to NULL.Statusis either 'A' for approved or 'O' for open. An order can have many logentries during its life. The selcode may be changed several times for thesame order.Ideally, I would like a result that links 2 log entries and shows the statuschanged from 'A' to 'O' when selcode changed.Thanks for your time.
This is how the data is organized:vID Answer12 Satisfied12 Marketing12 Yes15 Dissatisfied15 Technology15 No32 Strongly Dissatisfied32 Marketing32 YesWhat I need to do is pull a recordset which each vID is a single rowand each of the answers is a different field in the row so it lookssomething like thisvID Answer1 Answer2 Answer312 Saitsfied Marketing Yesetc...I can't quite get my mind wrapped around this one.
I need to return one record with concatenated string fields from a table that may contain several records. I think a cursor will be able to do what I want, but I'm not very experienced at writing them.
My data
HDR DMCD 107 TEX 107 AIR 107 LG 108 TEX 108 CAR 109 SM
I want the result of my query to find adn return each header and return the 1 or more DMCD field values concatenated. i.e.
I'm working on a report where my table is as follows:
WITH SampleData (ID,NAME,[VALUE]) AS ( SELECT 170983,'DateToday','6/04/2014' UNION ALL SELECT 170983,'DateToday','6/04/2014' UNION ALL SELECT 170983,'employee','1010' UNION ALL SELECT 170983,'employee','1010'
[Code] .....
Here is my query against the table above:
SELECT ID ,MAX(CASE WHEN NAME = 'employee' THEN VALUE END) AS PERSON ,MAX(CASE WHEN NAME = 'DateToday' THEN VALUE END) AS REQUEST_DATE ,MAX(CASE WHEN NAME = 'LeaveStartDate' THEN VALUE END) AS REQUEST_START_DATE ,MAX(CASE WHEN NAME = 'LeaveEndDate' THEN VALUE END) AS REQUEST_END_DATE ,MAX(CASE WHEN NAME = 'HoursPerDay' THEN VALUE END) AS REQUESTED_HOURS ,MAX(CASE WHEN NAME = 'LeaveType' THEN VALUE END) AS REQUEST_TYPE
FROM SampleData
Here is the result from the above query, I'm not sure how to get the desired results (listed at the end):
I have a robust query that returns a dataset and the data is good, however some of the records contain the exact same data with the exception of the 'Price' field. I want to combine the records that are identical and SUM the values in the 'Price' field. My query and example return dataset is below.
Query: -------- select distinct 'On-Demand' as 'Business Line', o.OrderID as 'Order #', isnull(d.DisplayCode,'UNK') as Hub, isnull(rz.RouteID,'UNK') as 'Default Route', 'On-Demand' as 'Assigned Route',
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.
I can use the IN with the WHERE clause as example:SELECT * FROM NORTHWIND WHERE LASTNAME IN ('FULLER','KING')I want to use the IN and LIKE at the same time:SELECT * FROM NORTHWIND WHERE LASTNAME LIKE ('A%','B%')I know this is a simplistic example, but the members for the IN will bemany, 5 to 10.I'm trying to avoid:SELECT * FROM NORTHWIND WHERE LASTNAME LIKE 'A%' OR LASTNAME LIKE 'B%'OR LASTNAME LIKE 'FU%' OR LASTNAME LIKE 'JON%' <...>and so forth.Any Ideas?TIARob
I have a table with multiple rows with the same ID. a) How do I combine all columns into one row with the same ID? b) Is this better to do the combine in the store procedure/trigger or a sub that involked by some sort of datarepeater, datagrid controls? Since I am trying to brush up my sql. I appreciate any examples on top of conceptual solution.
Combine 3 Databases, Not tables. Let me spell this out -- I have 3 databases (they are in isolation when in use, its a field app) that need to be merged into 1 "masterDB" database. I've discovered I can use something like this to get to each DB in a query... 1 USE [database1]2 SELECT table1.Name, table1.Location, table1.Date, table2.Blog3 FROM table2 INNER JOIN4 table1 ON table2.ID = table1.ID5 ORDER BY table1.Date and then just repeat for database2 and database3. Ok, fine, rah rah. My question is how do I "merge" all of these into 1. No data on each db will be identical, at all, ever so that is not a concern. I just need all the data from db1, 2 and 3 into masterDB. Ideas? Direction?
Hello, I have these variables on my page: userid = "10101" RequestHost = "example.com" What would be the best way performace wise to first check if the userid 10101 exists in my sql server db. If it does exist I would then need to check if "example.com" exists for the userid in the userdomains table. If these both exist I would then like to query some additional data. I was hoping its possible to combine this into one query somehow. I dont think this is the best solution: sqlcommand.CommandText = "SELECT UserId From Users Where UserID = '10101'" Conn.Open() dr = sqlcommand.ExecuteReader if dr.hasrows then sqlcommand2.CommandText = "SELECT UserDomain From UserDomains Where UserID = 'example.com'" dr2 = sqlcommand2.ExecuteReader if dr2.hasrows then sqlcommand3.CommandText = 'Select Additional Data dr3 = sqlcommand3.ExecuteReader 'read values conn.close else conn.close 'do something end if else conn.close 'do something end if Thanks Very Much!
I have an stored procedure that returns 3 columns. Month, Date, and Total Number of Calls. Here is the stored Proc: SELECT DATEPART(mm, CALLSTARTTIME) , DATEPART(dd, CALLSTARTTIME), COUNT(*) FROM CALL_LOG_MASTER WHERE (COMMERCIALS = '1') AND (PINCODE IS NOT NULL) GROUP BY DATEPART(mm, CALLSTARTTIME), DATEPART(dd, CALLSTARTTIME) ORDER BY DATEPART(mm, CALLSTARTTIME), DATEPART(dd, CALLSTARTTIME) It returns a table: MONTH DATE TOTAL NUMBER OF CALLS======= ===== ===========1 1 10 1 2 15 My question is: is it possible to combine the Month and Date column into one column. e.g. Date Total Number of Calls==== ==============1/1 101/2 15 Please Help, Thanks in advance :)
I am looking for the correct T-sql statement. I want to put parameters in a SP from a select statement. And make the SP exec for each records that the select statement returns. The following is the SP that I want to pass the parameters.
-- Create the CDONTS NewMail object. EXEC @hr = sp_OACreate 'CDONTS.NewMail', @object OUT IF @hr <> 0 GOTO ObjectError
-- Add the optional properties if they are specified IF @Body IS NOT NULL BEGIN EXEC @hr = sp_OASetProperty @object, 'Body', @Body IF @hr <> 0 GOTO ObjectError END
IF @Cc IS NOT NULL BEGIN EXEC @hr = sp_OASetProperty @object, 'Cc', @Cc IF @hr <> 0 GOTO ObjectError END
IF @Bcc IS NOT NULL BEGIN EXEC @hr = sp_OASetProperty @object, 'Bcc', @Bcc IF @hr <> 0 GOTO ObjectError END
IF @HTMLFormat <> 0 BEGIN EXEC @hr = sp_OASetProperty @object, 'MailFormat', 0 IF @hr <> 0 GOTO ObjectError END
-- Loop through the ; delimited files to attach CREATE TABLE #FileExists (FileExists int, FileIsDir int, ParentDirExists int)
WHILE isnull(len(@Attachments),0) > 0 BEGIN SELECT @StrEnd = CASE charindex(';', @Attachments) WHEN 0 THEN len(@Attachments) ELSE charindex(';', @Attachments) - 1 END SELECT @Attachment = substring(@Attachments, 1, @StrEnd) SELECT @Attachments = substring(@Attachments, @StrEnd+2, len(@Attachments))
-- Ensure we can find the file we want to send. DELETE #FileExists INSERT #FileExists EXEC master..xp_fileexist @Attachment
IF NOT EXISTS (SELECT * FROM #FileExists WHERE FileExists = 1) BEGIN RAISERROR ('File %s does not exist. Message not sent.', 16, 1, @Attachment) RETURN 1 END
I have two tables in MS SQL 2000 that I need to combine into one. they will share 3 columns and the rest will stay the same. the existing tables are very large and I REALLY don't want to plug in all the data by hand...Any nifty tricks??? I found software but dont want to spend $$ on it.
Here is my dilemma, i'm trying to combine the results of two different tables. Both tables are very similar but the data returned must be sorted before they are combined because I'm only returning the top xx records based on a hits column.
I have tried the following union query which combines the two RS's then sorts the data: SELECT Top 2 ID, Song, Hits FROM Table1 UNION SELECT Top 2 ID, Song, Hits from Table2 Which would return the first two records from each then sort them like this: 2 - tb1SONG 2 - 1459 1 - tb2SONG 1 - 412 1 - tb1SONG 1 - 356 2 - tb2SONG 2 - 85
I would like to sort based on the hits column then combine the RS producing this: 3 - tb2SONG 3 - 2035 2 - tb1SONG 2 - 1459 4 - tb1SONG 4 - 965 5 - tb2SONG 5 - 745
Any ideas or solutions will be greatly appreciated. Thanks
SELECT bms_id,email_address,COUNT(*) INTO #temp FROM emp_db WHERE email_address IS NOT NULL GROUP BY bms_id,email_address ORDER BY bms_id DESC,COUNT(*) DESC
SELECT bms_id COUNT(*) FROM #TEMP GROUP BY bms_id ORDER BY COUNT(*) DESC
How can i put these two statements into a single sql statement.
I need to combine to sql queries. Separately they work fine, but I need the "total qty" from second query put into the first query
Query 1
SELECT dbo.Job.CompanyJobId, dbo.Job.Name, dbo.Region.CompanyRegionID, dbo.Job.Active, dbo.Job.ChangeDate FROM dbo.Job LEFT OUTER JOIN dbo.Division ON dbo.Job.DivisionGuid = dbo.Division.DivisionGuid LEFT OUTER JOIN dbo.Region ON dbo.Job.RegionGuid = dbo.Region.RegionGuid LEFT OUTER JOIN dbo.JobType ON dbo.Job.JobTypeGuid = dbo.JobType.JobTypeGuid WHERE dbo.job.CompanyJobId = 3505048 ORDER BY dbo.Job.CompanyJobId
Query 2
SELECT case dbo.SourceType.CompanySourceTypeId when 'PR' then SUM(dbo.ProductionEvent.Quantity) end AS Ttl_Qty FROM dbo.Batch INNER JOIN dbo.Event ON dbo.Batch.BatchGuid = dbo.Event.BatchGuid INNER JOIN dbo.Job ON dbo.Event.JobGuid = dbo.Job.JobGuid INNER JOIN dbo.ProductionEvent ON dbo.Event.EventGuid = dbo.ProductionEvent.EventGuid INNER JOIN dbo.Item ON dbo.Event.ItemGuid = dbo.Item.ItemGuid INNER JOIN dbo.Source ON dbo.ProductionEvent.SourceGuid = dbo.Source.SourceGuid INNER JOIN dbo.SourceType ON dbo.Source.SourceTypeGuid = dbo.SourceType.SourceTypeGuid LEFT OUTER JOIN dbo.Product ON dbo.ProductionEvent.ProductGuid = dbo.Product.ProductGuid left outer join dbo.JobNoteEvent on Event.EventGuid = dbo.JobNoteEvent.EventGuid WHERE dbo.Job.CompanyJobId = 3505048 and dbo.SourceType.CompanySourceTypeId = 'PR' GROUP BY dbo.SourceType.CompanySourceTypeId
I have tried this but it doe not work:
SELECT dbo.Job.CompanyJobId, dbo.Job.Name, dbo.Region.CompanyRegionID, dbo.Job.Active, dbo.Job.ChangeDate, Ttl_Qty FROM dbo.Job LEFT OUTER JOIN dbo.Division ON dbo.Job.DivisionGuid = dbo.Division.DivisionGuid LEFT OUTER JOIN dbo.Region ON dbo.Job.RegionGuid = dbo.Region.RegionGuid LEFT OUTER JOIN dbo.JobType ON dbo.Job.JobTypeGuid = dbo.JobType.JobTypeGuid WHERE dbo.job.CompanyJobId = 3505048 and where Ttl_Qty =
(SELECT case dbo.SourceType.CompanySourceTypeId when 'PR' then SUM(dbo.ProductionEvent.Quantity) end AS Ttl_Qty FROM dbo.Batch INNER JOIN dbo.Event ON dbo.Batch.BatchGuid = dbo.Event.BatchGuid INNER JOIN dbo.Job ON dbo.Event.JobGuid = dbo.Job.JobGuid INNER JOIN dbo.ProductionEvent ON dbo.Event.EventGuid = dbo.ProductionEvent.EventGuid INNER JOIN dbo.Item ON dbo.Event.ItemGuid = dbo.Item.ItemGuid INNER JOIN dbo.Source ON dbo.ProductionEvent.SourceGuid = dbo.Source.SourceGuid INNER JOIN dbo.SourceType ON dbo.Source.SourceTypeGuid = dbo.SourceType.SourceTypeGuid LEFT OUTER JOIN dbo.Product ON dbo.ProductionEvent.ProductGuid = dbo.Product.ProductGuid left outer join dbo.JobNoteEvent on Event.EventGuid = dbo.JobNoteEvent.EventGuid WHERE dbo.Job.CompanyJobId = 3505048 and dbo.SourceType.CompanySourceTypeId = 'PR' GROUP BY dbo.SourceType.CompanySourceTypeId)
I have a query that looks at the stock levels in one warehouse and returns the quantity, have been asked to create a new column that shows the total of the same stock that is available in our two other warehouses.
Have tried this: SELECT ItemCode, WhsCode, InStock FROM TABLE1 INNER JOIN TABLE2 ON TABLE1.WhsCode = TABLE1.WhsCode WHERE WhsCode = '31' or WhsCode = '61' GROUP BY InStock, WhsCode,ItemCode
This returns the results in one column rather than in a seperate column for 31 & 61, I then need to add the two columns together so a total stock is shown.
I realise this may be a basic query but I'm batting my head against a wall at the moment.
I have two statements getting data from two different tables.
1: select dataDate from table1,- gives ‘20080325’
2: select count (recordNumber) from table2,-- gives ‘4566’
Each table has one row but more than one column. The columns are not the same in each table.
Question. I need to combine two statements to give the outcome in one row as '200803254566'. '2008032' from first statement and '54566'from second statement. How do you combine them? ?
I wonder if anyone can help. All I am trying to do is combine three SQL SELECT queries into one. They are:
SELECT COUNT(ISNULL(Result, 0)) AS Win FROM Games WHERE (CurrentSeason = 'True') AND Result = 'Win'AND ([MatchType] = @MatchType)
SELECT COUNT(ISNULL(Result, 0)) AS Lose FROM Games WHERE (CurrentSeason = 'True') AND Result = 'Lose'AND ([MatchType] = @MatchType)
SELECT COUNT(ISNULL(Result, 0)) AS Draw FROM Games WHERE (CurrentSeason = 'True') AND Result = 'Draw'AND ([MatchType] = @MatchType)
As you can see they are all doing pretty much the same thing. I have experimented by using GROUP and HAVING but end up with no results. Sorry if this is obvious but I am new to SQL!
I have a table that has two dates in it, a date opened and a dateclosed. I would like to create one query to give me the number ofrecords that have been opened each month plus, and this is the hardpart the number of those records that have been closed each month. Ican get the result with two seperate queries but have been unable toget it combined into one query with three values for each month, i.e.,the month, the number opened and the number of those that were openedin the month that have been subsequently closed.Here's my two queries. If anyone can help I'd appreciate.SELECT COUNT(*) AS [Number Closed], LEFT(DATENAME(m, DateOpened),3) + '' + CAST(YEAR(DateOpened) AS Char(5)) AS [Month Opened]FROM tableWHERE (DateClosed IS NOT NULL)GROUP BY CONVERT(CHAR(7), DateOpened, 120), LEFT(DATENAME(m,DateOpened), 3)+ ' ' + CAST(YEAR(DateOpened) AS Char(5))ORDER BY CONVERT(CHAR(7), DateOpened, 120)SELECT COUNT(*) AS [Number Opened], LEFT(DATENAME(m, DateOpened),3) + '' + CAST(YEAR(DateOpened) AS Char(5)) AS [Month Opened]FROM tableGROUP BY CONVERT(CHAR(7), DateOpened, 120), LEFT(DATENAME(m,DateOpened), 3)+ ' ' + CAST(YEAR(DateOpened) AS Char(5))ORDER BY CONVERT(CHAR(7), DateOpened, 120)TIABill