Get Result From 3 Tables In A SINGLE Query

Jun 17, 2014

I am using 3 tables: projects, project_manager and project_employee

projects

- project_id (int, PK)
- project_name

project_manager

- project_id (int, PK)
- manager_id (int, PK)

project_employee

- project_id (int, PK)
- employee_id (int, PK)

Assume that a manager is currently logged in (so we know what is his ID), what I trying to do is write a query that will display a grid-view showing:

project_id, project_name and number of employees in project.

I tried these quires to test:

SELECT project_id, count(emp_id) as NumberOfEmployees into #tempTable FROM project_employee WHERE project_id IN (SELECT project_id FrOM projects) GROUP BY project_id

SELECT projects.project_id, projects.project_name, NumberOfEmployees FROM projects, #tempTable WHERE projects.project_id = #tempTable.project_id

Problems are:
1 - I used two queries not one
2 - The result is for all projects of all managers, I just want to display projects for a specific manager (for example mag_id = 5)
3 - it created a temporary table - which I dont want.

Is there anyway to get what I want in a single query?

View 1 Replies


ADVERTISEMENT

How To Retrieve Two Columns From Different Tables As A Single Result Set

May 16, 2008

I have two tables that have no relation. However, both have a column which has a field of nvarchar(50) that I want to retrieve together in one operation and bind to a DropDownList in a sorted fashion. So, what I'm trying to achieve is this:
1. SELECT name FROM table1
2. SELECT name FROM table2
3. Join the two results together and order them alphabetically
4. Return the result set
I'm not sure how to do this or even if it's possible. Ideally I'm hoping it can be done in a stored proc.

View 6 Replies View Related

I It Possible To Get This Result By Single Query ?

Oct 13, 2007

hello
i am a beginner
i it possible to get this result by single query ?

i got a int column and a datetime column
is it possible to get the sum(int column) for all the year 2007 and by the april2007 and by the month n year by the person name Tony

so the end result will look like this

year 2007 | current_month | tonys_group
-----------------------------------------------
$ 222 $22 $2

View 2 Replies View Related

Query Single Col Into Several Cols Result Set

Oct 24, 2004

Hello,

I have a table with 1 column containing numeric values, and I need to create a query which displays the count of values for each set of conditions. For example, if the table contains the values 1,2,3,4,5 and 6, the output of the query should look like this:

L M H
-----------------------
3 2 1

(L are values below 4, M between 4 and 5, H is 6 and above)

Any suggestions?

TIA

View 1 Replies View Related

SQL Server 2012 :: SELECT Query - Cursor To Display Result In Single Transaction

May 25, 2015

Here the SELECT query is fetching the records corresponding to ITEM_DESCRIPTION in 5 separate transactions. How to change the cursor to display the 5 records in at a time in single transactions.

CREATE TABLE #ITEMS (ITEM_ID uniqueidentifier NOT NULL, ITEM_DESCRIPTION VARCHAR(250) NOT NULL)INSERT INTO #ITEMSVALUES(NEWID(), 'This is a wonderful car'),(NEWID(), 'This is a fast bike'),(NEWID(), 'This is a expensive aeroplane'),(NEWID(), 'This is a cheap bicycle'),(NEWID(), 'This is a dream holiday')
---
DECLARE @ITEM_ID uniqueidentifier
DECLARE ITEM_CURSOR CURSOR

[Code] ....

View 1 Replies View Related

Compare Two Tables Query Result

Jul 31, 2007

dear all
i need to write SQL Query that compares 2 tables as folows:
lets say i have:
table A with A.A, A.B, A.C columns (Table A with Columns A,B,C)
table B with B.A, B.B, B.C columns (Table B with Columns A,B,C)

i need to compare and to mark (get in result Query) each row lets say in table B that was changed from table A

For Example
Table A
A B C
12 15 hello
15 17 adv
asd 19 23
14 rer 89



Table B
A B C
12 15 hello
15 19 adv
*** 19 23
14 rer 89

the result is the records which was changed from A to B

A B C
15 19 adv
*** 19 23


Thnks alot!

View 5 Replies View Related

Can I Update Two Tables In A Single Query

Jun 14, 2008

hi friends

in my sqlserver 2005 i want to update two tables in a single query.

is it possible? or is it possible by creating a view?

thanks in advance.

shweta

View 3 Replies View Related

Joining Four Tables In A Single Query

Mar 19, 2015

I have four tables:

a, b, c and d

table a is related to table b by a foreign key. table b is related to c and so on.

I used the sql statement below to join the tables:

$result = mysql_query("SELECT a.colum1, a.column2,
b.column, c.column, d.column FROM a

JOIN b ON a.pkey = b.foreign key
JOIN c ON b.pkey = c.fkey
JOIN d ON c.pkey = d.fkey ")
or die(mysql_error());

[Code] .....

I succeeded in printing out the first record where the four tables are joined, but not other instances.my print out is this:

a.column1
a.colum2
b.colum
c.colum
d.colum

But there are about ten instances where the joining conditions are met. How do I print out all the records that have met the condition?

View 2 Replies View Related

Update Multiple Tables In Single Query

Apr 3, 2008

Hello All,

I want to update multiple tables using single query and fields name are same of tables.
I am trying like:

update tablename1 t1,tablename2 t2 set t1.fieldname1 = t2.fieldname1 = 'value' where condition;

or

update tablename1 t1,tablename2 t2 set t1.fieldname1 = 'value' t2.fieldname1 = value where condition;

Plzzzzzz help me.Thanx in advance.


Thanx & Regards,
Smita.

View 17 Replies View Related

Update Multiple Tables Using A Single Query

Nov 6, 2007

Hi,
I am using SQl server 2005.
want to update rows in 2 tables,which have a relation on Id field.

Some thing like
Update tblA a , tblB b
Set a.UpdatedDt=getdate(),b.Updateddt=getdate()
where a.Id=b.Id and a.Name='xyz'

can anyone out there help me?


Thanks
Renu

View 2 Replies View Related

Transact SQL :: Updating Multiple Tables In A Single Query?

Apr 27, 2015

Is there any way to update multiple tables in a single query. I know we can write triggers. Apart from triggers, is there any other way available in SQL Server. I am using 2008R2.

View 8 Replies View Related

Regarding The Query To Save The Ids Of The Edited Names From Different Tables Into A Single Table.

Mar 8, 2008

Here with the below query iam binding my gridview with industry name,company name,Plant Name,Group Name related to the IDs in Audit table.Select Aud.Ad_ID_PK,Aud.Audit_Name,Ind.Industry_Name,Cmp.Company_Name,Pla.Plant_Name,Gr.Groups_Name,Aud.Audit_Started_On,Aud.Audit_Scheduledto,Aud.Audit_Created_On from
Industry Ind,
Company Cmp,
Plant Pla,
Groups Gr,
Audits Audwhere Ind.Ind_Id_PK =Aud.Audit_Industry and
Cmp.Cmp_ID_PK =Aud.Audit_Company and
Pla.Pl_ID_PK =Aud.Audit_Plant and
Gr.G_ID_PK =Aud.Audit_Group and
Ad_ID_PK in (select Ad_ID_PK from Audits)
Now i want to edit these names.
when i click on edit in gridview these names will be filled into textboxes and when i change the names it should compare the name with particular tables and should get the Id of that and store in Audits table.
For example:
i have this data in my audits table:




Commercial83312

2
2
2
1
Here Commercial83312 is ID of that Audit and 2,2,2,1 are the Industry,Company,Plant and group Ids for that particular audit.In the front end i can see the names of this particular IDs.
when i edit the industry name in the UI it must check the name with industry table and get the ID of the changed name and store it in audit table.
so the data may be changed in audits table as :



Commercial83312

4
2
2
1

 




so here the industry ID is changed
I need the stored procedure for this.
please help me,its very urgent...

View 4 Replies View Related

SQL 2012 :: Single Query To Update Same Column Name In Different Tables With Where Condition?

Sep 25, 2014

I have two tables table1 and table2 and having a common column "col1"

When i ran the following query

UPDATE table1, table2 SET col1=FALSE WHERE id = 1;

getting the following error

Error Code: 1052 Column 'col1' in field list is ambiguous

id column exist in both the tables and need to update both the tables to false where the id is equivalent to 1.

how to achieve this in single query?

View 4 Replies View Related

How To Delete Unwanted Data From Multiple Different Tables With One Single SQL Query?

Mar 18, 2008

This a microsoft SQL 2000 server.
I have a DB with mutliple tables that have a column called "Date_stamp", which is used as a primary ID.
Here is my problem:
Some of tables have a bad datetime entry for the "Date_stamp". The bad entry is '2008-3-18". I need to delete this entry from every single table that has a name similary to 'Elect_Sub%Daily'.

I know how to get the user table names from the DB as follows:

SELECT name
FROM dbo.sysobjects
WHERE xtype = 'U' and name like 'Elect_Sub%Daily'

What I need to do is have a query that will basically scroll through the tables name produced by the above query and search and delete the entries that read '2008-3-18".

delete from tableName where Date_Stamp = '2008-3-18'

View 7 Replies View Related

Saving Query Result To A File , When View Result Got TLV Error

Feb 13, 2001

HI,
I ran a select * from customers where state ='va', this is the result...

(29 row(s) affected)
The following file has been saved successfully:
C:outputcustomers.rpt 10826 bytes

I choose Query select to a file
then when I tried to open the customer.rpt from the c drive I got this error message. I am not sure why this happend
invalid TLV record

Thanks for your help

Ali

View 1 Replies View Related

End Result Is Main Query Results Ordered By Nested Result

May 1, 2008

As the topic suggests I need the end results to show a list of shows and their dates ordered by date DESC.
Tables I have are structured as follows:

SHOWS
showID
showTitle

SHOWACCESS
showID
remoteID

VIDEOS
videoDate
showID

SQL is as follows:

SELECT shows.showID AS showID, shows.showTitle AS showTitle,
(SELECT MAX(videos.videoFilmDate) AS vidDate FROM videos WHERE videos.showID = shows.showID)
FROM shows, showAccess
WHERE shows.showID = showAccess.showID
AND showAccess.remoteID=21
ORDER BY vidDate DESC;

I had it ordering by showTitle and it worked fine, but I need it to order by vidDate.
Can anyone shed some light on where I am going wrong?

thanks

View 3 Replies View Related

Single Row Result From Mutliple Table Rows?

Sep 19, 2007

Hi again,

I'd appreciate advice on the following. Thanks very much!

Given this Table:
family|product|type
fam1 |abc |XX
fam1 |def |YY

What query would return this?
Family|Type1|Type2
fam1 |xx |yy


--PhB

View 8 Replies View Related

SQL Server 2012 :: Comma Separated In A Single Result

May 30, 2014

I have the following table

CREATE Table #Table1
(
ID INT, Name VARCHAR(50), Class VARCHAR(10)
)
INSERT INTO #Table1
Select 1, 'name1', 'a' UNION ALL
Select 2, 'name1', 'a' UNION ALL

[Code] ....

Is it possible to have each name and its corresponding class in a single line separated by commas to give a result like the one below in #table2 ?

CREATE Table #Table2
(
ID INT, CommaSeparated VARCHAR(100)
)
INSERT INTO #Table2
Select 1, 'name1, a' UNION ALL

[Code] ...

What I have

Select * FROM #Table1

Final Result
Select * FROM #Table2

Note that I still want to see all the IDs regardless.

If that is not possible to see all the IDs, I think the results below in #Table3 should suffice.

CREATE Table #Table3
(
CommaSeparated VARCHAR(100)
)
INSERT INTO #Table3
Select 'name1, a' UNION ALL
Select 'name2, b, c, d' UNION ALL
Select 'name3, e, f'
Select * FROM #Table3

View 3 Replies View Related

How To Synthesize A Single Row Result From A Cross-referenced Table?

Jan 13, 2008

Hello, I have an SQL problem that is hard to describe so here's an example scenario:

a) company has a personnel database, identifying each person in the company and their assigned role(s).

b) tblPersonnel has a row per person, key is 'PersonnelID'
c) tblRoles is a list of all the roles in the company (administrator, clerk, shipper, truck-driver, etc.), key is 'RoleID'

d) tblPersonnelRoles is a cross-reference of all the roles assigned to each person - in simple format of:

PersonnelID | RoleID


Given all the above, I need to have a select statement that produces one row per person, and list all the fields from tblPersonnel AS WELL AS identifies each role assigned to the person.

I'm no SQL guru .. is this even possible?

I know there are alternative solutions (e.g., to write code that for each Personnel does a lookup in Roles) but for one particular situation I need a single SQL statement, or even Stored Procedure.

Thanks in advance,
Rick Piovesan
Detaya Corp
Aurora, Ontario, Canada

View 1 Replies View Related

Stored Procedure For A Return Result Single Row With Coma(,) Seprator

May 1, 2008

Hello,
 
In SQL Server SELECT query Result displays tablePlease
tell how to create stored procedure for a single row at a time i.e. all only ONE row is
displayed at a time exselect name from useswhere name is display is tabular format,but i need in row with coma anc,d,f,f,e,g,h,jin this wayhow can i write a stored procedure for that    
 

View 4 Replies View Related

Integration Services :: Single-row Result From Querying Binding With Variable

Jul 20, 2007

I set up a connection to mysql using ADO.NET's ODBC Data Provider. And I'm running a simple query to return one table's maximum ID(int32 unsigned).But when I bind the result to a variable and excute task. It gives out error message: "An error occurred while assigning a value to variable "MaxAuditLogID": "Result binding by name "MaxID" is not supported for this connection type. " I tried to change the type of variable around but with no luck.  

View 5 Replies View Related

In SSIS Execute SQL Task, Single-row Result From Querying Mysql Binding With A Variable

Jul 20, 2007

I set up a connection to mysql using ADO.NET's ODBC Data Provider. And I'm running a simple query to return one table's maximum ID(int32 unsigned). There is no problem to achieve that.



But when I bind the result to a variable and excute task. It gives out error message: "An error occurred while assigning a value to variable "MaxAuditLogID": "Result binding by name "MaxID" is not supported for this connection type. "



I tried to change the type of variable around but with no luck.



Could anyone help with this issue? Thanks!

View 6 Replies View Related

Result From Two Tables

Oct 22, 2007

I would like to select a row (or multiple rows) from one table and at the same time all related columns from a second table (1:N)example, a phone book; selecting everyone with a certain name from the person_table and all their related phone numbers from the numbers_table, like

SELECT...

Smith, John 123456 234567 345678
Smith, Will 654321 765432 876543 987654
Smith, Eric 55564

View 4 Replies View Related

Result From 2 Tables

Dec 12, 2007

Hello,

I have a problem figuring out how I should do the following in SQL. I have 2 tables

table 1

M_Name, M_Application
A applA
b applB
c NULL
d applD

table 2

O_Name, O_Application
A applA
b applXX
c applC
d NULL

Now I need to somehow combine this to tables where M_Name and O_name should be the where clause e.g. where M_name = O_name and the result
should look something like this

Name (M_name and O_name), M_Application, O_Application
A ApplA ApplA
B ApplB ApplXX
C NULL ApplC
D ApplD NULL

I also would like to have NULLS included in the result

Thanks,
Patric

View 5 Replies View Related

SqlDataSource With Several Result Tables

Mar 14, 2007

I have an SqlDataSource that has SelectCommand as Stored Procedure. This stored procedure returns two tables. But my SqlDataSource can see first table only.
How can I see second table in Selected event of my SqlDataSource for example ?
SqlDataReader has method NextResult() for this task. How in SqlDataSource ?
I'm sorry for my English.

View 2 Replies View Related

SqlDataSource With Several Result Tables

Mar 14, 2007

I have an SqlDataSource that has SelectCommand as Stored Procedure. This stored procedure returns two tables. But my SqlDataSource can see first table only.
How can I see second table in Selected event of my SqlDataSource for example ?
SqlDataReader has method NextResult() for this task. How in SqlDataSource ?
I'm sorry for my English.

View 1 Replies View Related

Get Result Set From Two Tables Without Compare

Jan 26, 2008

Hi there,

Can someone please help me figure out how I can write a select statement that returns a row from one table and the count of records from the second table using the row name from the first table?

In other words:
First table has only one column "name" and that table name is called "namelist"
Second table has multiple columns, and the table is called "name"
so, what i want to do is something like:
select name from namelist and select count(*) from [name]

results should be:
sean,0
bob,1
tom,5
etc...

View 12 Replies View Related

SQLCE V3.5: Single SDF With Multiple Tables Or Multiple SDFs With Fewer Tables

Mar 21, 2008

Hi! I have a general SQL CE v3.5 design question related to table/file layout. I have an system that has multiple tables that fall into categories of data access. The 3 categories of data access are:


1 is for configuration-related data. There is one application that will read/write to the data, and a second application that will read the data on startup.

1 is for high-performance temporal storage of data. The data objects are all the same type, but they are our own custom object and not just simple types.

1 is for logging where the data will be permanent - unless the configured size/recycling settings cause a resize or cleanup. There will be one application writing alot [potentially] of data depending on log settings, and another application searching/reading sections of data.
When working with data and designing the layout, I like to approach things from a data-centric mindset, because this seems to result in a better performing system. That said, I am thinking about using 3 individual SDF files for the above data access scenarios - as opposed to a single SDF with multiple tables. I'm thinking this would provide better performance in SQL CE because the query engine will not have alot of different types of queries going against the same database file. For instance, the temporal storage is basically reading/writing/deleting various amounts of data. And, this is different from the logging, where the log can grow pretty large - definitely bigger than the default 128 MB. So, it seems logical to manage them separately.

I would greatly appreciate any suggestions from the SQL CE experts with regard to my approach. If there are any tips/tricks with respect to different data access scenarios - taking into account performance, type of data access, etc. - I would love to take a look at that.

Thanks in advance for any help/suggestions,
Bob

View 1 Replies View Related

SP To Perform Query Based On Multiple Rows From Another Query's Result Set

Nov 7, 2007

I have two tables .. in one (containing user data, lets call it u).The important fields are:u.userName, u.userID (uniqueidentifier) and u.workgroupID (uniqueidentifier)The second table (w) has fieldsw.delegateID (uniqueidentifier), w.workgroupID (uniqueidentifier) The SP takes the delegateID and I want to gather all the people from table u where any of the workgroupID's for that delegate match in w.  one delegateID may be tied to multiple workgroupID's. I know I can create a temporary table (@wgs) and do a: INSERT INTO @wgs SELECT workgroupID from w WHERE delegateID = @delegateIDthat creates a result set with all the workgroupID's .. this may be one, none or multipleI then want to get all u.userName, u.userID FROM u WHERE u.workgroupIDThis query works on an individual workgroupID (using another temp table, @users to aggregate the results was my thought, so that's included)         INSERT INTO @users             SELECT u.userName,u.userID                 FROM  tableU u                LEFT JOIN tableW w ON w.workgroupID = u.workgroupID                WHERE u.workgroupID = @workGroupIDI'm trying to avoid looping or using a CURSOR for the performance hit (had to kick the development server after one of the cursor attempts yesterday)Essentially what I'm after is:             SELECT u.userName,u.userID
                FROM  tableU u
                LEFT JOIN tableW w ON w.workgroupID = u.workgroupID
                WHERE u.workgroupID = (SELECT workgroupID from w WHERE delegateID = @delegateID) ... but that syntax does not work and I haven't found another work around yet.TIA!    

View 1 Replies View Related

Transact SQL :: Combine 3 Tables In One Search Result

Jul 1, 2015

I need a query to publish the front page of a blog.  Each blog post needs to show BlogTitle, BlogText, PublishDate, PublishBy, Primary Image and number of comments.  I would like to be able to do this in one sql statement, if possible.

 The table structure is below, you can assume the first image returned from the image table is the primary image.  

CREATE TABLE [dbo].[Blogs](
[ID] [int] IDENTITY(1,1) NOT NULL,
[BlogTitle] [nvarchar](200) NULL,
[BlogText] [nvarchar](max) NULL,
[Tags] [nvarchar](200) NULL,

[Code] ....

View 3 Replies View Related

Same Query Gives Result With Different Column Sequence When Used In Query Analyzer

Feb 25, 2012

When I run query in excel it gives result with different column sequence. The same query gives result with different column sequence when used in query analyzer or VBA Macro. E.g., Select * from ABC.

result in Excel 2003 SQL OLE DB query

col-A col-B col-C
values...

Result with Query Analyzer and VBA Macro

col-c col-B col-A
values...

View 3 Replies View Related

Re-display Result Set Without Re-running Query In Query Analyzer?

Apr 9, 2006

I hope I am not asking about something that has been done before, but Ihave searched and cannot find an answer. What I am trying to do is torun a query, and then perform some logic on the rowcount and thenpossibly display the result of the query. I know it can be done withADO, but I need to do it in Query Analyzer. The query looks like this:select Varfrom DBwhere SomeCriteriaif @@Rowcount = 0select 'n/a'else if @@Rowcount = 1select -- this is the part where I need to redisplay the resultfrom the above queryelse if @@Rowcount > 1-- do something elseThe reason that I want to do it without re-running the query is that Iwant to minimize impact on the DB, and the reason that I can't useanother program is that I do not have a develpment environment where Ineed to run the queries. I would select the data into a temp table, butagain, I am concerned about impacting the DB. Any suggestions would begreatly appreciated. I am really hoping there is something as simple as@@resultset, or something to that effect.

View 6 Replies View Related

Transact SQL :: SELECT On Column Name From Query Result Set In Same Query?

May 9, 2015

I have a column colC in a table myTable that has a value (e.g. '0X'). The position of a non-zero character in column colC refers to the ordinal position of another column in the table myTable (in the aforementioned example, colB).

To get a column name (i.e., colA or colB) from table myTable, I can join ("ON cte.pos = cn.ORDINAL_POSITION") to INFORMATION_SCHEMA.COLUMNS for that table catalog, schema and name. But I want to show the value of what is in that column (e.g., 'ABC'), not just the name. Hoping for:

COLUMN_NAME Value
----------- -----
colB        123
colA        XYZ

I've tried dynamic SQL to no success, probably not executing the concept correctly...

Below is what I have:

CREATE TABLE myTable (colA VARCHAR(3), colB VARCHAR(3), colC VARCHAR(3))
INSERT INTO myTable (colA, colB, colC) VALUES ('ABC', '123', '0X')
INSERT INTO myTable (colA, colB, colC) VALUES ('XYZ', '789', 'X0')
;WITH cte AS
(
SELECT CAST(PATINDEX('%[^0]%', colC) AS SMALLINT) pos, STUFF(colC, 1, PATINDEX('%[^0]%', colC), '') colC

[Code] ....

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved