[SQL Server 2000] - Selecting Nested Top N

Mar 30, 2004

Hi There,

We have problems getting the right records from a joined table.

First we have a table with all our Customers (eg. [Algemeen-B])
We join them with a table representing all Contacts per Customer (eg. [Algemeen-C])

An SP joins the tables because we have a few dynamic filters and parameters.

What we need is to link a maximum of @amount contacts per Customer.
Where each contact has a RANK (the TOP @amount ) joining the Customer Table.

We come thisfar:

-- The SP results this SQL select:

select *
from [Algemeen-B] left outer join
(
select * from [Algemeen-C] AS C
where exists
(
select * from [Algemeen-C]
group by bedrnummer
having bedrnummer=C.bedrnummer And min(rank) <= C.Rank and count(*) <= 2
) ) S
on [Algemeen-B].bedrnummer = S.bedrnummer
where KWP>=8

---
In this case I should return a maximum of 2 contacts per each Distinct Customer.
But I think the: 'And min(rank) <= C.Rank and count(*) <= 2' is wrong.

How can I select the TOP 2 Ranked Contacts for each Customer?
Because when there are no Contacts for the Customer it should return only the Columns for [Algemeen-B]
and NULL values for the Colums for [Algemeen-C].

If you need more info Tell me..
Hope someone can help me out..

Colin

View 6 Replies


ADVERTISEMENT

SQL Server 2000 Query - Nested Subquery Question

Jul 27, 2007

I am using SQL Server 2000. I have a somewhat large query and hope someone could help me with it.
(Man, there needs to be a way to use colors...) The bolded parts of the query need to be replaced by the underlined part. I can't say 'b.HW' because of the scope of the inline query and that they are all on the same level. I've been told I need to change to a nested subquery, but can't for the life of me figure out how to do that. Can someone please show me?
The current query:
SELECT x.SSN,x.RealName,x.BudgetCode,x.TH,b.HW,x.HP,z.HL,x.NHW,x.FSLAOT,y.HHW AS AH,y.NHH,CASE WHEN x.TH < x.HP THEN 'XX' WHEN x.TH > x.HP THEN x.NHW - x.HP - y.NHH WHEN x.TH <= x.HP THEN 0 END AS SOT,CASE WHEN x.TH > x.HP THEN x.NHW - x.HP - y.NHH + x.FSLAOT WHEN x.TH <= x.HP THEN 0 END AS AO
FROM(SELECT a.SSN,a.RealName,a.BudgetCode,SUM(a.Hours) AS TH,CASE WHEN SUM(a.hours) > 40 THEN (SUM(a.hours) - 40) * 1.5 WHEN SUM(a.hours) <= 40 THEN 0 END AS FSLAOT,CASE WHEN SUM(a.hours) >= 40 THEN 40 WHEN SUM(a.hours) < 40 THEN SUM(a.hours) END AS NHW,32 AS HP
FROM dbo.ActivitiesInCurrentFiscalYear aWHERE a.ItemDate BETWEEN startdate and enddate AND a.ScheduleType = 1 AND a.EmployeeType = 2GROUP BY a.SSN, a.RealName, a.BudgetCode) x LEFT OUTER JOIN
(SELECT a.SSN,a.RealName,a.BudgetCode,SUM(a.Hours) AS HHW,CASE WHEN SUM(a.Hours) >= 8 THEN 8 WHEN SUM(a.Hours) < 8 THEN SUM(a.Hours) END AS NHH
FROM dbo.ActivitiesInCurrentFiscalYear a, dbo.Holidays hWHERE a.ItemDate = h.HolidayDate AND a.ItemDate BETWEEN startdate and enddate AND a.EmployeeType = 2 AND a.ScheduleType = 1GROUP BY a.SSN, a.RealName, a.BudgetCode) y ON x.SSN = y.SSN AND x.RealName = y.RealName AND x.BudgetCode = y.BudgetCode LEFT OUTER JOIN
(SELECT a.SSN,a.RealName,a.BudgetCode,SUM(a.Hours) AS HLFROM dbo.ActivitiesInCurrentFiscalYear aWHERE a.ItemDate BETWEEN startdate and enddate AND a.EmployeeType = 2 AND a.ScheduleType = 1 AND (a.program_code = '0080' OR a.program_code = '0081')GROUP BY a.SSN, a.RealName, a.BudgetCode) z ON x.SSN = z.SSN AND x.RealName = z.RealName AND x.BudgetCode = z.BudgetCode LEFT OUTER JOIN
(SELECT a.SSN,a.RealName,a.BudgetCode,SUM(a.Hours) AS HWFROM dbo.ActivitiesInCurrentFiscalYear aWHERE a.ItemDate BETWEEN startdate and enddate AND a.EmployeeType = 2 AND a.ScheduleType = 1 AND NOT (a.program_code = '0080' OR a.program_code = '0081')GROUP BY a.SSN, a.RealName, a.BudgetCode) b ON x.SSN = b.SSN AND x.RealName = b.RealName AND x.BudgetCode = b.BudgetCode)

View 8 Replies View Related

Looping In SQL 2000 (Can It Be A Nested Loop)

Jul 20, 2005

I have to automate a process that assigns sales leads to sales people.For example:Every day we buy a list of sales leads, it ranges in size from 50 -100 records.We have a team of sales people that also can range from 5 - 8 people.I need to take the new records and divide them evenly among the salespeople.If i get 50 records, and have 5 sales people, then each sales persongets 10 leads.--So, im guessing that I may need to have a nested loop inside this. Ihave tried it several different ways, but cant seem to get it quiteright.DECLARE @TotalRecordCount int, @TotalSalesPeopleCount int,@AmountForEach int, @LooperSalesPeoplerecords int,@LooperNewSalesLeadsRecords int, @SalesPersonID intSELECT @TotalSalesPeopleCount = COUNT(UserId)FROM SalesPeopleWHERE Active = 1--SELECT @TotalRecordCount = COUNT(*)FROM NewSalesLeads--SELECT @AmountForEach = (@TotalRecordCount/@TotalSalesPeopleCount)--SELECT @LooperSalesPeoplerecords = 1SELECT @LooperNewSalesLeadsRecords = 1--WHILE @LooperSalesPeoplerecords <= @TotalSalesPeopleCountBEGINWHILE @LooperNewSalesLeadsRecords <= @TotalRecordCountBEGINSELECT @SalesPersonID = (SELECT UserIDFROM SalesPeopleWHERE UniqueId = @LooperSalesPeoplerecords)SELECT @LooperSalesPeoplerecords =(@LooperSalesPeoplerecords + 1)UPDATE SalesLeadsSET SalesPerson_ID = @SalesPersonIDWHERE UNIQUEID = @LooperSalesPeoplerecordsSELECT @LooperSalesPeoplerecords =(@LooperSalesPeoplerecords + 1)ENDEND----Table structuresCREATE TABLE [dbo].[SalesPeople] ([SalesPerson_ID] [int] NOT NULL ,[FirstName] [varchar](20)NOT NULL) ON [PRIMARY]--INSERT INTO SalesPeople (SalesPerson_ID,FirstName) VALUES (26, 'Bill')INSERT INTO SalesPeople (SalesPerson_ID,FirstName) VALUES (28, 'Bob')INSERT INTO SalesPeople (SalesPerson_ID,FirstName) VALUES (37,'Chris')------------------------------------------------CREATE TABLE [dbo].[SalesLeads] ([SalesLeadID] [int]NOT NULL ,[SalesPerson_ID] [int]NOT NULL) ON [PRIMARY]--INSERT INTO SalesLeads (SalesLeadID,SalesPerson_ID) VALUES (1001,0)INSERT INTO SalesLeads (SalesLeadID,SalesPerson_ID) VALUES (1002,0)INSERT INTO SalesLeads (SalesLeadID,SalesPerson_ID) VALUES (1003,0)INSERT INTO SalesLeads (SalesLeadID,SalesPerson_ID) VALUES (1004,0)INSERT INTO SalesLeads (SalesLeadID,SalesPerson_ID) VALUES (1005,0)INSERT INTO SalesLeads (SalesLeadID,SalesPerson_ID) VALUES (1006,0)------------------------------------------------So in this case, all 3 salespeople should receive 2 salesleads each.I dummied this down quite a bit. It actually ends up being more like15 sales people, and about 400,000 sales leads. But it should work onany level.Thanks for any help you might shed on this.

View 6 Replies View Related

Working In A Stored Procedure's Result Set In MSSQL 2000 (eg.: Selecting From)

Mar 4, 2004

Hy all.
My main goal would be to create some kind of map of the database, wich contains information of all connecting fields, including wich fields has key references to the other one and wich table. I'd like to have a table wich shows all the database connections tablename, field, field/table_key (from or to the key points), field_key_type (prymary or foreign)
So I thaugh to get sp_fkeys and sp_pkeys from master table and inner joining their results, but I simplay cannot "catch" their result sets. The script must have been written in SQL.
Obviously I'd like to do this:
SELECT * FROM EXEC sp_fkeys @table_name = 'xy'
of course it is not working this way, but I'd like something like this.


Please help! Thanx!

View 3 Replies View Related

Selecting The Most Recently Edited Item AND Selecting A Certain Type If Another Doesn't Exist

Sep 20, 2007

I've got a big problem that I'm trying to figure out:
I have an address table out-of-which I am trying to select mailing addresses for companies UNLESS a mailing address doesn't exist; then I want to select the physical addresses for that company. If I get multiple mailing or physical addresses returned I only want the most recently edited out of those.

I don't need this for an individual ID select, I need it applied to every record from the table.

My address table has some columns that look like:
[AddressID] [int]
[LocationID] [int]

[Type] [nvarchar](10)
[Address] [varchar](50)
[City] [varchar](50)
[State] [char](2)
[Zip] [varchar](5)
[AddDate] [datetime]
[EditDate] [datetime]

AddressID is a primary-key non-null column to the address table and the LocationID is a foreign key value from a seperate Companies table.
So there will be multiple addresses to one LocationID, but each address will have it's own AddressID.

How can I do this efficiently with perfomance in mind???

Thank you in advance for any and all replies...

View 2 Replies View Related

Sql Server Nested Set, How?

Nov 8, 2006

Hi, I'm not sure if this is  a good place to ask sql questions, so please bear with me here...I have a table like soid, parentidWhat I'm trying to do is to write a self join where given a random ID, it'll give me the  whole tree of its decendents. (I don't need its parent)so say I have data liek soid     parentid1      null2      13      2when I specificy 1, it'll give me 2 and 3, even though 3 is indirectly related to 1.  when I say 2, it'll just give me 3. Thanks a lot. GREATLY appreicate it.  

View 1 Replies View Related

Nested Table Concept In SQL Server

May 8, 2004

Hi all,

What is the equivalent for Oracle's nested table concept in SQL Server ?
Is there anything like TABLE( ) function to select from nested table as in Oracle ?

Eg in Oracle :

SELECT t.* FROM TABLE(nested_table_datatype) t;

( like the above query used in Oracle PL/SQL and 'nested_table_datatype' is a table datatype created in Oracle using 'create type ...' syntax )

Please give the equivalent for above...

Thanks,
Sam

View 2 Replies View Related

SQL Server 2012 :: Nested FOR XML Path

Oct 16, 2014

I'm trying to reverse engineer an XML output based on a client's need of a very specific format. Besides the issue of getting the XML declaration written in and removing NULLs, I'm having an issue with a three times nested PATH query.

So far the document almost has the correct format, except for the first nested root being returned. Is there any way to prevent this?

*some data redacted

Query:

DECLARE @a XML
SET @a =
(SELECT FileCreationDate,
(
SELECT PCE_TPD.PJN,
(
SELECT top (2) TaskCode, TaskName, RSI, TAFFD, AFD, Notes, PID, CUSID, NeedToBeNA

[Code] ....

Current Output (first few lines):

<TDBUIData xmlns="http://www.xxxxx">
<TDBUIData12 xmlns=""> --NEED TO ELIMINATE THIS
<FileCreationDate>2014-10-15T23:23:00</FileCreationDate>
<TDBUIDL>
<PJN>MRWSH010824</PJN>

[Code] ...

Desired Output (first few lines):

<TDBUIData xmlns="http://www.xxxxx">
<FileCreationDate>2014-10-15T23:23:00</FileCreationDate>
<TDBUIDL>
<PJN>MRWSH010824</PJN>
<TaskData>

[Code] ...

View 4 Replies View Related

SQL Server XML Destination - Nested XML File

Apr 15, 2008

I am creating an XML file from 'n' number of tables using Dataset.Writexml()

Now, I join tables using INNER JOIN and fill the resultset into a dataset (There is a foreign key called ID in each of the tables).

The resultant XML doesn't shows the nested nodes, It shows the nodes sequentially.

The Result I got was,

<Root>
<Name>
<FName>Fxxx</FName>
</Name>
<Name1>
<LName>Lxxx</LName>
</Name1>
</Root>

The FName and LName resides in different tables.


<Root>
<Name>
<FName>Fxxx</FName>
<Name1>
<LName>Lxxx</LName>
</Name1>
</Name>
</Root>


I have tried the DataTable Relations and Dataset merge.

Any work-around / Straight approaches ?

View 7 Replies View Related

SQL Server 2012 :: How To Implement Nested Tables

Dec 15, 2014

I need to perform some operations that seem to require multiple nested tables.

Is the following code the way I should be attempting this or is there a better way?

Here is the sample code:

SELECT tt.tdl_ID, tt.tx_ID, adj.Prof_Chgs, rc.Rvu_Comp
FROM Table1 as tt
LEFT JOIN (
SELECT tt1.Tdl_Id,
CASE
WHEN tt1.tdl_ID = '1000'

[code]....

View 8 Replies View Related

Internal SQL Server Error For Nested Query

May 29, 2008

Hi,

I have a following query:


select cu.Currencies_ShortName

from dbo.Currencies cu
inner join
(
select p1.Pairs_Shortname as f1, right(p1.Pairs_Shortname,3) as Currency1,

/*v1*/ -- max(SpotBid) as SpotBid, max(SpotAsk) as SpotAsk

/*v2*/ SpotBid, SpotAsk

from dbo.Pairs p1 inner join dbo.PairsQuotes pq1

on p1.Pairs_Id=pq1.Pairs_Id
and pq1.PriceDate=(select max(PriceDate) from dbo.PairsQuotes)

where p1.Pairs_Shortname like 'EUR%'

/*v1*/ -- group by p1.Pairs_Shortname, right(p1.Pairs_Shortname,3)

) as sr
on cu.Currencies_ShortName=sr.Currency1


which would work like /*v2*/, but not like /*v1*/ - there would be a message:
Server: Msg 8624, Level 16, State 3, Line 1
Internal SQL Server error.

Is Group By not manageable in a nested query, or is it some other problem?

thx
Katarina

View 5 Replies View Related

Including SQL Server Express As A Nested MSI Install

Sep 26, 2006

I'm working on an MSI-based install that installs a suite of applications. One of the applications requires SQL Server 2005 Express to be installed or already on the machine, but if the user doesn't want that app installed, I don't want to have to bother with the SQL Server issue; however, if that app is to be installed and SQL Server is not already installed, I want to be able to have it installed automatically during our install in order to make it easier for our end users. The obvious answer to this is to launch the SQL Server Express install as a nested MSI install at the appropriate point in our install. Since the SQL Server install is so complex, I was wondering if this would work if I were to launch the SQL Server install's setup.exe; or do I have to launch one of its dozen MSI files? If it's the latter, which one should my install launch? (Or is the SQL Server Express install simply too complex to be included in my install in this way? My plan is to have the SQL Server install sitting somewhere on our install CD - we've already obtained a redistribution licence - and have our install access it from there.) And will SQL Server Express appear as a separate entry in the Add/Remove Programs applet if it's installed this way? (I'd like to be able to leave SQL Server in place when uninstalling our application suite - or even just the one app that needs it - and allow SQL Server to be uninstalled separately if the user wishes.)

View 6 Replies View Related

Linked Server Nested Transaction Error

Oct 10, 2007

I have a problem in running this query on linked servers, which has distributed partitioned view.

SQLTransaction transaction;... public void DeleteAllData() { try { connection.Open(); transaction = connection.BeginTransaction(); { Console.WriteLine("Deleting All Data..."); string cmdText = ""; cmd = new SqlCommand(cmdText, connection, transaction); cmd.CommandText = "delete from NEW_ORDER where NO_O_ID > 0"; cmd.ExecuteNonQuery(); cmd.CommandText = "delete from ORDER_LINE where OL_NUMBER > 0"; cmd.ExecuteNonQuery();
transaction.Commit();
Console.WriteLine("Sucessful"); } } catch (Exception e) { Console.WriteLine("Failed in Method DeleteAllData"); throw e; } finally { connection.Close(); } }

The error returned was:

Failed in Method DeleteAllDataSQL Exception caught: Unable to start a nested transaction for OLE DB provider "SQLNCLI" for linked server "SERVER_B". A nested transaction was required because the XACT_ABORT option was set to OFF.OLE DB provider "SQLNCLI" for linked server "SERVER_B" returned message "Cannotstart more transactions on this session.".

I realized that this problem may be eliminated if I'm using stored procedures on the database, and SET XACT_ABORT ON before any transaction.

Please could anyone help me.

View 1 Replies View Related

Does The Varray Or/and Nested Table Mechanism Exists In Sql Server

Jun 6, 2007

Hi.Like in subject. I know the varray and nested tables from oracle, and I'm trying to implement them in sql server. I've been googling for any information but with no result. Can somebody direct me ??Sorry for any english mistakesThanks for help 

View 2 Replies View Related

SQL Server 2012 :: Structure For Multiple Nested Queries

Feb 27, 2014

I am using Server 2012 and very new to SQL. I have a request from a physician for a list of his patients that meet a criteria. This is stored in a temp table names #cohort.

Using this cohort he wants each row to be one patient with a list of labs, vitals, etc. Three items are the most recent lab value and date. I could query each lab individually and place it into a temp table and then join all temp tables at the end, but I am trying to move past that and have all labs in one temp table. All temp tables are joined with PatientSID.

I tried to do something for just 2 labs, but it is not working. There could be nulls values when joined with the #cohort table.

Individually the SELECT statements pull in the most recent lab value and date, but I cannot get them into a temp table with one row of PatientSID and then the lab value and date if they exist.

IF OBJECT_ID ('TEMPDB..#lab') IS NOT NULL DROP TABLE #lab
SELECT
cohort.PatientSID
,SubQuery1.LabChemResultNumericValueAS 'A1c%'
,SubQuery1.LabChemCompleteDateTimeAS 'A1c% Date'
,SubQuery2.LabChemResultNumericValueAS 'LDL'

[Code] .....

View 1 Replies View Related

SQL Server 2012 :: How To Copy Nested Sub-tree From One Node To Another

May 12, 2015

I have a tree and I need to copy a nested sub-tree (an element with its children, which in turn may have their owns) from one place to another.

The system should allow to handle up to 8 levels. I do know how to move, but cannot figure out how to copy.

Below is a working example With Create Table, Select and Cut / Paste (implemented via Update).

I would like to know how to copy a nested tree with reference id 4451 from Parent_Id 1 to Parent_Id = 2

--***** Table Definition With Insert Into to provide some basic data ****

IF (OBJECT_ID ('myRefTable', 'U') IS NOT NULL)
DROP TABLE myRefTable;
GO
CREATE TABLE myRefTable
(
Reference_Id INT DEFAULT 0 NOT NULL CONSTRAINT myRefTable_PK PRIMARY KEY,

[Code] ....

How to Copy nested sub-tree 4451 with all its children to Parent_Id 2, without deleting from Parent_Id = 1 ?

View 7 Replies View Related

SQL Server 2012 :: Nested Query Retrieving Min And Max Values?

Jul 16, 2015

I have a nested query that retrieves a min value. I would like to know how do i retrieve the corresponding time with that.

my data looks like this

valuevaluetime
1212/31/14 14:51
12.42/19/15 23:30
[highlight=#ffff11]10.92/21/15 6:40[/highlight]
13.21/25/15 20:47

My min value is 10.9 and i need the date 02/21/15

my nested query is as follows

( select min(cast(f.valuestr as float))
from bvfindings f
where f.ObjectName = 'Hematocrit'
and f.sessionid = s.sessionid
and f.ValueTime > s.open_time)

the above returns me the 10.9

i modified the query

select min(cast(f.valuestr as float)),
f.valuetime
from bvfindings f
where f.ObjectName = 'Hb'

but i get all values then.

View 6 Replies View Related

SQL Server 2012 :: Retrieve Column From Nested Query

Aug 6, 2015

I have the following query and where I need to use the t_PrevSession.DischargeTime which is in the nested query that is bolded below. How do i bring it up to the main select statement?

SELECT
s.facilityid,
s.sessionid,
s.MRN,

[code]....

View 2 Replies View Related

Problem With Nested DataTable In Server-side ADOMD.NET SP

Jan 7, 2008

Hi, I have a server-side stored procedure that I created in C#. The SP issues one DMX statement (within the implicit connection) which has a prediction join with SHAPE/APPEND. It then tries to map the results of the AdomdDataReaders to System.Data.DataTable objects, returning one System.Data.DataTable object. Because of the SHAPE/APPEND, I end up with two nested AdomdDataReaders.




Code Block

using Microsoft.AnalysisServices.AdomdServer;

using System.Data;


...


public DataTable VivaOMengoSP()
{
AdomdCommand c = new AdomdCommand(CreatePredictedDMX());


// select ... prediction join ... shape ... append



DataTable dt = new DataTable();
dt.Columns.Add("att1", typeof(string));
dt.Columns.Add("att2", typeof(int));
dt.Columns.Add("predictednestedmonster", typeof(DataTable));

object[] row = new object[3];
try
{
AdomdDataReader dr = c.ExecuteReader();
while (dr.Read())
{
DataTable innerdt = new DataTable();
innerdt.Columns.Add("inneratt1", typeof(int));
innerdt.Columns.Add("inneratt2", typeof(string));

row[0] = dr[0];
row[1] = dr[1];
AdomdDataReader innerdr = (AdomdDataReader)dr[2];
object[] innerrow = new object[2];
while (innerdr.Read())
{
innerrow[0] = innerdr[0];
innerrow[1] = innerdr[1];
innerdt.Rows.Add(innerrow);
}
row[2] = innerdt;
dt.Rows.Add(row);
}
dr.Close();
return dt;
}
catch
{
return null;
}
}
(The code is a modification to listing 20-3, page 807, of the book "Programming Microsoft SQL Server 2005" by Brust & Forte)

I call it directly in SSMS and I get this result:

Executing the query ...
Execution of the managed stored procedure VivaOMengoSP failed with the following error: Microsoft::AnalysisServices::AdomdServer::AdomdException.
Errors in the high-level relational engine. The System.Data.DataTable type is not supported by Analysis Services code name "Katmai".

Execution complete

Is it possible to have nested table as a SP result? Is DataTable the appropriate class?

Thanks,
Gustavo Frederico

View 4 Replies View Related

How To Invoke Nested Stored Procedures In SQL Server Projects In VS.NET 2005?

Jul 9, 2006

Hi,


I would like to use a stroed procedure within another stored procedure ( nested sp )

in a SQL project in VS.NET 2005. Since I have to use "context connection = true" as

connection string, I wont be able to use this connection for another sqlconnection

object. Because its already open. and If i try to use a regular connection string

("server=localhost;...") it will raise a security permission error. Having this

problem, Im not able to use nested stored procedures. Would anyone please give me a

hint how to resolve this issue?

View 4 Replies View Related

SQL Server Admin 2014 :: Script To Find Nested Views In A Database

Oct 7, 2015

Any easy way to find if there are any nested views existing in the database?...using SQL server 2014...

View 1 Replies View Related

SQLNCLI --Linked Server Provider -- Nested Query Problem (SQL 2005)

Nov 30, 2007

Ok here is a run down of the situation:

I'm running Server 'A' and Server 'B' which are both on SQL 2005 SP2. Server B connects to Server A using the linked server functionality via the SQLNCLI provider. I am issuing an update statement from a web api in a nested transaction that uses a distrubted transaction.


However, I am receiving the following error :

Unable to start a nested transaction for OLE DB provider "SQLNCLI" for linked server "A". A nested transaction was required because the XACT_ABORT option was set to OFF.
OLE DB provider "SQLNCLI" for linked server "A" returned message "Cannot start more transactions on this session.".


I've researched the issue and understand how XACT_ABORT works.

Also, I looked at the Linked Server provider options for SQLNCLI and came accross the Nested Queries option being unchecked. I checked the option and applied it to the Linked Server.

Okay, so after my long post my questions are: Do i need to restart SQL in order for this to take effect? If not, what do i need to do? I 've restarted IIS to no avail .

View 1 Replies View Related

Creating Nested Tables Inside Of A Existing SQL Server Express Table

May 26, 2007

Hello,

Quick question, I hope, I am trying to create a table that has a column that is a nested table in SQL Server 2005 Express Edition. Any ideas how I could go about doing this?

Sincerely,



James Simpson

Straightway Technologies Inc.

View 4 Replies View Related

Selecting Random Data From Sql Server

Jan 21, 2008

 I have three tables that are joined together to retrieve a piece of data.Table One has the columns pid1(PK), idTable Two has the columns pid1, qid1, idTable three has columns qid1, question, answerHere is my sql statement:SELECT  Table1.pid1, Table2.qid1, Table3.Question FROM Table1 JOIN Table2 ON Table1.pid1=Table2.pid1 JOIN Table3 ON Table2.qid1=Table3.qid1 WHERE Table1.pid=...(N)I put an elipsis because I'm stuck on how to proceed from here.  See I need to randomly select a value from column pid1 in table1 then use this value to replace N in the sql statement, then have the statement run and randomly return exactly one piece of data instead.Is this possible? How can you randomly get one piece of data from joining three table without a WHERE CLAUSE. 

View 1 Replies View Related

SQL Server 2008 :: Selecting Data From XML?

May 24, 2015

preparation of a query to get the data from xml which has xmlns in first few lines.

Here I am attaching the xml file(not able to attach ".xml" file, so converted it to ".txt" ).

View 9 Replies View Related

Selecting Distinct On 3 Columns In Ms Sql Server

Feb 26, 2006

Hi, I think you can do this in oracle but I'm trying to figure a way to do it in ms sql.. I need to select a distinct combination of columns, like so...

select distinct(ItemName,ItemData,FID) from tblSIFups

Does anyone know how to achieve that? I have multiple data where I shouldn't and I don't have any control over the application so I need to clean it this way.

thanks, nicki

View 1 Replies View Related

Security Issue While Selecting From A Linked Server:

Jul 6, 2001

NT 4/SP6a/ SQL7/SP1

I have a job owned by UserA on ServerA that selects data from ServerB. UserA
also exists on ServerB with same ID and password. UserA is dbo on ServerA
for all the databases. UserA is also member of the "System Administrators"
server role on ServerA. The job works OK. But if I remove it from "System
Administrators" server role and run the job, I get the following error
message and the job step fails:


Remote access not allowed for Windows NT user activated by SETUSER.
[SQLSTATE 42000] (Error 7410)


UserA on ServerB [remote server] has ReadOnly access. ServerB is linked to
ServerA using "they will be mapped to" option and UserA.

Any ideas!!!


Thanks

Abdul Gill

View 1 Replies View Related

SQL Server 2008 :: Selecting Records Not Between 2 Dates

Jul 22, 2015

I’m trying to extract a list of records that don’t appear between 2 dates. I have 4 tables:

tblCustomers
tblMachines
tblServiceOrders
tblMachinesServiced

tblCustomers contains a CustomerID that is unique to each customer.

tblMachines contains a list of all machines with a MachineID that is unique to each machine. It also contains the CustomerID number.

tblServiceOrders contains a list of each time each customer was serviced. It contains the ServiceDate, CustomerID, and ServiceOrderNo. But it does not have any information on the machines.

tblMachinesServiced contains a list of each machine that was serviced for each service order. It contains the ServiceOrderNo and the MachineID number.

What I want is to be able to extract a list of machines that were not serviced between 2 dates. What I end up getting is a list of machines that were serviced outside of the date range I provide.

For instance, say machine A was serviced in 2013 and 2015 but not in 2014. And say machine B was serviced in all 3 years. When I try to extract my list of machines not serviced in 2014 I end up with a list that contains machine A-2013, A-2015, B-2013 & B-2015. But what I need is just machine A-2014, since that machine wasn’t serviced in 2014.

I’ve tried several different queries but here is an example:

SELECT tblMachines.MachineID,ServiceMachines.ServiceDate
FROM tblMachines
LEFT JOIN
(SELECT MachineID, ServiceDate FROM tblServiceOrders, tblMachinesServiced
WHERE tblServiceOrders.ServiceOrderNo=tblMachinesServiced.ServiceOrderNo
) ServicedMachines
ON tblMachines.MachineID=ServicedMachines.MachineID
WHERE YEAR(ServiceDate) != '2014'

I understand why it returns the records that it does, but I'm not sure how to get what I want, which is a list of machines not serviced in 2014.

View 9 Replies View Related

SQL Server 2012 :: Selecting Max Between Two Dates For A Given Year

Jul 23, 2015

I have three tables: EMP (ID, NAME), EMPDATE (ID, STARTDATE, ENDDATE), YEAR(YEAR)

I would like to get the most recent date within a given year per each EMP? For example, EMPID 1 can be enrolled in many programs, each program has start end dates. I need to list the most recent date an employee was enrolled (max date between START AND END DATE which ever is most recent enrollment) for a given year. For example, for 2014 his/her most recent enrollment should be 10/23/2014 for year 2014 and 2013-10-24 for year 2013.

SELECT ID, EMP.NAME, DTE.StartDate, DTE.ENDDATE, year
FROM
EMP_DATE DTE join
EMP_INFO EMP on EMP.ID = DTE.ID join
YEAR YR on YR.YEAR = YEAR(DTE.STARTDATE)

DATA SAMPLE:

EMP
ID NAME
1 JOHN

EMP_INFO
ID STARTDATE ENDDATE
12013-10-24 2014-03-11
12014-06-13 2014-03-11
12014-06-15 2014-03-11
12014-09-08 2014-03-11
12014-09-12 2014-03-11
12014-09-14 2014-03-11
12014-01-13 2014-05-17
12014-05-14 2014-06-09
12014-06-10 2014-06-16
12014-08-31 2014-09-04
12014-09-05 2014-09-06
12014-09-07 2014-10-23

YEAR

Year
2012
2013
2014
2015

View 9 Replies View Related

SQL Server 2005 Reporting Svcs - How To Use Dataset 1 Info To Drive Nested Table Select

May 20, 2008

I've only been doing sql 2005 for a couple of months with minimal training so there's a lot I don't know.
What I'm trying to do is load a nested table (industry & customer totals) based on a value from the table it's nested in.
This is the relationship of the data.
I have at the highest group, an industry code, then a customer, then the part and then the fiscal year.
What I'm trying to accomplish is to get a group total (footer) for the (1) industry code and (2) the customer code. This footer would contain the fiscal years (ascending) and their monthly totals. I would like to take the industry code from table one and pass it to the select statement in the dataset that feeds the nested table. I've read this is not possible to load a dataset field into a parm but I've seen where some people know how to work around this. If you reply, please explain in simple terms. Thanks!


industry Customer Year OCT NOV DEC
001 - Signposts
M12345
Part 1
2006 5 6 2
2007 0 3 1


Part 2
2006 4 3 0
2007 1 0 7

Customer M12345 totals
2006 9 9 2
2007 1 3 8


M45678
Part 3
2007 8 4 7
2008 3 4 8


Part 4
2006 3 8 7
2007 5 6 6


Customer M45678 totals
2006 3 8 7
2007 13 10 13
2008 3 4 8
Industry 001 totals




2006 12 17 9
2007 14 13 21
2008 3 4 8

View 1 Replies View Related

Selecting Rows From SQL Server Dbs With A Where Clause Using The System Date.

Feb 1, 2008

Hello i currently have a website that has an SQL server 2005 dbs that stores appointments. I would like to do a select statement in my sqldatasource that selects all the records that have an 'appointmentDate' more than 2 weeks after the current date (ie the system date). I am stuck on the SQL statement i need to produce to achieve this. I was thinking along the lines of
SELECT * FROM appointments WHERE appointmentDate > System.Date + 14; However this is clearly not the right SQL statement. Any help would be appreciated.
Many thanks,
James.

View 5 Replies View Related

SQL Server 2012 :: Selecting Unique Record From A Table

Feb 10, 2014

I have a table (Billing Table) having multiple records for people having one record per person per each month.

How to get a list of the guys having record just for one month (say feb) and doesn't have any other months.

View 4 Replies View Related

SQL Server 2014 :: Selecting Records Based On Date

May 6, 2014

So let's say I have a table Orders with columns: Order# and ReceiptDate. Order#'s may be duplicated (Could have same Order# with different ReceiptDate). I want to select Order#'s that go back 6 months from the last ReceiptDate for each Order#.

I can't just do something like:
SELECT *
FROM Orders
WHERE ReceiptDate >= add_months(date,-6)

because there could be Order#'s whose last ReceiptDate was earlier than 6 months ago. I want to capture all of the instances of each Order# going back 6 months from each last ReceiptDate relative to each Order#.

View 9 Replies View Related







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