SQL获取满足不同条件的条目数

Dan*_*ilo 4 sql

目标是检索一个表中具有以下内容的用户数:

  1. 字段EXPIREDATE> CURRENT_TIMESTAMP as nUsersActive
  2. 字段EXPIREDATE <CURRENT_TIMESTAMP为nUsersExpired
  3. 字段EXPIREDATE为nUsersPreregistered时为NULL

所有一个查询,结果应该是例如

nUsersActive    nUsersExpired     nUsersPreregistered
10              2                 15
Run Code Online (Sandbox Code Playgroud)

稍后将进行json_encoded并将其传递给ExtJS脚本进行显示.

任何提示?我试了好几次都没有成功.我尝试使用UNION语句,我得到了正确的数字,但当然是在列中,而我需要它们排成行.

感谢您的支持.

a'r*_*a'r 6

类似下面的内容应该可以工作,您可能需要针对您正在使用的特定数据库进行调整.

要在列中获取它们:

select
    count(case when EXPIREDATE > CURRENT_TIMESTAMP then 1 end) AS nUsersActive,
    count(case when EXPIREDATE < CURRENT_TIMESTAMP then 1 end) AS nUsersExpired,
    count(case when EXPIREDATE IS NULL then 1 end) AS nUserPreregistered
from users_table
Run Code Online (Sandbox Code Playgroud)

在行中(这不是那么有效!):

  select 
    'nUsersActive' AS Param
    count(case when EXPIREDATE > CURRENT_TIMESTAMP then 1 end) AS Value
  from users_table

UNION ALL

  select 'nUsersExpired',
    count(case when EXPIREDATE < CURRENT_TIMESTAMP then 1 end)
  from users_table

UNION ALL

  select 'nUserPreregistered',
    count(case when EXPIREDATE IS NULL then 1 end)
  from users_table
Run Code Online (Sandbox Code Playgroud)