views:

54

answers:

1

Hello all,

First of all, I don't want to use a "join" because that will make my query longer and difficult to read. So what I need to do must be withing the same SELECT statement.

My columns in myTable are A, B , C , D , time, ID and H

H columnd tells if a record is 'Open' or 'Close', here how my query looks like.

SELECT 
A, 
B, 
C, 
D,
COUNT(DISTINCT ID) AS numberOfRecords,
SUM(time) / COUNT(DISTINCT ID) AS averageTimeOfAllRecords   
FROM myTable
WHERE ISNUMERIC(A)=1 AND A IN (SELECT A FROM myTable2)
GROUP BY A,B,C,D

I need the query above to return another column with a result: COUNT(DISTINCT ID) WHERE H = 'Open' so that I can get numberOfOpenRecords.

I can't write my new condition to my "WHERE", because that will effect the results, like numberOfRecords.

Hope I explained my problem.

Thanks for helps.

+3  A: 

Since count doesn't count null values, you could:

count(distinct case when H = 'Open' then id else null end)
Andomar
After editing my code by adding distinct, it returned rows as 1 or 0 only. My numberOfRecords column is like that row by row: 7, 14, 14My openRecords column is like that without distinct: 10, 25, 15My open Records column is like that with distinct: 1, 1, 1How it realy should be is, for all that three top row, all the records are open, and hence it should have returned 7,14,14
stckvrflw
btw sorry that I didn't implement your code with the way you wrote, I did it like count(distinct case when H = 'Open' then 1 else 0 end), that is why it returned like 1 or 0 only, If I wrote the exact way you told, then it tells me my ID is not countable, "The sum or average aggregate operation cannot take a nvarchar data type as an argument."
stckvrflw
PFF I am definitly sorry that I am a terrible reader. I copy pasted and that is why I didn't see that you wrote count instead of sum. Thanks for nice answer.
stckvrflw