选择具有多个值的记录并枚举它们

时间:2013-02-13 19:18:35

标签: php mysql

这就是我现在的表格:

如您所见,有多条记录,例如XRAY。 我想要做的就是列举那些 第一个X射线 第二个X射线 第3个X射线

或任何类型的枚举。

这是我当前表格的查询方式

"SELECT
             `incurredcharges`.`procedure_no`,
  `c`.`procedure`

FROM
  incurredcharges
  INNER JOIN (
    SELECT `procedure`, `procedure_no` FROM `charges`
    UNION ALL
    SELECT `confinement`, `procedure_no` FROM `confinement`
    UNION ALL
    SELECT `service`, `procedure_no` FROM `ultrasound`
  ) c ON `incurredcharges`.`procedure_no` = c.`procedure_no`
WHERE `incurredcharges`.`patient_no` = '$id'";

1 个答案:

答案 0 :(得分:0)

虽然我不知道如何前置“1st”,“2nd”等,但你可以在前面加上1,2等。这是一个例子:

SELECT
  CONCAT(CASE WHEN cnt > 1 THEN CONCAT(RN,'-') ELSE '' END, t.Proc) Proc
FROM
  (
    SELECT
      @curRow:=CASE WHEN @prevRow = a.Proc THEN @curRow+1 ELSE 1 END AS rn,
      a.Proc,
      @prevRow:=Proc grp
    FROM (
         SELECT Proc FROM Procedures ORDER BY Proc
      ) a JOIN (SELECT @curRow:=0) r
  ) t JOIN
  (
    SELECT Proc, COUNT(Proc) cnt 
    FROM Procedures 
    GROUP BY Proc
  ) c ON t.proc = c.proc

这是SQL Fiddle

基本上,您需要将程序分组在一起,为每个组分配行号。对于那些有多个的记录,先添加行号。

<强> --- --- EDIT

鉴于您的评论,您的查询只需要放在主FROM(中间附近),然后您需要将procno带到每个select语句。虽然未经测试,但这里应该非常接近:

SELECT
  procno,
  CONCAT(CASE WHEN cnt > 1 THEN CONCAT(RN,'-') ELSE '' END, t.Proc) Proc
FROM
  (
    SELECT
      @curRow:=CASE WHEN @prevRow = a.Proc THEN @curRow+1 ELSE 1 END AS rn,
      a.Proc,
      a.Procno,
      @prevRow:=Proc grp
    FROM (    
          SELECT
            `incurredcharges`.`procedure_no` procno,
            `c`.`procedure` proc
          FROM
            incurredcharges
            INNER JOIN (
              SELECT `procedure`, `procedure_no` FROM `charges`
              UNION ALL
              SELECT `confinement`, `procedure_no` FROM `confinement`
              UNION ALL
              SELECT `service`, `procedure_no` FROM `ultrasound`
            ) c ON `incurredcharges`.`procedure_no` = c.`procedure_no`
          WHERE `incurredcharges`.`patient_no` = '$id'
          ORDER BY `c`.`procedure`
      ) a 
          JOIN (SELECT @curRow:=0) r
  ) t JOIN
  (
          SELECT
            `incurredcharges`.`procedure_no` procno,
            `c`.`procedure` proc, Count(*) cnt
          FROM
            incurredcharges
            INNER JOIN (
              SELECT `procedure`, `procedure_no` FROM `charges`
              UNION ALL
              SELECT `confinement`, `procedure_no` FROM `confinement`
              UNION ALL
              SELECT `service`, `procedure_no` FROM `ultrasound`
            ) c ON `incurredcharges`.`procedure_no` = c.`procedure_no`
          WHERE `incurredcharges`.`patient_no` = '$id'
          GROUP BY `incurredcharges`.`procedure_no`,
            `c`.`procedure`
  ) c ON t.proc = c.proc
祝你好运。