Transact SQL :: Get Only Those Distinct Records Which Satisfied Condition

Jun 3, 2015

I need to write a query on a table..

table defination .. table Client_Master
file_id int identity(1,1) primary key 
, client_id int
,LOAN_SANCTION_DATE datetime
,is_reject bit

has Data ..

FILE_ID CLIENT_ID
LOAN_SANCTION_DATE IS_REJECT
21139 22784
2014-02-03 00:00:00.000 0
21141 22784
2014-02-03 00:00:00.000 NULL
20869 22784
2014-02-03 00:00:00.000 1
20870 22784
2014-02-03 00:00:00.000 0
21571 22784
2014-02-03 00:00:00.000 1
66056 22784
2014-02-03 00:00:00.000 1

Above has 6 files entries for client id 22784 and LOAN_SANCTION_DATE 2014-02-03  out of which 3 are rejected ..

Now , i want to write a query to select those distinct client_id , LOAN_SANCTION_DATE  from Client_Master where all files has been rejected ..

means by grouping client ID and LOAN_SANCTION_DATE all the files are rejected ..

I have wrote as below .. got the result but not satisfy with the query

SELECT DISTINCT CLIENT_ID,LOAN_SANCTION_DATE,COUNT(FILE_ID) AS No_Of_Files
,COUNT(DISTINCT CASE WHEN IS_REJECT=1 THEN FILE_ID END )AS No_Of_Rejected
FROM  dbo.FILE_MASTER 
GROUP BY CLIENT_ID ,LOAN_SANCTION_DATE
HAVING
COUNT(FILE_ID)=COUNT(DISTINCT CASE WHEN IS_REJECT=1 THEN FILE_ID END )

View 4 Replies


ADVERTISEMENT

Transact SQL :: Exclude A Distinct Records From Select When One Condition Is True?

May 28, 2015

I have customers named Alex (Cid=1), Bob (Cid=2), and Carrie (Cid=3) in a table customer.

Cid
First_Name
1
Alex
2
Bob
3
Carrie

I have products name Gin (Pid=1), Scotch (Pid=2) and Vodka (Pid=3) in a table products.

Pid
Product_Name
1
Gin
2
Scotch
3
Vodka

And I have a table that holds purchase called Customer_Purchases that contain the following records:

Cid
Pid
1
1
1
2
2
1
2
3
3
2

I would like to make a marketing list for all customers that purchased Gin or Scotch but exclude customers that purchased Vodka. The result I am looking for would return only 2 records: Cid’s 1 (Alex) and 3 (Carrie) but not 2 (because Bob bought Vodka).

I know how to make a SELECT DISTINCT statement but as soon as I include Pid=2 This clearly doesn’t work :

SELECT DISTINCT Pid, Cid
FROM           
Customer_Purchases
WHERE        (Cid = 1) OR
(Cid = 3) OR
(Cid <> 2)

View 3 Replies View Related

Transact SQL :: Get Records Based On Condition In Server

Nov 22, 2015

I have a question about SQL Server.

Table patient:

create table patient (pn int,code int,date date,doctorcode int)
insert into patient (pn,code,date,doctorcode)
values
(1,10,'2015-02-19','100),
(1,10,'2015-02-19','101),
(1,10,'2015-02-19','102),

[Code] ...

Table Patientref:

create table patientref
(pn int,code int, sdate date,edate date,status int)
insert into patientref(pn,code,sdate,edate,status)
values
(1,10,'2015-02-13','2015-02-19',1),
(1,10,'2015-02-19','2015-03-24',2),

[Code] ...

Here we need consider patient dates that fall between sdate and edate of the patientrefs table, and then we need to consider the highest status values in order (for example, the highest values in order - 2 is first highest, 4 is second highest, 3 is third highest, and 1 is fourth highest value)

If the date falls between multiple different sdate and edate with the same status values, then we need to consider the latest sdate value and from that entire record we need to extract that value.

Examples: patient

pn |  code  |  date      |   doctorcode
2  |  10    |2015-02-12  |   101
2  |  10    |2015-02-13  |   102
2  |  10    |2015-02-14  |   103

Table : Patientref:

pn |  code  |  sdate      |   edate      | Status
2  |  10    |2015-02-08   |   2015-02-19 |  4
2  |  10    |2015-02-09   |   2015-02-19 |  2
2  |  10    |2015-02-10   |   2015-02-19 |  2
2  |  10    |2015-02-11   |   2015-02-18 |  1

Here, pn=2 values have dates which fall between sdate and edate of patientref table. Then we give highest values status is 2, and status 2 values have two records, then we go for max sdate(latest sdate). Then this pn=2 latest sdates is 2015-02-10 and we need to retrieve the corresponding edate and status values.

pn = 4donot have sdate and edate and status values dut not fall conditon 

Based on this, the desired output is below:

pn |  code  |  date      |   doctorcode | sdate     |edate      |status
1  |  10    |2015-02-19  |   100        |2015-02-19 |2015-03-24 | 2
1  |  10    |2015-02-19  |   101        |2015-02-19 |2015-03-24 | 2
1  |  10    |2015-02-19  |   102        |2015-02-19 |2015-03-24 | 2
2  |  10    |2015-02-12  |   101        |2015-02-10 |2015-02-19 | 2

[Code] ...

I tried it like this:

select p.pn,p.code,p.[date],p.doctorcode,pr.sdate,pr.edate,pr.[status] from patient p
 outer apply (select top 1 pr.pn,pr.code,pr.sdate,pr.edate,pr.[status] from patientref pr 
where pr.pn=p.pn and pr.code=p.code and p.date between pr.sdate and pr.edate
 order by case when pr.status=2 
then 1 when pr.status=4 then 2
 when pr.status=3 then 3 
when pr.status=1 then 4 end ,pr.sdate 
 )pr

but this query not given expected result.here when dos not fall between sdate and edate  that records not given in the above query. I required that records also.if not fall b/w condition then we need retrive that records empty values for that records.

View 7 Replies View Related

Transact SQL :: Optimize Count Distinct For Multiple Groups Of Records?

May 21, 2015

I have a CTE returning a recordset which contains a column SRC.  SRC is a number which I use later to get counts and sums for the records in a distinct list. 

declare@startdate date = '2014-04-01'
declare@enddate date = '2014-05-01'
; with SM as
(
SELECT --ROW_NUMBER() OVER (PARTITION BY u.SRC ORDER BY u.SRC) As Row,
u.SRC,

[Code] ....

-- If Referral start date is between our requested dates

ref.Referral_Start_Date between @startdate and @enddate

OR

-- Include referrals which started before our requested date, but are still active during our date range.

(ref.Referral_Start_Date < @startdate and (ref.Referral_End_Date > @startdate OR ref.Referral_End_Date IS NULL ))
)
INNER JOIN c_sdt s on s.Service_Delivery_Type_Id = u.Service_Delivery_Type_Id
AND s.Service_Delivery_Unit_Id = 200
)
SELECT
count(distinct (case SRC when 91 then client_number else 0 end)) As Eligable_91,

[code]....

View 5 Replies View Related

Transact SQL :: How To Add Condition In Where Clause According To Another Condition

Oct 17, 2015

I write a query to get some data as the following. but i need when a user check specified condition a query parameter change to specified condition :

create proc proc_ReservationDetails
(
@status nvarchar(50) = null
)
as
begin
select reservationId, reservationStatus, reservationDesc

[Code] .....

View 3 Replies View Related

Multiple Records With Condition

Aug 29, 2006

I know how to query up duplicate records, here is what I am using to do so:

Select PhoneNum, Count(PhoneNum) as NumOccurances
From Tester
Group By PhoneNum
Having (Count(PhoneNum) > 1)


when the duplicates arise, I expect them to have unique CallResultCode values, and I would like to make a priority of which value stays and which one gets dumped, keep in mind that I am a SQL noob.


Registered Linux User #365191

View 1 Replies View Related

Condition Before Insert Records ?

Feb 7, 2008



Hi guys,

Help me to write my query,

I want to write a insert statement but before insert statement run i need to check a condition like if the same record is already existing or not ? how do i do this using transact -SQL

I mean i have a table call Employee like this definition

ColumnName Datatype
EmployeeID INT
Name Varchar(255)


Records like this

EmployeeID Name
1 John E Mathew
2 Ethel Elizabeth


Ok Before i insert a new record , i need to check if a emplyee name call ="John E Mathew" already in the table or not if Employee Name call ='John E Mathew' not exisits only it should execute my insert statement .

how do i write my SQL ?

regards
suis





View 9 Replies View Related

Transact SQL :: How To Delete Row With Condition

Aug 6, 2015

create table target
(Taid int, studenid int, std int,div int,year int ,ActivityId int)
insert into target values(1,1,1,2015,1),
(1,1,1,2015,2),(1,1,1,2015,3),(1,1,2,2015,1)
,(1,1,2,2015,4) ,(1,1,2,2015,3);

create table activity(ActivityId int,Activity nvarchar)
insert into activity values (1,'sport')
,(2,'swim')
,(3,'read')
,(4,'dace');

I want to edit(update,delete,insert) target table activity from front end for that I took grid view and that grid all activity come of single student studenid(unique key for each student) that you see design below like this 

that activity present in target table that come as check in check and that activity not select student from activity activity table that come unchecked

I want to update above information means  unchecked alredy check data should delete and new check data add , already check data update

I have use merge statement but problem is that at single time only one row execute that is check because  data come from data gridview.

View 5 Replies View Related

Transact SQL :: Using Isnull In Where Condition

Jul 10, 2015

I am in assumption that we cannot do NULL value comparison in where clause directly (results will not be proper) we have to use ISNULL. Is my understanding correct? Is using ISNULL efficient when we have to this operation for large volume?

View 5 Replies View Related

Transact SQL :: How To Apply Condition

Jul 24, 2015

I have an order with the time 08/03/2015 7:30 08/03/2015 10:30 ..I have availability with the time 08/03/2015 07:00:00 to 08/03/2015 19:30:00...Here the availability falls for 3 hours only..My requirement is that For order if availability< 4hours i don't want to show employee.How to apply the condition.

View 7 Replies View Related

Update All The Records Of A Table On A Condition

Sep 20, 2007

Hi
I have a two tables as follows

Table Category
{

ID PK,
LastUpdate DateTime
}

Table Master
{

ID PK
Catrgory DateTime
}

I wanted to update Catrgory coulmn of all records in the Master table with the Value of LastUpdate of the CategoryTable the where the ID of the both the table are same

Can any one please let me know the query

~Mohan

View 8 Replies View Related

Transact SQL :: Select Column On Condition

Jul 4, 2015

I have a table called names  (firstname, lastname, number) then i have a DECLARED variable called  @displaynum...If @displaynum id true   my select query should select the number column.  if the variable is false , only the first two columns are selected.

e.g   @displaynum = true                                          
@displaynum = false
Firstname  | Lastname | number                               Firstname  | Lastnam

blah           |   blah        |   12345                             
blah           |  blah

i am not sure if this is possible as a case still selects the column but just changes the values.

View 12 Replies View Related

Transact SQL :: Updating Only One Row Based On Where Condition

Sep 16, 2008

How can I update only one row doing an update query?
 
For example:
 
update from table1
set category = 'C'
where country = 'Brazil'
 
One want to update only one row with country = 'brazil'

View 5 Replies View Related

Selecting A Desired Sequence Of Records Without Where Condition

Apr 12, 2001

Dear Friend,

How to select a desired sequence of records without where condition?

For example I want to select the first 100 records I am using

SELECT TOP 100 * FROM EMPLYEETB;

Like this I want to select the records starts from 101 to 200.

Is it possible? If yes how?

Thanks in advance.

Lovingly,
Meyyarasu

View 1 Replies View Related

How To Filter Out Records With A Condition In The Data Flow?

Apr 3, 2008



Hi, all experts here,

I am desperate to need you help.

Could you please give me any advices on how to filter out the records through out the data flow by any particular condition? E.g. In my case, I want to filter out rows with null id (will get rid of those rows with null id which are not matched in the look up component)? Hope it is clear for your help and I am looking forward to hearing from you for your help and thank you very much.

With kindest regards,
Yours sincerely,

View 5 Replies View Related

Transact SQL :: Where Condition - If No Input Value Select All Rows

Apr 27, 2015

I  have table with filed

EmpProject -Table
Empno, Name, Project NO, cost center

I need to restrict the results by project No by user input. In case if user did not provide any value for the projectNO, then need to fetch all rows.

Select empno, name, projecno, cost_center from empproject where projectno=nvl(:pno, :deptno)

View 6 Replies View Related

Transact SQL :: Include A Condition In Store Proc

Sep 29, 2015

I have an existing store proc with insert and update statements, I want to add a condition at the top of the proc with conditions like;

declare @dayofweek int
set datefirst 1
select @dayofweek = datepart(dw,getdate())
--select @dayofweek
if @dayofweek = 1

[Code] ...

If the condition meets with either of the above 2 conditions, than have to run the actual store proc.

My actual Storeproc in which I need to incorp the above conditions is:

CREATE PROCEDURE [dbo].[Load_Product]
@FileDate date = NULL
AS
BEGIN
DECLARE @EventText varchar(500),
@Rows int = 0,
@RowsTotal int = 0,

[Code] .....

View 12 Replies View Related

Transact SQL :: Condition Failed Rows Count

Jul 3, 2015

I am using SQL Server 2008.Each stock item will have default 4 document type (1, 5, 6, 7) and each will have 3 zone's (1, 2, 3) to qualify. Each zone will be updated to 1 for that document type if the item successfully pass through it. If all zone are NULL means no transaction. How to retrieve only the failed rows which means not all zone are 1 or NULL.In the image GJ-00064 has one row failed. So how to get the count of failed rows for each item

Expected result:

Uniid <-> Stockcode <-> FailedRows
1670 <-> GJ-00064 <-> 1

View 8 Replies View Related

Transact SQL :: How To GROUP BY And Get Aggregate Where A Certain Condition Is True

Jul 16, 2015

I am using SQL 2005.  I have some data from an old application that did not follow the rules for normalization.  The table is for Invoices, and the table allows for 13 purchase items per record.  So in each row of my table I have a non-unique integer field itemID, itemID1, itemID2 ... itemID12.  For each itemID I also have "lbs_total" and "line_total" (which is price * lbs_total) - so itemID, lbs_total, line_total ... itemID1, lbs_total1, line_total1 ... etc.  It's a mess, I know.Each row has a unique Customer Number ("cno") and an Invoice Date ("inv_date").  My proc needs to allow for params for the item number, and a start date and end date for BETWEEN on the inv_date.I also need to get the aggregate for the lbs_total and the line_total.

View 15 Replies View Related

Transact SQL :: How To Use Case Statement In Select Condition

Nov 6, 2015

below is my original query

select Value = count(*) from dbo.test 

I have 20 rows in dbo.test so i will get 20 as my output, now i need to write a case statement here such that when count(*) = 0 then it should display text filed 'NO Data' else it should display the count.

View 5 Replies View Related

Transact SQL :: Passing Value In Where Condition Loop Wise

Jun 1, 2015

I want to calculate year to month data for month wise . Ihave start range and end range table like below

Start range and end range table

Start dateEnd date
01-04-201401-11-2014
01-04-201401-12-2014
01-04-201401-01-2015
01-04-201401-02-2015

[Code] ....

Then I want to pass this value one by one in below table for get value month wise

Main table

Branchamountperiod
Branch110201103
Branch22201104
Branch33201401
Branch44201402
Branch58201403
Branch610201404

[Code] ....

The below query is for november month: (Apr to Nov)

select * from maintable
where period between '01-04-2014' and '01-11-2014'
then for December month : (Apr to Dec)

So I want to pass second row

select * from maintable
where period between '01-04-2014' and '01-12-2014'
.....
....
select * from maintable
where period between '01-04-2015' and '01-12-2015'

Like wise I want to get month wise data of YTM data.

My expected output is

201411
201412
201501
201502
201503
201504
201505

[Code] ....

View 10 Replies View Related

Transact SQL :: Selecting First Row After Date Matching Condition?

Sep 22, 2015

I've two audit tables, AUDIT_ORDERS and AUDIT_ORDER_LINES.

The AUDIT_ORDERS has these columns: AUDIT_ID, ORDER_ID, AUDIT_DATE and other ones.

The AUDIT_ORDER_LINES has these columns: AUDIT_ID, ORDER_ID, ORDER_LINE_ID, AUDIT_DATE and other ones.

I need to join these two tables in order to select for each order line row the first order having the related audit date lower than or equal to the audit date of the related order line.

I don't want to use the TOP 1 clause or a subquery. I think to complete a such statement:

SELECT OL.Order_Line_ID, O.Order_ID, OL.Audit_Date, O.Audit_Date
FROM AUDIT_ORDER_LINES as OL INNER JOIN AUDIT_ORDERS as O
on OL.Order_ID = O.Order_ID and O.Audit_Date <= OL.Audit_Date ...

I'd like to get the first row of the Audit_Orders with audit_date <= of the audit_date of the Audit_Order_Lines table by using the join clause.

View 9 Replies View Related

Transact SQL :: How To Use Multiple Values In Where Condition In Query

Jun 17, 2015

I have a query where i would calculate the counts of three Servers 

declare @Managed float
declare @Active float
DECLARE @Values varchar(1000)
SET @Values = 'WE,EE,CO'
select @Managed = count(Name0) from v_R_System where Operating_System_Name_and0 like '%Workstation%' 

[Code] ...

Here i need output like below

Workgroup Managed Active
'WE' 255 ,400
'EE' 300 ,450
'CO' 155, 600

So how to use these three values in the where condition when i use the where clause i have put in condition it will give me the subquery returns more than one value,so how should i use this scenario to accomplish this output?

View 3 Replies View Related

Transact SQL :: While Loop Does Not End When Condition Is No Longer True

Dec 1, 2015

I have a Stored Procedure, wherein I need to use a while loop. essentially the loop looks like this.

Set @Kount = 1
--TestScript
Select 'TempReqTable', * from @TempReq
WHILE Exists(Select * from @TempReq WHERE TempID = @Kount)
BEGIN
--Do stuff with values from table
Set @Kount += 1
END

The test script confirms that there is only one row in the @TempReq table.  However the loop never stops running and @Kount keeps being incremented and incremented until I manually stop the execution of the SP.

Is there some rule that I am not aware of that does not allow the use of an Exists statement in the condition of a While loop?

View 12 Replies View Related

BCP Aborts When Constraints Are Not Satisfied

Mar 10, 1999

Hi all ,
I have a problem using BCP. The execution of BCP proccess stops whenever an error of constraint voilation occurs. What i want is that the BCP should log the errors and continue the execution.

The manuals states that the errors are logged into the file specified during bcp and proccess continues. Whereas the same thing is not happening here.

I am using SQL Server version 6.5

Please help me out with a solution as soon as possible.

Thanks
Shrenik Nanavati

View 1 Replies View Related

Trying To Get Distinct Records

Jan 7, 2008

How do I get distinct TitleID and Titles?  Right now I'm still getting duplicates on them both.  Here's my stored procedure.
select Distinct (Titles.Titleid), Titles.Title as TITLE, classifications.[description]as TOPIC,Titles.descriptions,media.[description] as MEDIA
from  Titlesjoin resources on resources.Titleid = Titles.Titleidjoin media on media.mediaid = resources.mediaidjoin titleclassification on titleclassification.titleid = titles.titleidjoin classifications on classifications.classificationid = titleclassification.classificationid  WHERE Title LIKE 'p' + '%' GROUP BY Titles.titleid, titles.title,classifications.[description],Titles.[descriptions],media.[description] 
Thanks! 
 
 
 

View 18 Replies View Related

Distinct Records

May 11, 2008

hi,
i want to ask a simple question,
i have a sql server relational tables named "tbl_Contact" (w/c has a field of ID & ContactName) and "tbl_reviews" (w/c has ID,ContactCode & Reviews).
the tables relationship is one-to-many, now my question is, how can i display a single record per 'ContactCode' from 'tbl_review'??
thanks..
 
 

View 7 Replies View Related

Only Get The Non Distinct Records

Oct 1, 2007

I am trying to write a query that will only return the non distinct records

what i have is a bunch of line items that have an order id and a rate

there may be 10 line items with the same orderid, I need to get the orderid and rates for the orderids that have more than one rate

how would i do this?

View 15 Replies View Related

Getting Distinct Records

Oct 16, 2007

how do i get an entire record returned when looking for only column to be unique?

basically i have 3 columns

id, tranid, appliedtranid

tranid can have multiple appliedtranids

i need to grab the top 10 distinct tranids but i need the entire record

View 4 Replies View Related

Get Top Distinct Records

Jan 31, 2008

hi I am trying to write a query that will return the most recent status of an event

my query is below

SELECT DISTINCT eventname, MIN(Status) AS Expr1, MIN(RecordUpdated) AS Expr2
FROM EventQueue
GROUP BY AuditName

does this query always result with the most recent distinct eventname record?

I need to make sure that the recordupdated is the most recent for the eventname

View 2 Replies View Related

Transact SQL :: Insert Missing Record Based On A Condition

Sep 29, 2015

How do I get the below scenario:

EmpID DepID
12 2
17 3
17 2
13 3

Every Employee should be in Department 2 and 3 (as example EmpID = 17 has DepID 2 and 3 from above table). But when any of the employees either exists only in any one department (as EmpID = 12 has only DepID = 2), then a new row should be added to the table for that employee with that missing DepID.

Desired Output:

EmpID DepID
12 2
17 3
17 2
13 3
12 3
13 2

View 5 Replies View Related

Get Ditinct Data If All 3 Criteria Is Satisfied?

Feb 11, 2008

Hi

I have table with 25 colums. 3 of the colums(Chkflag,BMCHECK,UPDATED) have yes/no data type.
What I am trying to do :
If chkflag is No value (i.e 0) and BMCHECK or UPDATED has no value then bring one of the field from BMCHECK.

quote:SELECT DISTINCT BMCHECK FROM FEEDER WHERE Chkflag = 0 AND BMCHECK = 0 OR UPDATED = 0

I am using the above query in vb.net to look for any of above field is blank or not ticked if the query brings any data THEN
---run the other queries
else (There is no data)
---do this---

Advance thanks

View 5 Replies View Related

Selecting Distinct Records

Sep 1, 2007

Hi,
 I'm just wondering if someone can help me with some SQL syntax stuff.I want to take this sql statement: 
"SELECT TOP 50 tblProfile.chName, tblProfile.intCount FROM tblProfile, tblLinks WHERE (tblLinks.MemberID = tblProfile.MemberID) ORDER BY tblLinks.dtDateAdded DESC;"
 and select only unique "chName's" records 

View 9 Replies View Related







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