This is my table(Tbl_12042014) with fields like recordId,batchName,SubaBatchname,OpStatus1,OpStatus2.
RecordId Batchname SubBatchname OpStatus1 OpStatus2
1 12042014 raw3 D D
2 12042014 raw3 D D
3 12042014 raw4 Null Null
4 12042014 raw4 Null Null
I used this query with group by but i didnt get desired output.
I want count recordId and column which having Status 'D' for respective subbatchName. fields with null value should be rejected.
Query
SELECT BatchName,SubBatchName,Count(RecordId)AS Records,
(Select count ( a.Opstatus1) FROM Tbl_12042014 as a where Opstatus1='D' ) as DE1,
(Select count(b.Opstatus2) FROM Tbl_12042014 as b where Opstatus2='D' )as DE2
FROM Tbl_12042014 GROUP BY BatchName, SubBatchName
I got output like by executing above query. I got DE1,DE2 count is 2 for raw3 and 2 for raw4.
Batchname SubBatchname Records DE1 DE2
12042014 raw3 2 2 2
12042014 raw4 2 2 2
But my desired output is like DE1,DE2 should be 2 for raw3 and 0 for raw4.
Batchname SubBatchname Records DE1 DE2
12042014 raw3 2 2 2
12042014 raw4 2 0 0
you can do this with case based aggregation
SELECT BatchName,SubBatchName, Count(RecordId)AS Records,
sum(case when Opstatus1='D' then 1 else 0 end) as DE1,
sum(case when Opstatus2='D' then 1 else 0 end) as DE2
FROM Tbl_12042014 GROUP BY BatchName, SubBatchName
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.