简体   繁体   English

将 group_concat 与条件一起使用:如果值不相等则显示 0

[英]Using group_concat With a Condition: Display 0 if Values are Not Equal

I just want to display column fields horizontally but also putting a condition to it.我只想水平显示列字段,但也要为其设置条件。 Display zero if it has not met the condition.如果不满足条件则显示零。

Example problem: Find the PAYCODE 912 and 686 and display the amount, if not available, display 0示例问题:找到PAYCODE 912和686并显示金额,如果不可用,显示0

my_table我的表

EMPLOYEE员工 PAYCODE支付码 AMOUNT数量
1 1 912 912 1 1
1 1 123 123 3 3
2 2 912 912 5 5
2 2 686 686 7 7
3 3 111 111 4 4

Output must be: Output 必须是:

EMPLOYEE员工 AMOUNT数量
1 1 1,0 1,0
2 2 5,7 5,7
3 3 0,0 0,0

My code so far:到目前为止我的代码:

SELECT 
    EMPLOYEE,
    GROUP_CONCAT(DISTINCT CONCAT(
          IF(PAYCODE = '912', AMOUNT, '0'), 
          IF(PAYCODE = '686', AMOUNT, '0')) 
          SEPARATOR',') as AMOUNT
FROM 
    my_table

Note: There are no duplicate paycodes on a similar employee.注意:类似员工没有重复的工资代码。 eg two 912 paycodes例如两个 912 支付码

I'm thinking a cross join approach should work here:我认为交叉连接方法应该在这里工作:

SELECT e.EMPLOYEE,
       GROUP_CONCAT(COALESCE(t.AMOUNT, 0) ORDER BY e.PAYMENTTYPE DESC) AS AMOUNT
FROM (SELECT DISTINCT EMPLOYEE FROM my_table) e
CROSS JOIN (SELECT '912' AS PAYMENTTYPE UNION ALL SELECT '686') p
LEFT JOIN my_table t
    ON t.EMPLOYEE = e.EMPLOYEE AND
       t.PAYMENTTYPE = p.PAYMENTTYPE
GROUP BY e.EMPLOYEE;

The cross join between the e and p subqueries generates all employee/payment type combinations of interest (only types 912 and 686). ep子查询之间的交叉连接生成所有员工/付款类型的利息组合(仅类型 912 和 686)。 We then left join to your table to bring in the amounts, which if are missing we report 0 instead.然后,我们将 join 留在您的表中以输入金额,如果缺少,我们将改为报告 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM