tags:

views:

66

answers:

5

I have to find out count of records which were created before 2 hours and which were created in last two hours. I can find that using

[ created in last two hours ]

select count(*)
 from trans_calc 
where
I_TRACKING_CODE = 112
and d_entered > (current_timestamp - 2 hours) 

[ created prior to two hours ]

select count(*)
 from trans_calc 
where
I_TRACKING_CODE = 112
and d_entered < (current_timestamp - 2 hours) 

Can we merge these two sqls or infact can we write a single sql which can give us the desired output?

+2  A: 

try this:

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
KM
I don't see horizontal scroll bars
KM
+1  A: 

How about

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'
BradC
A: 
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
Locksfree
A: 

Yes:

in one output row,

   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 

or in two separate rows as BradC suggested above...

Charles Bretana
your answer is same as `KM`. Great minds think alike. haha ;)
Rakesh Juyal
A: 
SELECT
    d_entered > (current_timestamp - 2 hours) AS IsRecent,
    COUNT(*)
FROM trans_calc
WHERE I_TRACKING_CODE = 112
GROUP BY IsRecent
dan04