有没有办法将单个字段值拆分为多个列

时间:2017-01-21 10:36:22

标签: mysql sql database

我有一种情况,我应该显示private isAdminSubj: Subject<boolean> = new Subject<boolean>(); private isAdmin: Observable<boolean> = this.isAdminSubj.asObservable(); canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>{ /* to store and redirect after login if user not logged in */ let target_url: string = state.url; this.verifyLoginForAdmin( target_url ); return this.isAdmin; } 时尚

即时使用此columnar

query

它会返回类似这样的内容

SELECT status, count(*) as total_
FROM companydata 
WHERE status = 'Not Emailed' or status = 'Not Emailed' or status = 'Email Sent' or status = 'Response Received' or status = 'Interested' or status =
'Not Interested'
GROUP BY status

有没有办法让它们看起来 status total_ -|--------------------|-------------------------- Not Emailed 9562 | Interested | 2 Response Received 45 | Email Sent | 3000 时尚

columnar

2 个答案:

答案 0 :(得分:1)

更改原始查询以有条件地计数

SELECT Count(CASE WHEN status = 'Not Emailed' THEN 1 END) AS `Not Emailed`,
       Count(CASE WHEN status = 'Email Sent' THEN 1 END) AS `Email Sent`,
       Count(CASE WHEN status = 'Response Received' THEN 1 END) AS `Response Received`,
       Count(CASE WHEN status = 'Not Interested' THEN 1 END) AS `Not Interested`
FROM   yourtable
WHERE  status IN ( 'Not Emailed', 'Not Emailed', 'Response Received', 'Interested', 'Not Interested' ) 

我们可以使用COUNT聚合代替SUM而不是

Sum(CASE WHEN status = 'Not Emailed' THEN 1 ELSE 0 END) AS `Not Emailed`

答案 1 :(得分:1)

这是对prdp答案的详细说明。在MySQL中,我认为最简单的方法是:

SELECT SUM(status = 'Not Emailed') AS `Not Emailed`,
       SUM(status = 'Email Sent') AS `Email Sent`,
       SUM(status = 'Response Received') AS `Response Received`,
       SUM(status = 'Not Interested') AS `Not Interested`
FROM yourtable
WHERE  status IN ( 'Not Emailed', 'Not Emailed', 'Response Received', 'Interested', 'Not Interested' ) ;

CASE也是正确的 - 并且可以移植到大多数数据库。这只是MySQL中的一个方便的简写。