Friday, October 4, 2013

top 5 populated states from each country



select state_name, county_name, population
from (
    select
        s.name state_name,
        c.name county_name,
        c.population,
        row_number() over(partition by s.state_code order by population desc) rn
    from
        states s
        inner join
        counties c on s.state_code = c.state_code
) s
where rn <= 5
order by state_name, population desc

Wednesday, October 2, 2013

php date difference excluding weekends

Method 1:-

$start = new DateTime('2012-09-06');
$end = new DateTime('2012-09-11');
// otherwise the  end date is excluded (bug?)
$end->modify('+1 day');

$interval = $end->diff($start);

// total days
$days = $interval->days;

// create an iterateable period of date (P1D equates to 1 day)
$period = new DatePeriod($start, new DateInterval('P1D'), $end);

// best stored as array, so you can add more than one
$holidays = array('2012-09-07');

foreach($period as $dt) {
    $curr = $dt->format('D');

    // for the updated question
    if (in_array($dt->format('Y-m-d'), $holidays)) {
       $days--;
    }

    // substract if Saturday or Sunday
    if ($curr == 'Sat' || $curr == 'Sun') {
        $days--;
    }
}


echo $days;
 
 
Method 2:- 
 
$datetime1 = new DateTime('2012-09-06');
$datetime2 = new DateTime('2012-09-11');
$interval = $datetime1->diff($datetime2);
$woweekends = 0;
for($i=0; $i<=$interval->d; $i++){
    $modif = $datetime1->modify('+1 day');
    $weekday = $datetime1->format('w');

    if($weekday != 0 && $weekday != 6){ // 0 for Sunday and 6 for Saturday
        $woweekends++;  
    }

}

echo $woweekends." days without weekend";
 
 
Method 3:-  

$start = strtotime('2012-08-06');
$end = strtotime('2012-09-06');

$count = 0;

while(date('Y-m-d', $start) < date('Y-m-d', $end)){
  $count += date('N', $start) < 6 ? 1 : 0;
  $start = strtotime("+1 day", $start);
}

echo $count;