Codeigniter - Concat查询

时间:2017-10-03 01:08:12

标签: sql-server codeigniter concatenation

所以我有这张桌子

EMP_ID     SECTION       TEST     SAMPLE_NAME   QUANTITY
 1001     molecular       reo         heart         3
 1001     molecular       reo         spleen        4

这是我的MODEL代码。

$query = $this->db->select('section, quantity,test,sample_name')
            ->from('tblmastersection')
            ->where('emp_id', $emp_id)
            ->order_by("save_section_id", "asc")
            ->join('tblsavesection', 'tblmastersection.section_id = tblsavesection.section_id', 'inner')
            ->join('tbljoinedtests', 'tblsavesection.test_id = tbljoinedtests.test_id', 'inner')
            ->join('tblmastersample', 'tblsavesection.samp_id = tblmastersample.samp_id', 'inner')
            ->get();
    return $query->result();

我想做的就是让它像这样......

EMP_ID     SECTION       TEST       SAMPLE_NAME        QUANTITY
 1001     molecular       reo       heart, spleen         7

具有相同EMP_ID的行将连续并且数量将汇总。 有人请帮我重新设计我的代码。非常感谢。

2 个答案:

答案 0 :(得分:0)

我可以改为sql选择这样:

SELECT EMP_ID,sum(QUANTITY) QUANTITY , STUFF(( SELECT  ','+ SAMPLE_NAME FROM TableName a
WHERE b.EMP_ID = a.EMP_ID FOR XML PATH('')),1 ,1, '')  Members
FROM TableName b
GROUP BY EMP_ID;

答案 1 :(得分:0)

所以我已经做了一个SQL-SERVER查询来回答我的问题。我现在的问题是将其转换为codeigniter模型查询代码....

这是我的SQL查询....

SELECT section, test, samp_id = 
STUFF((SELECT ', ' + sample_name
       FROM tblsavesection 
       inner join tblmastersample
       on tblsavesection.samp_id = tblmastersample.samp_id
       WHERE emp_id = '1' AND tblsavesection.test_id = tbljoinedtests.test_id
      FOR XML PATH('')), 1, 1, '')
      ,SUM(quantity)as Quantity
FROM tblsavesection
inner join TblJoinedTests
on TblSaveSection.test_id = TblJoinedTests.test_id
inner join Tblmastersection
on TblSaveSection.section_id = Tblmastersection.section_id
GROUP BY test, section, tbljoinedtests.test_id

谢谢! =)