MYSQL /查询生成器/ Eloquent - 将行转置为列

时间:2014-12-07 21:54:04

标签: php mysql laravel eloquent query-builder

**调度系统(按周预约的次数):**

我希望生成一个dashboard,显示一份顾问名单以及他们在未来几周内安排的约会人数。

所以我的sql查询/ eloquent等效查询我的具体方案如下:

select 
    consultant_id,
    count(appointment) as num_appointments,
    YEARWEEK(appointment, 1) as year_week 
from 
    appointments 
where 
    appointments.deleted_at is null 
    and appointments.consultant_id in (25, 29, 19, 38, 37, 32, 14, 21, 12, 40) 
    and appointment > '2014-12-07 16:39:07' 
    and YEARWEEK(now(), 1) + 4 >= YEARWEEK(appointment, 1) 
group by consultant_id, YEARWEEK(appointment, 1) 
order by consultant_id, YEARWEEK(appointment, 1) asc;


    $consultants = $this->consultant
        ->with(['appointments' => function($q) {
            $q->scheduled()
                ->where(\DB::raw('YEARWEEK(now(), 1) + 4'), '>=', \DB::raw('YEARWEEK(appointment, 1)'))
                ->select([
                    'consultant_id',
                    \DB::raw('count(appointment) as num_appointments'),
                    \DB::raw('YEARWEEK(appointment, 1) as year_week'),
                ])
                ->groupBy(\DB::raw('consultant_id, YEARWEEK(appointment, 1)'))
                ->orderBy(\DB::raw('consultant_id, YEARWEEK(appointment, 1)', 'DESC'));
        }])
        ->orderBy('name')
        ->paginate(10);

这对每位顾问都有效,如果有约会,它将提供如下信息:

consultant_id   num_appointments    year_week
14                      5            201450
14                      3            201451
29                      4            201450
29                      1            201451
40                      1            201450
40                      1            201452

但是,如果没有约会,则year_week将会丢失。

所以在mysql中,然后在Laravel的查询构建器中,我希望能够将year_week行转置为列。这样表格将输出:

consultant_id    week0     week1    week2
consultant_id   201450    201451    201452
14                 5         3         NULL
29                 4         1         NULL
40                 1         NULL      1

更新

SELECT
  consultant_id,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 0 WEEK), 1) = YEARWEEK(appointment, 1) THEN 1 END) as this_week,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 1 WEEK), 1) = YEARWEEK(appointmnet, 1) THEN 1 END) as week1,
  COUNT(CASE WHEN YEARWEEK(DATE_ADD(now(), INTERVAL 2 WEEK), 1) = YEARWEEK(appointmnet, 1) THEN 1 END) as week2
FROM
  demand as d
WHERE date_created >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
GROUP BY consultant_id;

1 个答案:

答案 0 :(得分:0)

解决方案1:在spatie macro collection中使用转置

转置的目标是旋转多维数组,将行转换为列,将列转换为行。

collect([
    ['Jane', 'Bob', 'Mary'],
    ['jane@example.com', 'bob@example.com', 'mary@example.com'],
    ['Doctor', 'Plumber', 'Dentist'],
]
)->transpose()->toArray();

// [
//     ['Jane', 'jane@example.com', 'Doctor'],
//     ['Bob', 'bob@example.com', 'Plumber'],
//     ['Mary', 'mary@example.com', 'Dentist'],
// ]

解决方案2:使用group by in collection groupBy方法按给定的键对集合的项进行分组:

$collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/