Query That Join Two Tables And Retrieve A Sum

Jan 13, 2012

I want to join two tables of information together. I want to bring the order information together with the order charge. But since the OrderCharges table can have multiple values, I just want to retrieve the sum of those charges for a specific OrderID+ItemID.

My data looks something like this:

CREATE TABLE #OrderItems
(
OrderItemsID INT IDENTITY (1,1) PRIMARY KEY,
OrderID INT,
ItemID INT
)
SET IDENTITY_INSERT #OrderItems ON

[Code] ....

So I'm looking to see a result set that would like this this:

OrderItemsID-----ItemID-----OrderID----OrderDescription--OrderCharge
----1------------124---------1------------Shipping----------6.55
----2------------156---------1------------Shipping---------16.85
----3------------156---------2------------Shipping----------7.40
----4------------158---------1------------Shipping----------7.85
----5------------158---------2------------Shipping---------15.25

View 2 Replies


ADVERTISEMENT

Join Query With Three Tables

Aug 30, 2013

I need to make a query to extract data from three tables.The tables are:

Customer

CREATE TABLE [Customer] (
[CustomerCode] VARCHAR(20) PRIMARY KEY NULL,
[CustomerName] VARCHAR(60) NULL,
[CustomerNif] VARCHAR(10) NULL,

[code]....

I wrote this SQL Query based in several tutorial on the net:

"SELECT c.CustomerName, sh.IncidentDesc, sh.IncidentTechInCharge, sih.IncidentChangeTo, sih.IncidentChangeDate FROM Customer c INNER JOIN SupportHistory sh ON c.CustomerCode = 'sh.IncidentCustomerCode' INNER JOIN SupportIncidentHistory sih ON sh.IncidentID = sih.IncidentID"

but it does not return any results.

View 5 Replies View Related

Query To Join 3 Tables

Nov 15, 2013

I have 2 tables:

Element(Element_Id, Element_Name) and Parent_Child(Parent_Id, Child_Id). Parent_Id and Child Id are actually the element Ids only. An element can have more than 1 parent or more than one child.

Now i want the output like this:

Element_Id Element_Name Parent_Name Child_Name

View 3 Replies View Related

3 Tables Join Query Provlem

Oct 26, 2004

Hi

I had a problem in my query and i expalined in detail in the following link


http://www.balainfo.com/forums/viewtopic.php?t=39

View 2 Replies View Related

Related Tables: Help Needed With JOIN Query

Oct 16, 2006

Hi Group,My apologies for the lengthy post, but here goes...I have the following tables:TABLE Vehicles([ID] nvarchar(5),[Make] nvarchar(20),[Model] nvarchar(20),)TABLE [Vehicle Status]([ID] int, /* this is an auto-incrementing field*/[Vehicle ID] nvarchar(5), /* foriegn key, references Vehicles.[ID] */[Status] nvarchar(20),[Status Date] datetime)Here's my problem...I have the following data in my [Vehicles] and [Vehicle Status] tables:[ID] [Make] [Model]----------------------H80 Nissan SkylineH86 Toyota Aristo[ID] [Vehicle ID] [Status] [Status Date]----------------------------------------1 H80 OK 2006-10-012 H80 Damage 2006-10-053 H86 OK 2006-10-134 H86 Dent 2006-10-155 H86 Scratched 2006-10-16I need a query that will join the two tables so that the most recentstatus of each vehicle can be determined. I've gotten as far as:SELECT Vehicle.[ID], Make, Model, [Status], [Status Date] FROM[Vehicles] INNER JOIN [Vehicle Status] ON [Vehicles].[ID] = [VehicleStatus].[Vehicle ID]Of course this produces the following results:[ID] [Make] [Model] [Status] [Status Date]--------------------------------------------H80 Nissan Skyline OK 2006-10-01H80 Nissan Skyline Damage 2006-10-05H86 Toyota Aristo OK 2006-10-13H86 Toyota Aristo Dent 2006-10-15H86 Toyota Aristo Scratched 2006-10-16How do I filter these results so that I get only the MOST RECENT vehiclestatus?i.e:[ID] [Make] [Model] [Status] [Status Date]--------------------------------------------H80 Nissan Skyline Damage 2006-10-05H86 Toyota Aristo Scratched 2006-10-16Thanks in advance,Rommel the iCeMAn*** Sent via Developersdex http://www.developersdex.com ***

View 1 Replies View Related

Sql Query Which Uses Multiple Tables But No Common Field To Join

Jan 29, 2004

Hello-

I have a sql query that I am using to populate a datagrid. The problem is one of the tables is a month table. and the other tables are full of data. So there is no common column name to match using a inner join "on".

How do i do this?

View 6 Replies View Related

Transact SQL :: Retrieve Last Class Attended By The Student Using JOIN

May 14, 2015

In my query, I am showing Student Record and also want to retrieve the last class attended by the student using JOIN to the table (ClassHistory).

Master
ID     Student_Name
1     Arindam
2     Brenda
3     Callie

(ClassHistory)
ID     Class     Year
1     4           2003
1     5           2004
1     6           2005
2     4          2003
2     5          2004
3     4          2003

DESIRED RESULTSET
ID    Student_Name    Class Record
1    Arindam                   6
2    Brenda                     5
3    Callie                       4

The result is like - Arindam last class was Class 6, while Brenda was in Class 5 and Callie was in class 4.

Please note that the query will b part of a larger query and the Class record to be retrieved from ClassHistory if possible need to be retrieved through JOIN.

View 7 Replies View Related

How To Join 3 Tables Using Left Or Right Join Keyword?

Aug 17, 2007

Hi guys,

I'll appreciate any help with the following problem:

I need to retrieve data from 3 tables. 2 master tables and 1 transaction table.

1. Master table TBLOC contain 2 records :
rcd 1. S01
rcd 2. S02

2. Master table TBCODE contain 5 records:

rcd 1. C1
rcd 2. C2
rcd 3. C3
rcd 4. C4
rcd 5. C5

3. Transaction table TBITEM contain 4 records which link to 2 master table:
rcd 1. S01, C1, CAR

rcd 2. S01, C4, TOY
rcd 3. S01, C5, KEY
rcd 4. S02, C2, CAR



I use Left Join & Right Join to retrieve result below (using non-ASNI method) but it doesn't work.

Right Join method:


SELECT C.LOC, B.CODE, A.ITEM FROM TBITEM A RIGHT JOIN TBCODE B ON A.CODE = B.CODE

RIGHT JOIN TBLOC C ON A.LOC = C.LOC

GROUP BY C.LOC, B.CODE, A.ITEM ORDER BY C.LOC, B.CODE



When I use Non-ASNI method it work:



SELECT C.LOC, B.CODE, A.ITEM FROM TBITEM A, TBCODE B, TBLOC C

WHERE A.CODE =* B.CODE AND A.LOC =* C.LOC

GROUP BY C.LOC, B.CODE, A.ITEM ORDER BY C.LOC, B.CODE

Result:

LOC CODE ITEM
-----------------------------
S01 C1 NULL
S01 C2 NULL
S01 C3 CAR
S01 C4 TOY
S01 C5 KEY
S02 C1 NULL
S02 C2 CAR
S02 C3 NULL
S02 C4 NULL
S02 C5 NULL


Please Help.

Thanks.






View 3 Replies View Related

Retrieve Info From Two Tables

Aug 8, 2005

Hello;

I have two tables

Table 1 Rx
-------
RxNumber, RxId(no duplicates), RxDate, Name, Notes, Type, DOB

Table 2 Email
-------
EmailId, RxId(duplicates ok), Subject, Message, To, From, Type


I would like the result to be

Result Table
------------
Rx Id, RxDate, Name, Notes(or Subject), Type

Table 1 can be searched by date, or Name or DOB I want the result of this search to go through table 2 and return to me all emails that match thre previous results RxIds

For example Table 1
RxNumber, RxId, RxDate, Name, Notes, Type, DOB
1 99 1/1/2005 Person1 Note1 1 1/1/95
2 98 3/1/2005 Person2 Note2 1 1/1/96
3 97 5/1/2004 Person3 Note3 1 1/1/97
4 96 1/1/2004 Person4 Note4 1 1/1/98
5 95 6/1/2005 Person5 Note5 1 1/1/99

For Example Table 2
EmailId, RxId(dupl ok), Subject, Message, To, From, Type
1 100 S1 M1 T1 F1 2
2 98 S2 M2 T2 F2 2
3 101 S3 M3 T3 F3 2
4 95 S4 M4 T4 F4 2
5 98 S5 M5 T5 F5 2
6 95 S6 M6 T6 F6 2
7 96 S7 M7 T7 F7 2
8 98 S8 M8 T8 F8 2
9 100 S9 M9 T9 F9 2
10 100 S10 M10 T10 F10 2

If I do a search for Rxs that were prescribed from 1/1/2005 to 7/1/2005
I would like the resulting table to be
RxId RxDate Name Note/Subject Type
99 1/1/2005 Person1 Note1 1
98 3/1/2005 Person1 Note2 1
98 3/1/2005 Person2 S2 2
98 3/1/2005 Person2 S5 2
98 3/1/2005 Person2 S8 2
95 6/1/2005 Person5 Note5 1
95 6/1/2005 Person2 S4 2
95 6/1/2005 Person2 S6 2

I have tried a combination of inner joins and Union with no luck any suggestions

Thanks

Fernb200

View 2 Replies View Related

How Do I Retrieve The Available Tables In A Database

Sep 20, 2004

I need to retrieve the available tables in a database in SQL Server 2000. I found this command and although it works I can't figure out how to filter the results.

exec sp_tables

I don't want to return the whole list, just the tables starting with "OV" and "SV". Does SQL Server 2000 support a wildcard? Like can I have it search for "OV*" or do I have to use LIKE. Did google search with no helpful results. I remember in mySQL this was simply "SHOW Tables" but this command isn't supported in SQL Server 2000.

any help would be appreciated

thanks

View 1 Replies View Related

Retrieve Data From Two Tables

Apr 26, 2006

palli writes "how to retrieve data from two tables..."

View 2 Replies View Related

Retrieve Data From Two Tables

Jan 25, 2008

I need to retrieve data from 2 tables (I have a sp that populates each table) regardless if they have a match or not.

First table:
#JobListTable
job_date datetime,
job_number char(15),
job_phase char(15),
qty_delivered decimal(8,2)

Second table:
#EquentialJobListTable
job_date datetime,
job_number char(15),
job_phase char(15),
qty_received decimal(8,2)

There could be a match between the two tables, or a record could exist in one and not in the other. Result will be loaded into a DataSet and dataGrig

Can I use a join?

View 2 Replies View Related

Retrieve ALL Tables From ALL Databases

Apr 10, 2007

(SQL 2005)I'm looking to create a stored procedure to first "select name fromsys.databases where name like '%site'" then pass each name to thefollowing using some kind of loop "USE @name select name fromsys.tables where type = 'U'"I tried a while statement, but the master sys.databases recordsetdoesn't change..It's the loop I can't get to work.Any help is greatly appreciated!

View 3 Replies View Related

Retrieve Most Frequent Use Tables

May 30, 2008



Hi guys , may I know is there any way for getting the information about the tables that most use frequently in the db?

Best Regards,
Hans

View 2 Replies View Related

Webform Time Out Trying To Retrieve From Different Tables

Jun 9, 2006

I'm having a problem retrieving information from two different tables. Everytime i run a query which i type a source id into a textbox my page keeps timing out. What could be the problem? The tables i'm pulling from is profiles and phone. Here is the code. If someone could tell me what's going on id apperciate it. Thanks!
 
Dim queryString As String = "SELECT [profiles].[date_added], [profiles].[source_id], [RP_profiles].[fnam"& _"e], [profiles].[lname], [profiles].[title], [phone].[number], [RP_phone"& _"].[source_id] FROM [profiles], [phone] WHERE ([profiles].[source_id] = "& _"@source_id)"
 
 

View 3 Replies View Related

Retrieve Data From 3 Tables Which Are Related To Each Other

May 28, 2007

Hey,

I want retrieve data from 3 table my tables structure is this

tblUsers

U_ID - Name

3 John


tblGroups

G_ID - Name

5 Admins
6 Moderators


Now I want join some of the users to different groups for example John maby is a member of two groups (Admins and Moderators)

in order to do this I created a new table names tblGroupsUsers

tblGroupsUsers

ID - User_ID - Group_ID

1 3 5
1 3 6


its ok, but Now I don't know how to retrive my users list from database I don't know how to write a wuery for this
I have tried this :



strSQL = "SELECT tblUsers.name, tblUsers.U_ID, tblGroups.G_ID, tblGroupsUsers.Group_ID, tblGroupsUsers.User_ID FROM tblUsers INNER JOIN tblGroupsUsers ON tblGroupsUsers.User_ID = tblUsers.U_ID, tblGroups WHERE tblGroupsUsers.Group_ID = tblGroups.G_ID ORDER BY tblUsers.name ASC;"



Its working withut error but the problem is the results its like this


John

John


its will retrive the username twice , I think its reading based on tblGroupsUsers table because it has two rows ,
help please I need this how can I configure my query to get eache name once

Thanks

View 8 Replies View Related

Transact SQL :: How To Retrieve All Tables From A View

Jun 29, 2015

We are accessing a database through Linked Servers. That database has a bunch of views.We are able to get a list of columns for our views by querying [syscolumns]. However, how do we find out which of those columns have primary keys?

View 6 Replies View Related

Retrieve ALL Related Tables Through TSQL

Apr 30, 2008

Many HUGE Thanks to the person who knows how to do this.

Problem: My goal is to take a single data row (myDataRow) from some table (MyTable) and then retrieve every single associated record throughout the database that is related to that datarow. This requires me to first find out what tables are related to the starting table and then recursively pull all of the associated records until I get all of the records associated. Sounds simple right?

The following code only pulls back only those tables that have a child table
with an associated foreign key (i.e. a 1 -> many):


Select [Name] from sysobjects where xtype='U' and Id in(

select fkeyid from sysforeignkeys where rkeyid=

(Select Id from sysobjects where Name='<TableName>'))

order by name


But this query does not work backwards where I start with a child table
and want to know the parents (i.e. many->1 relationship)

Anybody have a clue how to retrieve these parent related tables when starting with a child table? I know it can be done because SQL Server Management lets you select a table (child OR parent) and retrieve the related table(s).

Thank you for any direction you can suggest!

Best Wishes to All
-Eric

View 6 Replies View Related

How Would I Retrieve Values From Multiple Tables In The Database?

Feb 27, 2008

 Hi, i m using vwd 2005 express and sql express. i have created following tables table_office,table_customer,table_order in my sql express. i also added one more table named table_final. In my webform i have 2 textbox and submit button plus(controls to take values for table_office,table_customer,table_order).so when user fills the form and clicks the button the data gets inserted into thier respected tables.similarly table_final gets populated with values   in this way (id,name,address,table_office_id,table_customer_id,table_order_id) Now when displaying the output in the gridview. i combined values of all these  tables together. its fine till here. Now what i want is i want to write a query to retrieve these values back into the webform . Here i want the values from all the tables back into the webform controls on a click of a button.so that i can modify it manually, make updation on it and finally show it into gridview. i hope i m able to make u understand. anyway can somebody help me with simple code(C#) and sql query to achieve this task.? thanks. jack.     

View 8 Replies View Related

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

Multi-table JOIN Query With More Than One JOIN Statement

Apr 14, 2015

I'm having trouble with a multi-table JOIN statement with more than one JOIN statement.

For each order, I need to return the following: CarsID, CarModelName, MakeID, OrderDate, ProductName, Total ordered the Car Category.

The carid (primary key) and carmodelname belong to the Cars table.
The makeid and orderdate belong to the OrderDetails table.
The productname and carcategory belong to the Product table.

The number of rows returned should be the same as the number of rows in OrderDetails.

View 2 Replies View Related

Why Does My Query Timeout Unless Force Join To Hash Join?

Jul 25, 2007

I'm using SQL Server 2005.



A piece of software I wrote starting timing out on a query that left outer joins a table to a view. Both the table and view have approximately the same number of rows (about 170000).



The table has 2 very similar columns, one is a varchar(1) and another is varchar(100). Neither are included in any index and beyond the size difference, the columns have the same properties. One of the employees here uses the varchar(1) column (called miscsearch) to tag large sets of rows to perform some action on. In this case, he had set 9000 rows miscsearch value to "g". The query then should join the table and view for all rows where miscsearch is set to g in the table. This query takes at least 20 minutes to run (I stopped it at this point).

If I remove the "where" clause and join all rows in the two tables, the query completes in about 20 seconds. If set the varchar(100) column (called descrip) to "g" for the same rows set via miscsearch, the query completes in about 20 seconds.



If I force the join type to a hash join, the query completes using miscsearch in about 30 seconds.



So, this works:

SELECT di.File_No, prevPlacements, balance,'NOT PLACED' as status FROM Info di LEFT OUTER HASH JOIN View_PP pp ON di.ram_file_no = pp.file_no WHERE miscsearch = 'g' ORDER BY balance DESC



and this works:

SELECT di.File_No, prevPlacements, balance,'NOT PLACED' as status FROM Info di LEFT OUTER JOIN View_PP pp ON di.ram_file_no = pp.file_no WHERE descrip = 'g' ORDER BY balance DESC



But this does't:

SELECT di.File_No, prevPlacements, balance,'NOT PLACED' as status FROM Info di LEFT OUTER JOIN View_PP pp ON di.ram_file_no = pp.file_no WHERE miscsearch = 'g' ORDER BY balance DESC



What should I be looking for here to understand why this is happening?



Thanks,

john















View 1 Replies View Related

Data Access :: Retrieve Schema Information Of Columns Of Tables

Sep 10, 2015

Till recently we were using the following code to retreive schema information of columns of tables

Dim schemaTable = connection.GetOleDbSchemaTable( _
System.Data.OleDb.OleDbSchemaGuid.Columns, _
New Object() {Nothing, Nothing, tableName, Nothing})

Now instead of getting the name of table (which i was using as param for filtering) i'm going to receive a sql-query. Now my question is if I were to get a query like the following :

SELECT
[EmployeeID],
[Title] + ' ' + [LastName] + ' ' + [FirstName] AS FullName,
[BirthDate],
[Address],
[City] + ', ' + [Region] + ', ' + [Country] + ' - ' + [PostalCode] AS FullAddress
FROM [dbo].[Employees]

Then how can I retrieve the schema information of only the columns present in the query.

(Its possible that i might get a query with multiple tables with joints)...

View 3 Replies View Related

Query To Retrieve Max Price Without Using Max Function And Sub Query

Mar 5, 2014

ItemIDItemNamePrice

1Item1120.00
2Item2234.00
3Item3250.00
4Item4300.00
5Item5300.00
6Item6290.00
7Item7170.00
8Item890.00
9Item9170.00

the above is the existing table and i need a query to retrieve max price with out using max function and sub query

View 6 Replies View Related

HOW To Select A Matrix (cross Join) With Empty Records To Retrieve The Same Amount Of Records For Each Cell

Nov 2, 2006

Hello

Im searching for a solution to set all matrix row or cell the same height.
it schoud looks like this example:

This is a simple matrix


test a

text b








text c








text d

text e

text f








text g










This is a matrix with all the same row-height.



test a

text b

.








text c

.
.









text d

text e

text f








text g

.

.









Thx you a lot

View 3 Replies View Related

How To Retrieve Id From That Query Line

May 30, 2008

Hey.
I have two sets of tables.
Machine Warranty table (primary key=machine_warranty_id) 
("INSERT into machine_warranty(Job_No, Cust_ID, Machine_SerialNo, Product_ID, Unit_Price, Payment_Type, Date_Installed, Freebies, Remarks, Unit_Location, Date_Paid_MW, Cheque_CC_No, Date_TrialStart, Waterblock, Pressure_Regulator, Rental) VALUES ('" + job + "','" + txt_CustID.Text + "','" + txt_MachineSerialNo.Text + "','" + txt_ProductID.Text + "','" + txt_UnitPrice.Text + "','" + dd_PaymentType.SelectedValue + "','" + txt_DateInstalled.Text + "','" + txt_Freebies.Text + "','" + txt_Remarks.Text + "','" + txt_UnitLocation.Text + "','" + txt_DatePaid_MW.Text + "','" + txt_ChequeCCNo.Text + "','" + txt_DateTrialStart.Text + "','" + dd_WaterBlock.SelectedValue + "','" + dd_PressureRegulator.SelectedValue + "','" + dd_Rental.SelectedValue + "')", connectionOne);
//machine warranty id is a primary key is auto generated already therefore not in the query line.
 
Warranty Period table (primary key=warranty_period_id/ foreign key=machine_warranty_id)("INSERT into warranty_period(Warranty_Period_ID, Warranty_Start) VALUES ('"+ txt_Warranty.Text +"','"+ txt_Warranty_Start.Text +"')", );
 
How to retrieve the machine_warranty_id from the first sql query line? So that I could use it for Warranty Period Insert statement.

View 2 Replies View Related

How To: Retrieve A Value From An Exececuted Query?

Feb 12, 2004

I would like to use a dynamic query to obtain a value...a recordcount specifically.

I have two options so far. The 2nd option works fine, but seems like it would be slower. The first option doesn't recognize that i have declared my variable (@int). Any ideas how i would use the first method...or if it's worth trying?

Method 1

--# produces error: Must declare the variable '@int'.

DECLARE @int as int
EXEC ('SELECT @int = COUNT(ProductID) FROM Products')
print @int


Method2

--# works fine...but seems less efficient.
EXEC ('SELECT ProductID FROM Products')
print @@rowcount

View 4 Replies View Related

Query To Retrieve Data From XML

Sep 9, 2014

Here is the sample xml

<ClinicalDocument xmlns:sdtc="urn:h12-org:abcd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:h12-org:v3">
<realmCode code="US" />
<typeId extension="POCD_HD000040" root="2.16.840.1.113883.1.3" />
<templateId root="2.16.840.1.113883.10.20.22.1.1" />
<id root="226ff30f-3b1f-11e3-a969-005056bb0109" />

[code]....

how to write a sql query.

View 2 Replies View Related

SQL Query To Retrieve Result Like This

Aug 24, 2007

I am using SQL Server 2005.

I have a table with records like this:

Date EmpID ADCode ADAmount
----------------------------------------------------------------------
01-Jul-07 101 GPF 150
01-Jul-07 102 GPF.ADV 100
01-Jul-07 103 GPF 250
01-Jul-07 103 GPF.ADV 200
01-jul-07 104 GPF 300

I want to show results like this using a single SQL query:

Date EmpID GPF GPF.ADV
-----------------------------------------------------------
01-Jul-07 101 150 0
01-Jul-07 102 0 100
01-Jul-07 103 250 200
01-Jul-07 104 300 0


I tried:

select PaySlipDate,EmpID,
case ADCode when 'GPF' then ADAmount else 0 end GPF,
case ADCode when 'GPF.ADV' then ADAmount else 0 end 'GPF.ADV'
from EmpSalaryRecord

It is showing like this:

Date EmpID GPF GPF.ADV
-----------------------------------------
01-Jul-07 101 0 0
01-Jul-07 101 150 0
01-Jul-07 102 0 100
01-Jul-07 103 0 0
01-Jul-07 103 250 0
01-Jul-07 103 0 200

It is showing multiple records of each employee for each date. First a record with GPF and GPF.ADV both zero and then records with values. I want a single record for each date and employee.

View 7 Replies View Related

SQL Query Question - JOIN Or Not To JOIN

Jan 2, 2006

I have 2 tables, I will add sample data to them to help me explain...Table1(Fields: A, B)=====1,One2,Two3,ThreeTable2(Fields: A,B)=====2,deux9,neufI want to create a query that will only return data so long as the key(Field A) is on both tables, if not, return nothing. How can I dothis? I am thnking about using a 'JOIN' but not sure how to implementit...i.e: 2 would return data- but 9 would not...any help would be appreciated.

View 3 Replies View Related

How To Retrieve Only Nth Row As A Result By Writing One Query.

Jan 9, 2006

How to retrieve only nth row as a result of execution of one query?
For example:
Lte the table be:

SNo     SudentName             Marks
001       Ashok kumar               67
002      
Anderson                    
70
003        Alfred  
              
        60
004        Ameeruddin  
              65
005        Kalyan
Kumar.            
69

Now the Query is: How is the 3rd ranker.    The answer must be Ashok kumar.

How to write this query in SQL Server.

View 4 Replies View Related

Query To Retrieve Unique Records

Jun 7, 2008

I am new to SQL, still learning.

If I want to retreive unique records for e.g. VendorName,City and State however no 2 vendors must be of the same city or state.

How can I do this?

I have used Select and distinct but that still brings unique vendornames in the same state and city. I only need one vendor per city and State.

Help!

View 4 Replies View Related

How Do You Write A Query To Retrieve An Attribute Value From Xml?

Oct 24, 2007



how do you write a query to retrieve an attribute value from xml?
example xml:

<PassportResponse><Passport><RequestID>200409201037256748130032433</RequestID><Status>COMPLETE</Status><CustId>33625</CustId><UserId>00000000000000000000</UserId><RequestTimeStamp>9/20/2004 10:37:25 AM</RequestTimeStamp><CompletedTimeStamp>9/20/2004 10:37:26 AM</CompletedTimeStamp></Passport><Errors /><Reports><Report product="DetailPPC"><ProductCode>LOCNF110</ProductCode><Status>COMPLETE</Status><ReportName>PPC DETAILED NETWORK</ReportName><CriticalResult /><OrderTimeStamp>9/20/2004 10:37:26 AM</OrderTimeStamp><CompletedTimeStamp>9/20/2004 10:37:26 AM</CompletedTimeStamp><RiskAddress /><ADDRESS><ScrubberCode> C1 </ScrubberCode><AddressChanged> Y </AddressChanged><HomeStreetNum>339</HomeStreetNum><HomePreDir /><HomeStreetName>ALL PEAT BEDS</HomeStreetName><HomePostDir /><HomeStreetType>RD</HomeStreetType><HomeCity>EARLTON</HomeCity><HomeState>NY</HomeState><HomeZip>12058</HomeZip><HomeZip4>2707</HomeZip4><HomeCountry>USA</HomeCountry></ADDRESS><PERSONAL><PPC><PRODHEAD><ProductName>PPC</ProductName><PPCErrorCode>L000</PPCErrorCode><PPCErrorMsg>success</PPCErrorMsg><PPCReturnSrc>ADDRESS</PPCReturnSrc><PPCRecordCnt>1</PPCRecordCnt></PRODHEAD><PRODBODY><RECORDNUMBER><PPCVal>7/9 </PPCVal><FireDistrName>COXSACKIE FPD NO 2 </FireDistrName><StateSpecificCode /><FireSubscribeDistrCode /><PPCCountyFIPS>039</PPCCountyFIPS><PPCCountyName>GREENE </PPCCountyName></RECORDNUMBER></PRODBODY></PPC></PERSONAL><COMMERCIAL><PPC><PRODHEAD><ProductName>PPC</ProductName><PPCErrorCode>L000</PPCErrorCode><PPCErrorMsg>success</PPCErrorMsg><PPCReturnSrc>ADDRESS</PPCReturnSrc><PPCRecordCnt>1</PPCRecordCnt></PRODHEAD><PRODBODY><RECORDNUMBER><PPCVal>7/9 </PPCVal><FireDistrName>COXSACKIE FPD NO 2 </FireDistrName><StateSpecificCode /><FireSubscribeDistrCode /><PPCCountyFIPS>039</PPCCountyFIPS><PPCCountyName>GREENE </PPCCountyName></RECORDNUMBER></PRODBODY></PPC></COMMERCIAL></Report></Reports></PassportResponse>'

I want to get back a table of all products. Example
Report product="DetailPPC">

want to return DetailPPC the xml may contain multiple reports I want a table with all the report products:


SELECT PassportResponse.Reports.query('.') as result FROM
@xml.nodes('/PassportResponse/Reports') PassportResponse(reports)


the sql will return the reports but I want to get what the product = only.. I'm hoping to do this without a substring function.

any help would be appreciated.


thanks

View 1 Replies View Related







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