Transact SQL :: Additional Restriction On Inner Join Needed

Sep 28, 2015

I have two employee tables called EmpA and EmpB.Each table has the same attributes of Employee ID and Email address.I do an inner join on email address like this:

select * from EmpA
inner join EmpB on EmpA.email = EmpB.email
where EmpB like '%@mydomain.com'

I now want to modify the above where I want to output rows such that

 EmpA.employeeid <> EmpB.employeeid

View 9 Replies


ADVERTISEMENT

Additional Criteria In LEFT JOIN

Jan 18, 2008

I have a stored procedure which is used to search records in the database based on the data sent from the web page. There are several search fields and all of them are in one table (Table1) except the "CallerName" field which is in a different table (Table2). Since I had to show CallerName also in the gridview apart from other columns, I did a LEFT JOIN (using field CallerNumber) to show all the required fields from Table1 and CallerName from Table2.
Now heres the problem. Since CallerName is a search criteria, its supposed to be in the WHERE clause after the JOIN or in the JOIN clause itself. The problem is, if I put it in WHERE clause, the result set doesn't show records from Table1 which do not have a matching CallerNumber in Table2. SELECT T1.CallerNumber, T1.DateCalled, T2.CallerName
FROM Table1 T1
LEFT JOIN Table2 T2 on
T1.CallerNumber = T2.CallerNumber
WHERE T1.CallerNumber = 'some number' AND T2.CallerName = 'some name' If I put it in the JOIN condition, it works just like a LEFT JOIN is supposed to work, showing all the records in Table1 and also those which had CallerName in Table2. SELECT T1.CallerNumber, T1.DateCalled, T2.CallerName
FROM Table1 T1
LEFT JOIN Table2 T2 on
T1.CallerNumber = T2.CallerNumber AND T2.CallerName = 'some name'
WHERE T1.CallerNumber = 'some number'

1st SQL won't work for me because it doesn't show all the records in Table1, even when no search criteria is specified.2nd SQL won't work for me because it shows more than required when just CallerName is sent from the web page as search criteria. It will show all the records where CallerName is "some name" and also all the additional records (since it is a left join).
Can I get the goodness of both in one or do I have to create two separate Stored Procedures?
Thanks all,Bullpit
 

View 11 Replies View Related

T-SQL (SS2K8) :: Additional Join Causing Duplicates?

Mar 9, 2015

I have this statement:

SELECT top 100 P.LastName ,
P.FirstName,
P.MiddleName,
P.PractitionerTypeID,
P.SuffixID,
A.Linenumber1,
A.LineNumber2,
Z.City,

[code]....

Seems like no matter which join type I choose i still get duplicates.

View 5 Replies View Related

Transact SQL :: Additional Column With Bulk Insert?

Aug 11, 2015

Need to know a mode whereby somehow I can every time insert an additional column in a table while bulk inserting data to an existing table from a new flat file thus identifying the file from which, or the time when, the data was inserted in an existing table.

View 2 Replies View Related

Transact SQL :: Column Length Restriction When Naming CTE Column?

Jun 22, 2015

My CTE is failing and I don't know why...Is there a Common Table Expression column name length restriction???

View 2 Replies View Related

Transact SQL :: Difference Between Inner Join And Left Outer Join In Multi-table Joins?

Oct 8, 2015

I was writing a query using both left outer join and inner join.  And the query was ....

SELECT
        S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
        Production.Suppliers AS S LEFT OUTER JOIN
        (Production.Products AS P
         INNER JOIN Production.Categories AS C

[code]....

However ,the result that i got was correct.But when i did  the same query using the left outer join in both the cases

i.e..

SELECT
        S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
        Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
LEFT OUTER JOIN Production.Categories AS C
ON C.categoryid = P.categoryid)
ON
S.supplierid = P.supplierid
WHERE
S.country = N'Japan';

The result i got was same,i.e

supplier     country    productid    productname     unitprice    categorynameSupplier QOVFD     Japan     9     Product AOZBW    97.00     Meat/PoultrySupplier QOVFD    Japan   10     Product YHXGE     31.00     SeafoodSupplier QOVFD     Japan   74     Product BKAZJ    10.00     ProduceSupplier QWUSF     Japan    13     Product POXFU     6.00     SeafoodSupplier QWUSF     Japan     14     Product PWCJB     23.25     ProduceSupplier QWUSF    Japan     15    Product KSZOI     15.50    CondimentsSupplier XYZ     Japan     NULL     NULL     NULL     NULLSupplier XYZ     Japan     NULL     NULL     NULL     NULL

and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.

View 5 Replies View Related

Help Needed With A Join

Apr 8, 2008

SELECT * FROM A INNER JOIN
B ON A.AId =
(SELECT B.BId
FROM B
WHERE (B.AId = 4))

I have two tables
Table A has several columns and B has just two columns
B.AId and B.BId.

I will pass B.AId as a parameter and that will return more than one B.BId values. Then I need to create a join where A.AId matches B.BId.

I tried the above SQL but it says subquery can't return more than one value. In my case it must return more than on value.
How can I construct the SQL query.
Please Help.
Thanks

View 3 Replies View Related

Inner Join And Union Help Needed

Dec 7, 2006

Ok, getting a little better at joins, but now need to take it two more steps.Main table tblEquipmentsFields: ID, EquipmentType, Location, StatusSecond Table tblEquipments_GroupFields: equipmentID, categoryID, subCategoryID (all are ints)I joined these two together and got the info back I needed:SELECT a.ID, a.Description, a.Status, a.Location, from tblEquipments ainner join tblEquipments_Group U on u.categoryID = a.EquipmentTypeand u.subCategoryID = @type Now, the a.status returns a number. What the status actually is is in tblStatus.Fields: statusID (int) , Status (varchar).So, the statusID matches a.Status.I need to get the text from tblStatus in the field Status and replace the a.Status (which is a number still) with the text.The other one, location, is the same situation.I've been trying to do another join and am at an end on this.Suggestions?Thanks!!Zath

View 2 Replies View Related

What Type Of Join Needed?

Feb 22, 2008

I need to find all of the records Table A with ID values that are not found in Table B.  What type of join do I need? Is there such a join?
Thank you

View 4 Replies View Related

Left Join Help Needed!

Dec 27, 2007

I’m attempting to use a Left Join to pull information from a table that contains my objectives and place in with information from a Summary table. I use one where clause per Left Join, that defines which rows from the objective table I want that left join to represent (for instance “(mdt.SLA_NAME = 'Duration MNOC to NDC % Met SLA' OR mdt.SLA_NAME IS NULL )� ). I have 7 left joins and where statements.

The problem I’m having is that the where clause are removing all rows where the Left Join does not result in a match, despite the fact that I have the OR IS NULL in the where clause.

Can anyone help!

The full SQL is as follows:


SELECT DATE_DAY
, SEVERITY
, ENTRY_TYPE
, EQ_REGION
, EQ_MARKET_CLUSTER
, FORCE_STATUS
, NUM_CREATED
, NUM_OPEN
, NUM_AWAITING_DISPATCH
, NUM_OPEN_IN_DUE_DATE
, NUM_DISPATCH_TO
, DURATION_DISPATCH_TO
, SLA_DURATION_DISPATCH_TO
, SLA_DURATION_DISPATCH_TO_G_L
, MET_SLA_DISPATCH_TO
, mdt.SLA AS SLA_MET_DISPATCH_TO
, mdt.SLA_G_L AS SLA_MET_DISPATCH_TO_G_L
, C_NUM_DISPATCH_TO
, C_DURATION_DISPATCH_TO
, C_SLA_DURATION_DISPATCH_TO
, C_SLA_DURATION_DISPATCH_TO_G_L
, C_MET_SLA_DISPATCH_TO
, mdt.SLA AS C_SLA_MET_DISPATCH_TO
, mdt.SLA_G_L AS C_SLA_MET_DISPATCH_TO_G_L
, NUM_DISPATCH_FROM
, DURATION_CREATE_TO_DISPATCH_FROM
, NUM_DISPATCH_TO_TO_FROM
, DURATION_DISPATCH_FROM
, SLA_DURATION_DISPATCH_FROM
, SLA_DURATION_DISPATCH_FROM_G_L
, MET_SLA_DISPATCH_FROM
, mdf.SLA AS SLA_MET_DISPATCH_FROM
, mdf.SLA_G_L AS SLA_MET_DISPATCH_FROM_G_L
, C_NUM_DISPATCH_FROM
, C_DURATION_CREATE_TO_DISPATCH_FROM
, C_NUM_DISPATCH_TO_TO_FROM
, C_DURATION_DISPATCH_FROM
, C_SLA_DURATION_DISPATCH_FROM
, C_SLA_DURATION_DISPATCH_FROM_G_L
, C_MET_SLA_DISPATCH_FROM
, mdf.SLA AS C_SLA_MET_DISPATCH_FROM
, mdf.SLA_G_L AS C_SLA_MET_DISPATCH_FROM_G_L
, NUM_CLOSED
, DURATION_WIP_TO_RESOLVE
, SLA_WIP_TO_RESOLVE
, SLA_WIP_TO_RESOLVE_G_L
, MET_SLA_WIP_TO_RESOLVE
, wip.SLA AS SLA_MET_WIP_TO_RESOLVE
, wip.SLA_G_L AS SLA_MET_WIP_TO_RESOLVE_G_L
, DURATION_MTTR
, SLA_MTTR
, SLA_MTTR_G_L
, MET_SLA_MTTR
, mttr.SLA AS SLA_MET_MTTR
, mttr.SLA_G_L AS SLA_MET_MTTR_G_L
, NUM_RESOLVE_FD
, rfd.SLA AS SLA_RESOLVE_FD
, rfd.SLA_G_L AS SLA_RESOLVE_FD_G_L
, NUM_DISPATCH_NTF
, ntf.SLA AS SLA_DISPATCH_NTF
, ntf.SLA_G_L AS SLA_DISPATCH_NTF
, AR_NUM_MET_DUE_DATE
, ar.SLA AS AR_SLA_MET_DUE_DATE
, ar.SLA_G_L AS AR_SLA_MET_DUE_DATE
FROM (
SELECT DATE_DAY
, CASE
WHEN upper(ENTRY_TYPE) = 'ACTION REPORT' THEN
(CASE WHEN PROBLEM_CATEGORY IN ('Compliance','Routine') THEN PROBLEM_CATEGORY ELSE 'Other' END)
WHEN upper(ENTRY_TYPE) IN ( 'TROUBLE REPORT','NET REPORT' ) THEN
(CASE WHEN SEVERITY IN ( 'Critical','Major' ) THEN SEVERITY ELSE 'Other' END)
ELSE SEVERITY END AS SEVERITY
, ENTRY_TYPE
, EQ_REGION
, EQ_MARKET_CLUSTER
, CASE WHEN FORCE_STATUS = 'Jeopardy' OR FORCE_STATUS IS NULL THEN FORCE_STATUS ELSE 'Other' END AS FORCE_STATUS
, sum( NUM_CREATED ) AS NUM_CREATED
, sum( NUM_OPEN ) AS NUM_OPEN
, sum( NUM_AWAITING_DISPATCH ) AS NUM_AWAITING_DISPATCH
, sum( NUM_OPEN_IN_DUE_DATE ) AS NUM_OPEN_IN_DUE_DATE
, sum( NUM_DISPATCH_TO ) AS NUM_DISPATCH_TO
, sum( DURATION_DISPATCH_TO ) AS DURATION_DISPATCH_TO
, max( SLA_DURATION_DISPATCH_TO ) AS SLA_DURATION_DISPATCH_TO
, max( SLA_DURATION_DISPATCH_TO_G_L ) AS SLA_DURATION_DISPATCH_TO_G_L
, sum( MET_SLA_DISPATCH_TO ) AS MET_SLA_DISPATCH_TO
, sum( C_NUM_DISPATCH_TO ) AS C_NUM_DISPATCH_TO
, sum( C_DURATION_DISPATCH_TO ) AS C_DURATION_DISPATCH_TO
, max( C_SLA_DURATION_DISPATCH_TO ) AS C_SLA_DURATION_DISPATCH_TO
, max( C_SLA_DURATION_DISPATCH_TO_G_L ) AS C_SLA_DURATION_DISPATCH_TO_G_L
, sum( C_MET_SLA_DISPATCH_TO ) AS C_MET_SLA_DISPATCH_TO
, sum( NUM_DISPATCH_FROM ) AS NUM_DISPATCH_FROM
, sum( DURATION_CREATE_TO_DISPATCH_FROM ) AS DURATION_CREATE_TO_DISPATCH_FROM
, sum( NUM_DISPATCH_TO_TO_FROM ) AS NUM_DISPATCH_TO_TO_FROM
, sum( DURATION_DISPATCH_FROM ) AS DURATION_DISPATCH_FROM
, max( SLA_DURATION_DISPATCH_FROM ) AS SLA_DURATION_DISPATCH_FROM
, max( SLA_DURATION_DISPATCH_FROM_G_L ) AS SLA_DURATION_DISPATCH_FROM_G_L
, sum( MET_SLA_DISPATCH_FROM ) AS MET_SLA_DISPATCH_FROM
, sum( C_NUM_DISPATCH_FROM ) AS C_NUM_DISPATCH_FROM
, sum( C_DURATION_CREATE_TO_DISPATCH_FROM ) AS C_DURATION_CREATE_TO_DISPATCH_FROM
, sum( C_NUM_DISPATCH_TO_TO_FROM ) AS C_NUM_DISPATCH_TO_TO_FROM
, sum( C_DURATION_DISPATCH_FROM ) AS C_DURATION_DISPATCH_FROM
, max( C_SLA_DURATION_DISPATCH_FROM ) AS C_SLA_DURATION_DISPATCH_FROM
, max( C_SLA_DURATION_DISPATCH_FROM_G_L ) AS C_SLA_DURATION_DISPATCH_FROM_G_L
, sum( C_MET_SLA_DISPATCH_FROM ) AS C_MET_SLA_DISPATCH_FROM
, sum( NUM_CLOSED ) AS NUM_CLOSED
, sum( DURATION_WIP_TO_RESOLVE ) AS DURATION_WIP_TO_RESOLVE
, max( SLA_WIP_TO_RESOLVE ) AS SLA_WIP_TO_RESOLVE
, max( SLA_WIP_TO_RESOLVE_G_L ) AS SLA_WIP_TO_RESOLVE_G_L
, sum( MET_SLA_WIP_TO_RESOLVE ) AS MET_SLA_WIP_TO_RESOLVE
, sum( DURATION_MTTR ) AS DURATION_MTTR
, max( SLA_MTTR ) AS SLA_MTTR
, max( SLA_MTTR_G_L ) AS SLA_MTTR_G_L
, sum( MET_SLA_MTTR ) AS MET_SLA_MTTR
, sum( NUM_RESOLVE_FD ) AS NUM_RESOLVE_FD
, sum( NUM_DISPATCH_NTF ) AS NUM_DISPATCH_NTF
, sum( AR_NUM_MET_DUE_DATE ) AS AR_NUM_MET_DUE_DATE
FROM CTS.dbo.NDC_Scorecard_Summary_Table t
WHERE DATE_DAY >= cast(convert(varchar(8),getdate()-30,1) as datetime)
AND DATE_DAY < cast(convert(varchar(8),getdate(),1) as datetime)
AND upper(EQ_REGION) IN ( 'NSD', 'NORTHEAST', 'CENTRAL', 'SOUTHEAST', 'WEST' )
AND upper(EQ_MARKET_CLUSTER) IN ( 'NEW ENGLAND','GEORGIA' )
GROUP BY DATE_DAY
, CASE
WHEN upper(ENTRY_TYPE) = 'ACTION REPORT' THEN
(CASE WHEN PROBLEM_CATEGORY IN ('Compliance','Routine') THEN PROBLEM_CATEGORY ELSE 'Other' END)
WHEN upper(ENTRY_TYPE) IN ( 'TROUBLE REPORT','NET REPORT' ) THEN
(CASE WHEN SEVERITY IN ( 'Critical','Major' ) THEN SEVERITY ELSE 'Other' END)
ELSE SEVERITY END-- AS SEVERITY
, ENTRY_TYPE
, EQ_REGION
, EQ_MARKET_CLUSTER
, CASE WHEN FORCE_STATUS = 'Jeopardy' OR FORCE_STATUS IS NULL THEN FORCE_STATUS ELSE 'Other' END-- AS FORCE_STATUS
) t
LEFT JOIN CTS.dbo.NDC_SLAs mdt ON t.SEVERITY=mdt.SLA_SEVERITY
LEFT JOIN CTS.dbo.NDC_SLAs mdf ON t.SEVERITY=mdf.SLA_SEVERITY
LEFT JOIN CTS.dbo.NDC_SLAs wip ON t.SEVERITY=wip.SLA_SEVERITY
LEFT JOIN CTS.dbo.NDC_SLAs mttr ON t.SEVERITY=mttr.SLA_SEVERITY
LEFT JOIN CTS.dbo.NDC_SLAs rfd ON t.SEVERITY=rfd.SLA_SEVERITY
LEFT JOIN CTS.dbo.NDC_SLAs ntf ON t.SEVERITY=ntf.SLA_SEVERITY
LEFT JOIN CTS.dbo.NDC_SLAs ar ON t.SEVERITY=ar.SLA_SEVERITY
WHERE (mdt.SLA_NAME = 'Duration MNOC to NDC % Met SLA' OR mdt.SLA_NAME IS NULL )
AND (mdf.SLA_NAME = 'Duration NDC to Field % Met SLA' OR mdf.SLA_NAME IS NULL )
AND (wip.SLA_NAME = 'Duration Dispatch Out % Met SLA' OR wip.SLA_NAME IS NULL )
AND (mttr.SLA_NAME = 'Total MTTR % Met SLA' OR mttr.SLA_NAME IS NULL )
AND (rfd.SLA_NAME = '% Resolved 1st Dispatch' OR rfd.SLA_NAME IS NULL )
AND (ntf.SLA_NAME = '% Dispatched NTF' OR ntf.SLA_NAME IS NULL )
AND (ar.SLA_NAME = '% Met Due Date' OR ar.SLA_NAME IS NULL )

View 1 Replies View Related

Help Needed In Join Query

Mar 25, 2008

hi,

this is my db tables:

groupallocation
groupid(primarykey)
groupname

systemallocation

systemid(primarykey)
systemname

deviceallocation

deviceid(primarykey)
devicename
sensorallocation

sensorid(primarykey)
sensorname
groupid(foreignkey)
systemid(foreignkey)
deviceid(foreignkey)

so i want to make a query in sensorallocation table should display as like folllows:

i want to make query to join the tables and display the following fields.

sensorid,sensorname,groupname,systemname,devicename

becos in sensorallocation table i do have only groupid,systemid,deviceid only but while displaying i need to display groupname,systemname,devicename

View 3 Replies View Related

Query Help Needed (JOIN)

Jul 20, 2005

I have two tables populated during the use of an application to loguser events and application states. They are named "EventTable" and"StateTable" and the structures follow:EventTable:ID EventTimeStep EventID-- ------------- ---------1 5 E12 22 E23 56 E3StateTableID StateTimeStep StateID-- ------------- -------1 1 S12 39 S2I want to perform a query that reports the StateID of the applicationat the time that each event was logged to the EventTable. The desiredoutput is:ID TimeStep EventID StateID-- -------- ------- -------1 5 E1 S12 22 E2 S13 56 E3 S2I have tried to create a query with an INNER JOIN where the value forthe StateID output field comes from the last row in the StateTableWHERE StateTable.TimeStep <= EventTable.TimeStep and where I use aGROUP_BY EventTable.ID to merge the following rows from the join:3 56 E3 S13 56 E3 S2However, the closest I can get is a query that gives me the wrongstate when applying the GROUP BY clause3 56 E3 S1I also think that the queries I have written is slow and inefficient.Is there a better way to perform this query or is my database designfatally flawed?Thanks,Adam Nemitoff

View 2 Replies View Related

Help Needed With Merge Join

Jan 10, 2008

I am trying to use the merge join example in the following link. To import new records only.

http://www.sqlis.com/311.aspx

The problem is that for some unkown reason the join is not woeking correctly. One of the records is incorrectly showing a NULL on the output. This would indicate that it would be a new record, but it is not it already exists in the new table.

I created a dummy table in SQL and executed the same join and I always get the right answer. What the heck could be wrong?

For example. Table A has 20 records Table B has 3 records. Table B has the new records I want to import into Table A. The package runs corectly the first time, only importing the 3 new records. Then the next time the package runs it shows 1 of the 3 records as being new still, and tries to import the record causing a PK error. Adding a watch to the MERGE output shows that the one record has a NULL on the join.

Please help this is driving me nuts.

View 10 Replies View Related

SQL Query JOIN Needed? Too Advanced For Me

Sep 5, 2006

THIS LOOKS LIKE A LOT BUT I JUST WANTED TO GIVE ALL INFORMATION NEEDED FOR YOU TO EASILY ASSIST ME.  I am not good with SQL so please bare with me. I will give a dumbed down table for us to work with:timestamp          -   DATA1 - DATA2 - MAXVALUENEEDED - DATA32006/8/12 12:00       123         125             1289                      121 2006/8/12 12:05       124         128             1291                      1232006/8/15 12:00        130        128              1190                     1242006/8/15 1:00          131        127             1196                      123  The columns labeled DATA do not really matter.  The only important ones are timestamp and MAXVALUENEEDED but I do need the query to return all columns. What the query has to do: The query needs to find the MAX of MAXVALUENEEDED for a given DAY.  Example Output- 2006/8/12      124   128   1291   1232006/8/15      131   127   1196   123As you can see the MAX values were grabbed for each given day and the unique records were returned on a per day basis. My current SQL Query is:  SELECT CONVERT(varchar, timestamp, 101) AS Time, CONVERT(int,LV50AEPM_AMPS_A_VAL0) AS AMPS_A, CONVERT(int,LV50AEPM_AMPS_B_VAL0) AS AMPS_B, CONVERT(int,LV50AEPM_AMPS_C_VAL0) AS AMPS_C,
CONVERT(int,LV50AEPM_KVA_TOT_VAL0) AS KVA_TOTAL, CONVERT(int,LV50AEPM_KW_TOT_VAL0), CONVERT(int,LV50AEPM_VLL_CA_VAL0), CONVERT(int,LV50AEPM_VLL_BC_VAL0), CONVERT(int,LV50AEPM_VLL_AB_VAL0)
FROM Table_1 T1
WHERE CONVERT(int,T1.LV50AEPM_KVA_TOT_VAL0) = (SELECT MAX(CONVERT(int,T2.LV50AEPM_KVA_TOT_VAL0)) FROM Table_1 T2 WHERE CONVERT(varchar,T1.timestamp,101) = T2.timestamp)
ORDER BY Time ASC The problem is it only returns the max value for one day instead of all days.  Can anyone help me correct this?  Thanks in advance for your help. 

View 34 Replies View Related

Transact-SQL And XML Help Needed.

Jul 4, 2004

Ok here is the situation I need a little help with.

I am passing an XML document to a stored procedure. My XML document looks like this:
<ROOT>
<customer ID="10" Address="1234 Somewhere"></customer>
<customer ID="20" Address=""></customer>
</ROOT>

Now I use sp_xml_preparedocument and OpenXML to Insert the XML ID and Address attributes into a table in my database. The table has 2 fields (ID int) and (Address varchar(100) nullable)

The result of the insertion is 2 rows in my table with the ID field containing (10 and 20) and the Address field containing (1234 Somewhere and an empty string).

My first question is, why isn't the second row Address field in my database null instead of an empty string since thats what I would like happen. Is it because the XML Address atribute = "".

If that is the case then that should bring up my second question. Since the OpenXML inserts Address="" as an empty string instead of NULL, why doesn't a regular TransactSQL INSERT statement called from ASP does the same thing?? If I lost you here then let me give a quick example.
An html web form with a text field (txtAddress). The user leaves the text box empty and submits the form. My ASP takes the value of the form, Request.Form("txtAddress") and passes it to stored proceudre through an ASP parameter object. My stored procedure simply does an INSERT into tablename (ID, Address) VALUES (@passedID, @PassedAddress). Now the outcome in the database is that the Address field is NULL and not an empty string.

That is why im confused. Why arent the OpenXML and the straight-forward insertion yield the same result (either null or empty string). It seems to me that an empty text box is an empty string and not null. ASP's ISNull(txtAddress) agrees and returns false.

Any insight ot help on this issue is greatly appreciated.

View 1 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

Problem With SQL Server Left Outer Join: Help Needed

Nov 1, 2004

I am getting different results with LEFT outer join operator and *= operator. With *= I am getting the expected results. Can anyone look at SQL and tell what I am doing wrong?

SQL with Left Outer join operator:

select CurrentWeekFinMetrics.[Hub+],
WeeklyMetricsFormat.line#,
WeeklyMetricsFormat.MetricsType,
WeeklyMetricsFormat.Metrics,
WeeklyMetricsFormat.Measure, WeeklyMetricsFormat.jobs, case when dataformatchar is not null then
case when IsPrefix = 'Y' then dataformatchar + convert (varchar, CurrentWeekFinMetrics.displayCol )
else convert (varchar, CurrentWeekFinMetrics.displayCol ) + dataformatchar end
else
convert (varchar, CurrentWeekFinMetrics.displayCol )
end
from WeeklyMetricsFormat LEFT JOIN CurrentWeekFinMetrics on (WeeklyMetricsFormat.Line# = CurrentWeekFinMetrics.Line#)
where CurrentWeekFinMetrics.WeekEndingDate = '10/09/04' and CurrentWeekFinMetrics.[Hub+] = 'Amstelveen'
order by CurrentWeekFinMetrics.[Hub+], WeeklyMetricsFormat.Line#


SQL with *= operator
select CurrentWeekFinMetrics.[Hub+],
WeeklyMetricsFormat.line#,
WeeklyMetricsFormat.MetricsType,
WeeklyMetricsFormat.Metrics,
WeeklyMetricsFormat.Measure, WeeklyMetricsFormat.jobs, case when dataformatchar is not null then
case when IsPrefix = 'Y' then dataformatchar + convert (varchar, CurrentWeekFinMetrics.displayCol )
else convert (varchar, CurrentWeekFinMetrics.displayCol ) + dataformatchar end
else
convert (varchar, CurrentWeekFinMetrics.displayCol )
end
from WeeklyMetricsFormat , CurrentWeekFinMetrics
where CurrentWeekFinMetrics.WeekEndingDate = '10/09/04' and CurrentWeekFinMetrics.[Hub+] = 'Amstelveen'
AND (WeeklyMetricsFormat.Line# *= CurrentWeekFinMetrics.Line#)

For Left outer join operator, I am getting 54 rows, *= I am getting 69 rows.

Thanks and Regards
mb

View 2 Replies View Related

Access Restriction

May 5, 2004

I want to access mssql2000 server only by 'sa' & database login ids. I want to restrict windows administrator account to access the database. Please help !!!

Our enviorment :- SQL2000 with SP3 on Windows2000 advanced server with latest service pack..

View 2 Replies View Related

Column Restriction

Sep 26, 2007

In SQL 2005 is there a way where you can restrict certain columns on a table from being view from a user(s) or group, without creating a view?

View 2 Replies View Related

Removing Foreign Key Restriction

Apr 13, 2008

Hi everyone,
My first table has a column named "customer" that is directed to "customers" table "id" column as foreign key.
I wanted to change "id" name so i wanted to delete it and create another column of another name but i cannot delete that column because it is attached as fk to another table.
How can i remove th fk constraint ?
Thanks.

View 3 Replies View Related

Adding A Restriction To An Insert

Feb 16, 2006

I'm inserting rows from one table to another and trying to figure out how to not allow nulls from one field. ie - the feeder table can have nulls, but when I insert into the other table, I don't want the records that have NULLS in one field to insert. I hope that's clear.

View 3 Replies View Related

Constraint/Restriction Question

Feb 7, 2008

Hello all,

First of all I would like to show my satisfaction at this great forum.

I'm quite a beginner at SQL and would like to ask a question.

Let's say I have a table of Students and a table of Subjects with their respective details. Now I want to create another table that references both the previous tables so that I would know what subjects the Student is attending. My problem is how to put a restriction in the new table on the number of subjects that each student can have (e.g. each student can only apply for 8 subjects, not more).

I've heard about triggers and other possible solutions, but it's too advanced for me at the moment, so I'd like to possible find a solution through the new table.

Roughly, I guess the new table (let's call it StudentAttends) will have the student id from the Students table and the subject id from the Subjects table. Now how should I add the above restriction?

Thanks for your help!

View 1 Replies View Related

Multi Processor OS Restriction?

Jul 23, 2005

Hi, Ive been told this, but I hope it is NOT true. I have an sqlserver2000 installation running on a server that has four processors.It is on a active network but is not the domain controller soessentially it is fully dedicated to servicing the needs of sqlserver, (a bit of browsing, a bit of ms Office, but almost whollydedicated to sqlserver. Now, the big question, why, when the serverproperties have been set to utilize all four processors, can any onejob never get more than 25% of cpu time? I can launch multipleinstance of QA and run the same job on each one and that will utilisemore and more cpu time, but if you launch multile QA windows fromwithin one insance of QA, you can NEVER get more than 25% CPUutilisation. Now i have to run a job (FTS is a good example,re-indexing lots of db's another, or even a huge query with multipleufd's on computed cols which I hoped would grab lots of CPU time thatthey need, but no. So do I have to live with this or can I tell eitherwindows or sql server to grab more cpu when it want to ie use my spareCPU capacity more efficiently or am i working on a misguided premiseand 25% per job is your lot?DMAC

View 4 Replies View Related

Horizontal Data Restriction

Jul 20, 2005

I have 2 installations:1. W2k with MS SQL 2000 sp2.2. W2003 with MS SQL sp3.There are two databases in all instalations: "maindb" and "userdb". Thetable with data is in maindb.In the 1'st installation I restict user access to all data in table in thisway:- create user's login and user in databases maindb and userdb.- create view in userdb with "where" clause as dbo (dbo is owner of thisview). This clause restict access to data. (create view userdb.dbo.table asselect * from maindb.dbo.table where ...)- add user to group "Public" in maindb.- add role "data reader" to user in userdb.- effect: user can access data only by view, can not access any data inmaindb.I do the same in secound installation:- effect: user can not access data by view - message like this: "userhave not permission to select on maindb.dbo.table"Is this bug in sp3 or in sp2 ?Is there another way to horizontal restrict access data in tables?In Sybase ASE this method (restict by view) works ok. And there is newproperty of ASE 12.5.1 - administrator can define context of login - the"where" clause will be added automatically to any select.Please help me. Thank You for any advice.

View 2 Replies View Related

Transact SQL :: Getting Min And Max Records From Join

Oct 1, 2015

I have 2 tables:

create table #InsuredLoc (
PolGK int,
InsuredLocGK varchar(20),
InsuredLocEffDt datetime,
InsuredLocType varchar(20),
InsuredLocStatus varchar(20),
InsuredLocAddress varchar(50),
PolEdrGk varchar(20),

[Code] ...

I will need to join the #InsuredLoc table to the #PolicyEndorsement table using PolGk and PolEdrGk and get the min(BkgDt) and min(PolEdrRowUpdateDt) for the distinct list of InsuredLocType, InsuredLocStatus, and InsuredLocAddress fields from the #InsuredLoc table above.

 I will also need the min(InsuredLocEffDt) and the max(InsuredLocUpdateDt) from the #InsuredLoc table for those records. So after the first run, i should get the following:

I tried to use CTE's with ranking, but some records are dropping off and I'm not sure why.  

View 6 Replies View Related

What Kind Of Constraint-restriction I Need To Apply, And How To

May 22, 2008

Hello

I have the following table, and i need to know, what kind of Constraint-restriction and how to apply using management studio for the next case

Table ITEMSProperties
===============================================================================
ItemID (PK-FK) ValueType (PK-FK) PropertyValue (NVARCHAR)
-----------------------------------------------------------------
1 1 (1=Color) Red
1 2 (2=Date) 01/01/2001
2 1 Blue
2 2 021/badStr/08badstr



Well, so ..
If I don€™t want bad Dates-Strings stored in this table, for the ValueType = 2, .. What kind of constraint-restriction or maybe a trigger, I need to use and please tell me how to aplly using management studio ?

View 3 Replies View Related

Transact SQL :: JOIN On Calculated Fields

Sep 21, 2015

I am trying to JOIN table on datetime column truncated to full minutes with other table, where I store time intervals (in order to have all minutes in result even when there was no event in main data table).

SELECT
dateadd(minute, datediff(minute, 0, StartTime), 0) as StartTimeMinute
,ApplicationName
,COUNT(*) as Requests
FROM dbo.Profiler as p INNER JOIN dbo.MinuteIntervals as i ON i.TIMEVALUE = p.StartTimeMinute
WHERE EventClass IN (10,12)
GROUP BY dateadd(minute, datediff(minute, 0, StartTime), 0), ApplicationName
ORDER BY StartTimeMinute

How to join on p.StartTimeMinute? I do understand why this doesn't work, as p.StartTimeMinute is calculated in my query, so JOIN cannot find it in original p table.

View 5 Replies View Related

Transact SQL :: Left Join With Subquery

Aug 24, 2015

SELECT A.EmpId,A.IncidentDate
FROM EmployeePoints1 as A
WHERE IncidentDate=
(SELECT MAX(IncidentDate)
FROM EmployeePoints1
WHERE EmpId = A.EmpId) AND (DATEADD(day,28,DATEADD(WEEK, DATEDIFF(WEEK, 0,A.IncidentDate), 0)) < DATEADD(WEEK, DATEDIFF(WEEK, 0,GetDate()), 0)) AND (A.IncidentCode = 'I' OR A.IncidentCode = 'A')
LEFT JOIN EmployeeTotalPoints1 ON EmployeeTotalPoints1.EmpId = A.EmpId

I am trying to left join another table but  I got

Incorrect syntax near the keyword 'LEFT'.

View 9 Replies View Related

Transact SQL :: Avoid Duplicates From Join

Jun 8, 2015

I am doing some audit and i  have below query, how can i get rid of duplicates from the below query any T SQL to get rid of duplicates...

I am using SP_Who2 and sql server  Audit for auditing all data happening on sql server databases  and dumping them to tables  Audit_DBAudit  abd Audit_sp_who2  and from then i am trying to get data which is not repeating/duplicate ...
 
SELECT
A.ProgramName
,a.HostName,[Server_principal_name],[Server_instance_name],[Database_name],[Object_name],F.Statement
FROM Audit_DBAudit as F 
 Join [Audit_sp_who2] AS a
on LTRIM(RTRIM(F.server_principal_name))=LTRIM(RTRIM(A.Login))

View 11 Replies View Related

Transact SQL :: How To Join 2 Tables Have Different Foreign Key

Apr 23, 2015

i have two tables Table one have 2 columns id and value
     
id value

1 Dell

2 Hp

B2 Hp-mini
B3 Hp-lapTop

3 Acer

the second table have 3 clomuns id,name,idTable

1 TeaBou B
2 Mark B
3 Jack 1
4 Piere 2
5 Jean 2
6 Mark 3

i tried this query

select*from table1 t1 ,table2 t2
where t1.id=t2.idTable

i had some data but also i need to include the person who have the B product.

View 6 Replies View Related

Transact SQL :: Using Join With Part Of A Table

Jul 14, 2015

I have a table like this :

reg.no |   description |  start_date |  end_date |   load_date

I want to join this table with itself on reg. no. But not all the rows in table must be joined.

But for example, rows with load_date 01-07-2015 to be joined with rows with load_date 02-07-2015. And the rest of the rows should not used in join (for example, rows having other load_dates)

Is this possible ? and how?

View 4 Replies View Related

Transact SQL :: Get Min Date Row From Join Table

Sep 10, 2015

I have the following 2 tables:

Location:

Policy:

1 Location can be attached to many policies.

I need to create a query to get 1 row per location and get the minimum PolicyBookingDt and RowUpdateDt from the policy table.  All the attributes from the Location table should also be from the Policy that has the minimum PolicyBookingDt.

 So from the above example, i need to get the following:

Getting a little confused on how to create the syntax for this.

View 4 Replies View Related

Removing Data Base Size Restriction

Jul 10, 2007

About a month ago I restored a data base that had been originally created in MSDE into a full version of SQL Server 2000. I thought that the size restriction would automatically be removed by putting it into the full version of SQL. I was wrong and about a week or so later the data base reached the 2GB size and needed attention. I received some assistance through Microsoft and they walked my client through the process of removing the size restriction. Since then everything has been OK.



Now I am doing something similar. My client has a data base that was originally created in MSDE. We upgraded them to SQL Express and the data base has now grown to 4GB which is the max that SQL Express allows.



We will be installing SQL for Workgroups this week.



My question is this. Is there a setting I must change inside the data base or in SQL for Workgroups that will allow the data base to grow beyond 4GB? We need to let it expand to whatever they need and I cant seem to find any documentation on whether or not I have to change a setting for this data base.



Thanks for your help. Jean

View 3 Replies View Related







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