我试图在mySQL DB中进行查询
我有
Field 1 | Field 2 | url v1 | Value01 | http:1 v1 | Value02 | http:2 v2 | Value02 | http:3 v3 | Value01 | http:4 v3 | Value02 | http:5 v2 | Value02 | http:6
我尝试在重复时计算字段2中的值 所有按字段1分组
我期待这个
Field 1 | count Value01(from Field 2)|count Value02(from Field 2) v1 | 1 | 1 v2 | 0 | 2 v3 | 1 | 1
有没有办法做这样的事情?
答案 0 :(得分:0)
您使用条件COUNT
或SUM
ELSE NULL
因为CASE
的默认回复,但我将其包含在内以便清楚阅读。
SELECT
Field1,
COUNT( CASE
WHEN Field2 = 'Value01' THEN 1
ELSE NULL
END) as count_Value01,
SUM ( CASE
WHEN Field2 = 'Value02' THEN 1
ELSE 0
END) as count_Value02
FROM yourTable
GROUP BY Field1
答案 1 :(得分:0)
您可以使用条件聚合来完成此操作。这在MySQL中特别简单:
select field1, sum(field2 = 'Value1') as NumValue01,
sum(field2 = 'Value02') as NumValue2
from table t
group by field1;