我必须找出在2小时之前创建并且在过去两小时内创建的记录数。我可以找到使用
[最近两小时创建]
select count(*)
from trans_calc
where
I_TRACKING_CODE = 112
and d_entered > (current_timestamp - 2 hours)
[在两小时之前创建]
select count(*)
from trans_calc
where
I_TRACKING_CODE = 112
and d_entered < (current_timestamp - 2 hours)
我们可以合并这两个sqls或者事实上我们可以编写一个可以为我们提供所需输出的sql吗?
答案 0 :(得分:3)
试试这个:
SELECT
SUM(CASE WHEN d_entered>(current_timestamp-2 hours) THEN 1 ELSE 0 END AS NewerCount
,SUM(CASE WHEN d_entered<=(current_timestamp-2 hours) THEN 1 ELSE 0 END AS OlderCount
FROM trans_calc
WHERE I_TRACKING_CODE = 112
答案 1 :(得分:1)
怎么样
SELECT CASE WHEN (d_entered > (current_timestamp - 2 hrs)
THEN 'New'
ELSE 'Old' AS AGE
, Count(*) as Rows
from trans_calc
where I_TRACKING_CODE = 112
GROUP BY CASE WHEN (d_entered > (current_timestamp - 2 hrs) THEN 'New' ELSE 'Old'
答案 2 :(得分:0)
SELECT SUM(lasttwo) AS lasttwo, COUNT(*) - SUM(lasttwo) AS others
FROM
(
SELECT
CASE WHEN d_entered > (current_timestamp - 2 hours) THEN 1 ELSE 0 END AS lasttwo
FROM
trans_calc
WHERE
I_TRACKING_CODE = 112
) AS det
答案 3 :(得分:0)
是:
在一个输出行中,
select
Sum(Case When d_entered > (current_timestamp - 2 hours)
Then 1 Else 0 End) afterCount,
Sum(Case When d_entered <= (current_timestamp - 2 hours)
Then 1 Else 0 End) beforeCount
from trans_calc
where I_TRACKING_CODE = 112
或在BradC建议的两个单独的行中......
答案 4 :(得分:-1)
SELECT
d_entered > (current_timestamp - 2 hours) AS IsRecent,
COUNT(*)
FROM trans_calc
WHERE I_TRACKING_CODE = 112
GROUP BY IsRecent