简体   繁体   中英

How to use count twice on same column in a table

I've a table like below. What I want is to write a query which count all the rows where exit_flag is 0 and also count all the rows where exit_flag is 1 and than subtract the both counts and return a single value. How to do that using entity framework .

id created_date        device_id exit_flag
1  2017-10-24 23:00:00  13         0
2  2017-10-24 23:00:00  13         1
3  2017-10-24 23:30:00  13         0 
4  2017-10-24 23:30:00  13         1 

You can write something like below

select sum(exit_flag = 0),sum(exit_flag = 1),
sum(exit_flag = 0) - sum(exit_flag = 1)
from demo 
group by device_id

Demo

Using Mysql you can get your conditional count using sum function, When expression is used inside sum() it will return as boolean value 0/1

I have added group by device_id to get results per device if you want it for all the remove this part from query

one way is wirite two different query to count exit_flag is 0 and exit_flag 1

1). select count(*) as flg0 from table where exit_flag = 0;

2). select count(*) as flg1 from table where exit_flag = 1;

and then substrect both value

and another

1). select count(exit_flag = 0) - count(exit_flag = 1) as flg from table

var answer = (from item in context.items
              group item by 0 into sub
              select 
              sub.Where(x => x.exit_flag == 0).Count() - sub.Where(x => x.exit_flag == 1).Count()
             ).First();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM