我们能否以比下面的核心SQL更多的Yii2 ActiveQuery方式拥有 切换案例查询 ?
$comboGraph = \Yii::$app->db->createCommand('select class , count(*) registered, '.
'sum(case when payment_status = \'1\' then 1 else 0 end) paid, '.
'sum(case when payment_status = \'0\' then 1 else 0 end) unpaid '.
'from students group by class ORDER BY FIELD(class,\'V\',\'VI\',\'VII\')')
->queryAll();
即使我使用上述查询,我也会得到结果,但我希望我的东西更多Yii2 Specific。那么有什么建议吗?
答案 0 :(得分:1)
createCommand的使用是Yii2投诉..(目前还没有针对manage CASE WHEN ..语句的特定功能,这些状态由flat sql指令管理)
但可能是您想使用查询构建器和相关函数.. http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
$comboGraph = (new \yii\db\Query())
->select("class
, count(*) registered
, sum(case when payment_status = '1' then 1 else 0 end) paid
, sum(case when payment_status = '0' then 1 else 0 end) unpaid")
->from('students')
->groupBy('class')
->orderBy("FIELD(class,'V','VI','VII')")
->all();
您可以使用单引号和双引号的正确组合来获得更好的阅读