计算 MySql 中的多列
Count multiple columns in MySql
Table "orc"
P1 p2 p3 p4
__________________________________
w2 w2 w2 w1
w1 w5 w3 w7
Table "artg"
ref design
_________________
w1 product1
w2 product2
w3 product3
w4 product4
w5 product5
w6 product6
w7 product7
我需要把P1、P2、P3、P4一起数。
点赞输出:
Design Total
_________________
Product1 2
Product2 3
使用Union All
将orc
table的所有列合并为一列。然后找到每个设计的数量并加入 artg
table.
查询
select t2.design,count(t1.p) as Total
from
(
select p1 as p from orc
union all
select p2 as p from orc
union all
select p3 as p from orc
union all
select p4 as p from orc
)t1
right join artg t2
on t1.p = t2.ref
group by t2.design;
结果
+----------+-------+
| Design | Total |
+----------+-------+
| product1 | 2 |
| product2 | 3 |
| product3 | 1 |
| product4 | 0 |
| product5 | 1 |
| product6 | 0 |
| product7 | 1 |
+----------+-------+
Table "orc"
P1 p2 p3 p4 __________________________________ w2 w2 w2 w1 w1 w5 w3 w7
Table "artg"
ref design _________________ w1 product1 w2 product2 w3 product3 w4 product4 w5 product5 w6 product6 w7 product7
我需要把P1、P2、P3、P4一起数。
点赞输出:
Design Total _________________ Product1 2 Product2 3
使用Union All
将orc
table的所有列合并为一列。然后找到每个设计的数量并加入 artg
table.
查询
select t2.design,count(t1.p) as Total
from
(
select p1 as p from orc
union all
select p2 as p from orc
union all
select p3 as p from orc
union all
select p4 as p from orc
)t1
right join artg t2
on t1.p = t2.ref
group by t2.design;
结果
+----------+-------+
| Design | Total |
+----------+-------+
| product1 | 2 |
| product2 | 3 |
| product3 | 1 |
| product4 | 0 |
| product5 | 1 |
| product6 | 0 |
| product7 | 1 |
+----------+-------+