我在查询特定输出时遇到了一些问题。
我的表格如下:
ID | meta_value | field_id | item_id
------------------------------------
1 | Steve | 75 | 5
2 | Johnsson | 76 | 5
3 | Sick | 705 | 5
4 | John | 75 | 6
5 | Doe | 76 | 6
6 | Sick | 705 | 6
7 | Laura | 75 | 7
8 | Jenner | 76 | 7
9 | Sick | 705 | 7
10 | Laura | 75 | 8
11 | Jenner | 76 | 8
12 | Vacation | 705 | 8
13 | Steve | 75 | 9
14 | Johnsson | 76 | 9
15 | Sick | 705 | 9
我想合并 - 按item_id分组及其组合的meta_value - 并计算结果,其中值为“Sick” - 按计数排序,如下所示:
Name: Sick (Count):
Steve Johnsson 2
John Doe 1
Laura Jenner 1
(假期被遗漏)
我想我已经尝试了所有可能的组合,但显然似乎没有什么是正确的。 (不能选择更改表格)。我已经尝试了好几个小时......
请帮助:)
提前致谢!
答案 0 :(得分:1)
尝试两个级别的聚合:
select first_name, last_name, count(*)
from (select max(case when field_id = 75 then meta_value end) as first_name,
max(case when field_id = 76 then meta_value end) as last_name,
max(case when field_id = 705 then meta_value end) as reason
from t
group by item_id
) t
where reason = 'sick'
group by first_name, last_name
order by count(*) desc;
答案 1 :(得分:0)
键值表很难看,但通常它们至少有一个分组列。你的没有。您必须首先通过查找名称找出哪个item_ids代表同一用户。 (并希望表中没有两个不同的约翰史密斯。)
您首先按user_id聚合,然后按名称再次聚合:
select
name,
sum(item_sick_count) as sick_count
from
(
select
concat(
any_value(case when field_id = 75 then meta_value),
' ',
any_value(case when field_id = 76 then meta_value)
) as name,
sum(field_id = 705 and meta_value = 'Sick') as item_sick_count
from mytable
group by item_id
)
group by name
order by sick_count desc, name;
sick_count
公式使用MySQL' s = 1,false = 0。
答案 2 :(得分:0)
为每个字段加入表格一次:
select
f.meta_value as first_name,
l.meta_value as last_name,
count(*) as sick_count
from eav s
join eav f using(item_id)
join eav l using(item_id)
where s.field_id = 705
and s.meta_value = 'Sick'
and f.field_id = 75
and l.field_id = 76
group by first_name, last_name
order by sick_count desc