Transact SQL :: Creating A View Using DISTINCT And Not Getting Unique Results?

Sep 21, 2015

I am building a view to be used to drill down into a Lightswitch app I'm building and to drive this I want to use a view based off the selection of that value several other values will be given to the user to choose from related to the first selection. I've created a view using the following statement:

SELECT DISTINCT TOP (100) PERCENT ARSFamily, ARS_Index
FROM dbo.csr_standards_cmsars
ORDER BY ARSFamily

 but the results come back with ALL the records of the source table (509 rows) when there should have only been 29 rows returned (the appropriate number of families or unique groups).  The index is necessary to have Lightswitch use the view as a data source.what I'm doing wrong here?

View 2 Replies


ADVERTISEMENT

Problem Creating View With DISTINCT Column

Oct 5, 2005

Hi Guys

I'm trying to create a view in SQL Server to display only one copy of all records in a table, where some of the records are exact matches to other records (except for an ID autoincrement field)

I have the following code that displays distinct titles:

sql Code:






Original
- sql Code




SELECT DISTINCT DocTitle
FROM dbo.TBL_TABLE_NAME






SELECT DISTINCT DocTitleFROM         dbo.TBL_TABLE_NAME



But when i use this code (adding one field to query), it displays all the duplicate records also, which I do not want:

sql Code:






Original
- sql Code




SELECT DISTINCT DocTitle, ID
FROM dbo.TBL_TABLE_NAME






SELECT DISTINCT DocTitle, IDFROM         dbo.TBL_TABLE_NAME




I want to get the distinct results for DocTitle, with 5 other columns added to the query so they can be displayed in a web page list.
The query I want is something like this, but I can not get it to work:

sql Code:






Original
- sql Code




SELECT DISTINCT DocTitle, ID, FirstName, LastName, Company, DocDescription, DocFile
FROM dbo.TBL_TABLE_NAME
ORDER BY DocTitle






SELECT DISTINCT DocTitle, ID, FirstName, LastName, Company, DocDescription, DocFileFROM         dbo.TBL_TABLE_NAMEORDER BY DocTitle



I know this query works from an MS Access DB, but I need it to work from SQL Server.

I am using SQL Server 2000

Any help is greatly appreciated.

Alex

View 1 Replies View Related

Transact SQL :: Query Distinct Results Based On Date Range

May 21, 2015

I have a data structure like this

UID , Name, amount, start date                               End Date
     1      A         10         2015-05-01 00:00:00             2015-05-01 23:59:59
     2      A         10         2015-05-02 00:00:00             2015-05-02 23:59:59
     3      A         10         2015-05-03 00:00:00             2015-05-03 23:59:59
     4      A         10         2015-05-04 00:00:00             2015-05-04 23:59:59
      5      B         10         2015-05-05 00:00:00             2015-05-05 23:59:59

[code]...

View 5 Replies View Related

SQL DISTINCT UNIQUE QUERY

May 4, 2007

I have a problem with a SQL SELECT query. As far as my research goes i figured out that UNIQUE is used when you have one column that you whant unique and DISTINCT is used when you have more than one column that you want to all be unique. But i have a query where i want just some of the columns to be unique and some not. Here is the full query (It's in a stored procedure):

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[rpt_ExecSum_Combined_4fields](@BondGroupID int)
AS SELECT DISTINCT
SUM(dbo.Bond.LoanAmount) AS SumOfBondValue, COUNT(dbo.Bond.BondID) AS CountOfBond, dbo.ProgressStepType.ProgressStepType
FROM dbo.BondGroup INNER JOIN
dbo.TransactionTable ON dbo.BondGroup.BondGroupID = dbo.TransactionTable.BondGroupID INNER JOIN
dbo.Bond ON dbo.TransactionTable.TransactionID = dbo.Bond.TransactionID INNER JOIN
dbo.ProgressStep ON dbo.TransactionTable.TransactionID = dbo.ProgressStep.TransactionID INNER JOIN
dbo.ProgressStepType ON dbo.ProgressStep.ProgressStepTypeID = dbo.ProgressStepType.ProgressStepTypeID
WHERE (dbo.BondGroup.BondGroupID = @BondGroupID)

GROUP BY dbo.ProgressStepType.ProgressStepType, dbo.ProgressStep.ProgressStepID
HAVING (dbo.ProgressStepType.ProgressStepType = 'AIP (Approval in Principle) received') OR
(dbo.ProgressStepType.ProgressStepType = 'Grants') OR
(dbo.ProgressStepType.ProgressStepType = 'Attorney') OR
(dbo.ProgressStepType.ProgressStepType = 'Feedback received from bank')
ORDER BY dbo.ProgressStepType.ProgressStepType

*********
With the DISTINCT it gives me a full set of unique values but what i want is this: Every CountOfBond may have more than one SumOfBondValue and they may be the same, but if there is more than one dbo.ProgressStepType.ProgressStepType the query should only read it once. In other words the dbo.ProgressStepType.ProgressStepType is a unique value and the rest not...

Please help, my boss is on my case :)

View 14 Replies View Related

Update ONLY When Unique Or Distinct

Nov 7, 2007

Im running updates on a table. I would like to only update the table with new records. Right now, Im running a query that will only update the records that were added yesterday. Here is my code:

FROM GRAB where BKDATE = convert(varchar(8), getdate()-1, 112)

I would like to Update like this (incorrect syntax):

FROM GRAB where FCN is distinct

I know the above is incorrect.... what would be correct?

Thanks again

View 15 Replies View Related

Distinct Count Fall Under Unique ID

Feb 19, 2014

Aim- Need to count how many [FDMSAccountNo] fall under a unique parentid

This is my query

SELECT [FDMSAccountNo]
,ParentID
FROM [FDMS].[dbo].[Dim_Outlet]
where ParentID = '878028271889'

Which produces the following, The number of fdmsaccountno under parentid is two. Its two because one of the fdmsaccountno is = to parentid

FDMSAccountNo ParentID
878028271889878028271889
878028272887878028271889
878028273885878028271889

Desired result

Parentid #_of_outlets
878028271889 2

View 5 Replies View Related

Distinct, Unique, Group By, 'Footing'?

Jun 13, 2007

I created an ouput text file that was perfect until specs were revised today to add quarterly tax and deduction summations for each employee. (Expected turnaround time for new spec: today!)

So my employee record now has 8 records (which I expected) because I had to join it to the pay_summary table. Like this:

SELECT
COALESCE(CONVERT(char(1),e.record_status),'')
+ COALESCE(CONVERT(char(4),'97 '),'')
and many more fields
from employees as e
JOIN emp_taxes as t on e.employee_no = t.employee_no
LEFT OUTER JOIN pay_summary AS p ON e.employee_no = p.employee_no

Where
dateadd(d, 0, datediff(d, 0, p.dated)) BETWEEN '20061231' AND '20070401'

and e.record_status not like 'D'
and t.tax_authority_type = 'F'
and e.company_no = '2' and e.employee_no = t.employee_no

order by e.employee_no

There are 6 or so fields I intend to sum as records to go into the
file. In another language, in order to get one record per employee_no, the syntax would be like this:

sort on employee_no
footing at employee_no
report field_a field_b field_c subtotal field_e field_f subtotal

in which case fields c and f are numeric and summed from the multiple pay_summary records.

What is the (most efficient) SQL command to give only one record per
employee while summing all the detail records?

I can't thank you guys enough for this forum.

Lisa

View 9 Replies View Related

Distinct Vs. Unique Index In Stored Procedure

Jun 10, 2004

Hi All,

I'm struggling with this one.
We have a Street database that can contain multiple entries for one record in our main table. We don't wish to pass duplicate rows back to our end user so I wish to get distinct recno's (the unique identifier for the main table) back from our Street Table.

We have a stored procedure that currently uses Select distinct Recno but I think this is slower than if I used a unique index with ignore_dup_key. Problem is that when I alter the stored procedure it looks like the functionality of the LIKE function is somehow altered. For example Like 'King%' fails to return anything but Like 'King St%' does. I suspect it is the fact that the error "Server: Msg 3604, Level 16, State 1, Procedure" is being generated. How do I code around this server side.

View 2 Replies View Related

How To Use Distinct To Select Unique Records But Without Sorting ?

May 30, 2008



Hi

I need to select unique records from a Table. I'm using Distinct Keyword for this purpose. But the result set is showing distinct records in sorted order. I do'nt want to sort records. I need the order in which they are created in table.

Please suggest me the solution for this problem.

Thanks

Regards

Avinash Vyas

View 4 Replies View Related

Creating Index On A View To Prevent Multiple Not Null Values - Indexed View?

Jul 23, 2005

I am looking to create a constraint on a table that allows multiplenulls but all non-nulls must be unique.I found the following scripthttp://www.windowsitpro.com/Files/0.../Listing_01.txtthat works fine, but the following lineCREATE UNIQUE CLUSTERED INDEX idx1 ON v_multinulls(a)appears to use indexed views. I have run this on a version of SQLStandard edition and this line works fine. I was of the understandingthat you could only create indexed views on SQL Enterprise Edition?

View 3 Replies View Related

Calling A Stored Procedure From A View OR Creating A #tempTable In A View

Aug 24, 2007

Hi guys 'n gals,

I created a query, which makes use of a temp table, and I need the results to be displayed in a View. Unfortunately, Views do not support temp tables, as far as I know, so I put my code in a stored procedure, with the hope I could call it from a View....

I tried:

CREATE VIEW [qryMyView]
AS
EXEC pr_MyProc


and unfortunately, it does not let this run.

Anybody able to help me out please?

Cheers!

View 3 Replies View Related

DISTINCT Results Based On The Value Of One Col?

Jun 19, 2008

Here's one thats had me and a coworker puzzled. Hopefully it's something simple:

TABLE A: (log of messages)
userid, int
date, datetime
message, varchar(50)

Table A Data:
1, 6/18/2008 @ 2:32:41, This is my message
1, 6/18/2008 @ 2:31:02, This is my message
1, 6/17/2008 @ 7:34:26, This is another message
2, 6/18/2008 @ 2:32:41, This is not his message
2, 6/16/2008 @ 11:21:32, This is my message


TABLE B: (List of users)
userid, int
name, varchar(100)

Table B Data:
1, John
2, Mike

I want to extract the most recent message logged per user, i.e.:

name | date | message
--------|---------------------|-------------------------
John | 6/18/2008 @ 2:32:41 | This is my message
Mike | 6/18/2008 @ 2:32:41 | This is not his message.

I have been unable to come up with a query that can return just the one value. I've tried variants of:

SELECT DISTINCT b.name, a.date, a.message
FROM a INNER JOIN
b ON a.userid = b.userid

including sub-queries and even played with the visual diagrams trying to design this in Enterprise Manager but none of the combinations I tried work. Is there an easy way to do this via a query? I don't have experience with stored procedures. Would that be necessary?

TIA

View 4 Replies View Related

Not Getting Distinct Results With Inner Join

Mar 5, 2007

Hello, first post since I can usually find answers by reading the forums. I've searched the internet up and down and for some reason I can't get this query to work properly.

I have two tables:

ticket

ticket_id
ticket_to
ticket_from

message

message_id
ticket_id
message

There can be several messages per ticket, connected by the ticket_id. I'd like to only pull only the most recent message, as well as the results from the ticket table. Currently I'm getting all messages per ticket.

Here's what I have:

SELECT distinct ticket.ticket_to, ticket.ticket_from, message.ticket_id, message.message
FROM tickets
INNER JOIN message ON tickets.ticket_id = message.ticket_id
GROUP BY message.ticket_id, message, ticket_to, ticket_from

Any help would be greatly appreciated! Thanks much.

View 3 Replies View Related

Select Distinct Results From Where Clause?

Jul 14, 2014

Just wondering if it's possible to select distinct results from the where clause?

View 3 Replies View Related

Row_number With Distinct And Inner Join Messes Up Results

Jul 28, 2007

I want to select all usernames from tlbUsers which practice a certain sport.I also have a table UsersAndSports:UserID intSportID intI therefore need an inner join statement:select username from(SELECT ROW_NUMBER() OVER (ORDER BY au.LastActivityDate DESC) as RowNum,ud.username from tblusers usinner join tblUsersAndSports uas on uas.usercode=us.usercode and (uas.sportID=3 or uas.sportID=4)WHERE us.UserName <>''  )as MemberInfo WHERE RowNum between (@startRowIndex+1) AND (@startRowIndex+@maximumRows)The problem lies in the usage of the ROW_NUMBER command. I need that in order to effectively page through my records, but it also makes thatI cant make a distinct selection as each RowNum is unique....:SIn case the user would practice 2 sports, the query would return 2 rows...if I place a distinct in front of the username as such:select distinct username fromThe query would return each user only once...BUTBUTBUT: my startrowindex and maximumrows apply to the results that can be found in the MemberInfo selection..so lets say my startrowindex would be 0 and maximumrow 5if my 1st query (without distinct) was to return:johnjohnjohnjohnmikemikerobmy 2nd query (with distinct) would return:johnmikewhereas I want it to return:johnmikerobWhat can I do?

View 2 Replies View Related

Using Distinct And Count (*) Is Not Giving The Results Expected

Feb 12, 2008

I have 2 tables.  Product, ProductCategory.
Product table consists of (productid, productname, producttypeid, createdate, portid)
productcategory consists of (productid, categoryid, productcategoryid, categoryid, prodroletypeid, createdate)
I want to write sql query to get the unique products.  So the count should only give one value/resuls.  But when I run the following query, I am getting more than one rows
select count(distinct categoryid) as uniquecat
from productcategory as pc, product as p
where pc.prodroletypeid in ('P', 'F')
and pc.createdate <= dateadd(d, 30, getdate())
and p.portid = 100
group by pc.productid
 
 

View 3 Replies View Related

Displaying Distinct Results From Union Query

Aug 31, 2000

I've got a union query (below)and it returns rows that have duplivate itemno's, descrip's, imsrp3's, and imsrp4's, while the remaining columns are not duplicate for the same row. An Excel report uses this query to populate itself and for a more visually appealing look, I'd like to skip the duplicated columns in the display. I'm not sure how to use the Distinct or Group by in this case, since technically I'm dealing with two separate queries, neither one separately returning any duplicate rows.
thanks for any suggestions...

~
select itemno,descrip,imsrp3,imsrp4,qoh,border,wadcto,wad oco,
watrdj,wapddj,wauorg,wauser
from nowo
where nowo.wasrst <='40'
union
select itemno,descrip,imsrp3,imsrp4,qoh,border,wadcto,wad oco,
watrdj,wapddj,wauorg,wauser
from nopo
where nopo.wasrst <='499'

View 1 Replies View Related

Extract Distinct Information And Order The Results

Sep 24, 2007

Hi,

MSSQL 2000 T-SQL

I have a problem in extracting information pertaing to a key value and matching that key value to another transaction but the order is based on another value in the same row.


I've attached a sample of DB data below.

tran_nr ret_ref_no msg_type description
5111 12345 420 reversal
5112 12345 200 auths
5113 15236 200 auths
5114 46587 200 auths
5115 46587 420 reversal

Requirement using the above data is to extract data where the ret_ref_no is the same for more than one row but also check that the msg_type 420 happens before the 200. Is there a way of retrieving the information in this way using the tran_nr coloumn values? The tran_nr values is basically the serial number when the transaction is wrriten away to the DB.

I've managed only to retrive the 1st half of my query whereby the same ret_ref_nr is being used by more then one transaction. Still need to figure out the 2nd part where the msg_type of 420 happens before the 200.


SELECT * FROM SAMPLE
WHERE ret_ref_no in
(
SELECT ret_ref_no FROM SAMPLE
GROUP BY ret_ref_no HAVING COUNT(*) > 1
)

Results of query
5111 12345 420 reversal
5112 12345 200 auths
5114 46587 200 auths
5115 46587 420 reversal

If someone could assist with only retreiving the above results in bold to the query analyser i will really appreciate it.

Regards
Deceptive

View 9 Replies View Related

Unique Results Based On Popularity Voting

Jun 18, 2008

I've managed to get my query to this: Product | Color | Votes
======== ======= =======
Bus Red 10
Bus Blue 5
Train Blue 1Car Red 1
Car Blue 1
 
I need the most popular color of the product based on the votes for each product, so MAX(Votes) GROUP BY Product solves the Bus and the Train, but I still need a result for the Car? Not really that bothered which Color is picked up, do I need to run another query, because I need another table to join to the results.
 
Any help would be greatly appreciated.
Thanks, Pete.

View 2 Replies View Related

Creating A Unique Field

Nov 30, 2000

I have built a table called Visit_Fact, which is detailed medical data. Within this table I have to create several index fields.

Well one of the fields ([Diag Code]) that should be included will have null values.

Well in Access I was able to build my new field called IndKey which has the following SQL statement:

IndKey: [PracticeCode]&[Physician Code]&[Chart #]&[Visit #]&[InsCoNum]&[CPT]&[Modifier]&[Units]&[Diag Code]

1. Example data with Diag Code = null
ABCD1234ABCDEF1234567MEDI19921301

2. Example data with Diag Code <> null
ABCD1234ABCDEF1234567MEDI19921301708.1

This runs fine in Access and if the Diag Code is null, Access does not care, it still puts all the other information together. Such as the examples above.

Well I tried doing this in a Stored Procedure and when I ran across a record that had a null value for the [Diag Code] it made the IndKey field Null for that record. If it was not null then it looked like Example 2.

What is the proper way of creating my unique field in SQL Server?

View 2 Replies View Related

Creating A Unique Index

Jul 20, 2005

HiI tried the following from the help file...When you create or modify a unique index, you can set an option toignore duplicate keys. If this option is set and you attempt to createduplicate keys by adding or updating data that affects multiple rows(with the INSERT or UPDATE statement), the row that causes theduplicates is not added or, in the case of an update, discarded.For example, if you try to update "Smith" to "Jones" in a table where"Jones" already exists, you end up with one "Jones" and no "Smith" inthe resulting table. The original "Smith" row is lost because anUPDATE statement is actually a DELETE followed by an INSERT. "Smith"was deleted and the attempt to insert an additional "Jones" failed.The whole transaction cannot be rolled back because the purpose ofthis option is to allow a transaction in spite of the presence ofduplicates.But when I did it the original "Smith" row was not lost.I am doing something wrong or is the help file incorrect.Dan

View 3 Replies View Related

Creating A Unique Temp Table.

Jan 11, 2007

Set Quoted_Identifier On
Go
Set Ansi_Nulls On
Go

Alter Procedure spReport_SomeFooReport
@SearchFromThisDate datetime = null, @SearchToThisDate datetime = null

As
Declare @TableUniqueIdentifier varchar(80), @SQLString varchar(5000)

set @TableUniqueIdentifier = newid()
set @TableUniqueIdentifier = 'Report_SomeFooReport' + @TableUniqueIdentifier
set @TableUniqueIdentifier = replace(@TableUniqueIdentifier, '-', '7')
set @SQLString = 'Create Table ' + @TableUniqueIdentifier + ' (xxx varchar(40))'
exec @SQLString

Return
Go
Set Quoted_Identifier Off
Go
Set Ansi_Nulls On
Go


-------------------------------------------
the error is:
Server: Msg 2812, Level 16, State 62, Line 12
Could not find stored procedure 'Create Table Report_SomeFooReport06EEEC8D7EA6A74D0178EDD79E999B (xxx varchar(40))'.

So may'be a format issue or something,
im trying to create "temp" tables for sql 2005 report services in my Stored procedures which would have a sql job to get deleted at 23:00

View 5 Replies View Related

Transact SQL :: First DISTINCT Value In A Result Set

Jun 23, 2015

I created a view which gave me the TOP1000 Companies we do consulting work for.

It includes their name, rank, year, companyID. I wanted to then link this view to the address table. I was able to do this, but because one company might have multiple addresses my result set was large when I started out by just adding city to my view. How can I take my result set and just choose the first DISTINCT value in the result set? Here's an example of the result set:

Name                   Rank           Year      CompanyID           City

Bill's Fish                 22          2015         779             Sunrise
Bill's Fish                 22          2015         779             Billings

I just want the Sunrise as city record.

View 20 Replies View Related

SQL 2012 :: Creating A Unique ID For Groups Of Rows?

Mar 20, 2015

We have a sorted data that looks like the first 3 columns below, and fourth colum is what I want to create)

Shift_start meal_break shift_endShift ID
1 0 0 1
0 0 0 1
0 0 1 1

1 0 0 2
0 0 0 2
0 0 1 2

I need to find a method to assign unique Shift IDS to rows that correspond to a single shift. For instance, the first shift would begin on the first row when shift_start flag is turned on, and end on the third row when shift_end flag is turned on.

Can I do this in SQL ?...some kind of grouping ?

View 2 Replies View Related

How To Create Unique Field Or Sequence In View

Jun 5, 2012

I have created a view based on joining 3 tables, however, it is not possible to have a unique field in the view which I must need it and I must create index on some other fields. Is there any way to create sequence number or uniqie field in mssql view.

View 13 Replies View Related

How To Create Non-unique Clustered Indexed View?

May 30, 2008

I'm not able to create indexed views,
which are clustered-indexed on only 1st field.

I can't even INCLUDED other fields.

I need the entire view to exist as a physical table. (for performance)

Please let me know the work around.


Thanks..

View 1 Replies View Related

Transact SQL :: Sum Of Distinct Service Numbers?

Jun 17, 2015

I have data in the below format 

Service Numbers    start datetime     enddate time        part number     Calc(in hrs (endate - startdate) 
223344                  2014-05-05          2014-05-07       12345               48
223344                  2014-05-05          2014-05-07       56789               48
223355                  2014-05-06          2014-05-07       17865               24
223355                  2014-05-06          2014-05-07       76543               24
345627                  2014-05-09         2014-05-013      76543               72

I want measure like  sum of  hours of distinct service numbers.I want to use it in a reporting tool.

it means my sum will be 144 and my Average of per time closed will be 144/3 =  48.

How to create a measure like that ?

View 4 Replies View Related

Transact SQL :: Getting Distinct Row With Min Date From Other Table?

Sep 18, 2015

Have the following 2 tables:

create table #LiabilityConstraint
(
PolNum varchar(10),
LcCode varchar(10),
LcDsc varchar(100),
LcAmt decimal(18,2),
LcFreq varchar(10),
LcSetId int

[code]....

there is a many to many relation between the tables.  Each Policy can have 1 or many Liability Constraints.  Each Liability Constraint can be attached to 1 or many policies.

What I need to do is get the distinct combination of LcCode, LcDesc, LcAmt, LcFreq and LcSetId from the Liability table as well as the earliest PolInceptionDt from any of the policies associated with the Liability Constraint using only the distinct combination of LcCode, LcDesc, LcAmt, and LcFreq.

Give the data above, I would need to end up with the following result:

I tried to use the Row_Number functionand join using PolNum, but I keep getting the wrong results back.

View 4 Replies View Related

Creating A Unique Constarint On A Multiple Null Column

Aug 3, 2007



HI,

To create a unique constraint on a multiple nullable column, we need to create a view with not null column and and then create a unique index on that view.

Is this is the only way of doing ?

Thank you.

View 1 Replies View Related

Transact SQL :: Inserting Distinct Data From One Table To Another

Aug 19, 2015

I have 2 tables: Source Table - IncidentDimNew and Destination Table - IncidentDimNew with identical columns: Id and CreatedDate but the data is different.

I would like to insert distinct data from those 2 columns of 1st table into the same 2 columns into the 2nd table but I onlt want to replace the values in the 2nd table where the Created Date is > 2015-04

I compiled the code in order to get the information I want from 2 tables:

Source Table
SELECT
COUNT(Id),
LEFT(CONVERT(VARCHAR(10)), CreatedDate, 126), 7)
FROM
IncidentDimNew

[Code] ...

This is the code I wrote in order to do it
                     
INSERT INTO IncidentDim 
[Id]
      ,[CreatedDate]
     SELECT
[Id]
,[CreatedDate]

FROM
IncidentDimNew

where left(CONVERT(VARCHAR(10), CreatedDate, 126),7) > '2015-04'

GO

But what it does it's gives the SUM of the values in the corresponding rows where the values are not null which I don't want.

So  how do I leave the values as is from table IncidentDim and insert new values as it is from IncidentDimNew where the Created Date is > 2015-04?

View 2 Replies View Related

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

Transact SQL :: How To Get Distinct Count Of All Columns Of A Table

Dec 3, 2015

I have a table called Employee which have 6 columns. This table are having 1000 records. Now I want to know the distinct value count of all these 6 columns as well as normal count. like this:

ColumnName DistinctCount NormalCount
Id 1000 1000
Name 1000 1000
Phone 600 600
PINCode 200 1000
City 400 1000
Gender 2 1000

View 5 Replies View Related

Transact SQL :: Distinct Values From Multiple Tables?

Nov 2, 2015

best way to go about this. My query works great and displays the information I require.

EG all demographic for ED, IP & OP. However if a patient has a record in each of the tables then I get the same info multiple times.

What I'm trying to do is a Select Distint against the entire query (below).

eg Select Distinct * from all below.

DECLARE @StartDate datetime = '01 oct 2015';
DECLARE @EndDate datetime = '30 OCT 2015';
--***OUTPATIENT DQ QUERY***--
SELECT distinct
HEYNo,
NHSNo2,
NHSNo1,

[code]....

View 3 Replies View Related







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