# Metrics - Queries SQL (Fallback)

Queries para usar quando tools MCP nao estao disponiveis.

## Top 10 Skills

```sql
SELECT
  name,
  COUNT(*) as uses,
  AVG(duration_ms)/60000 as avg_min,
  (SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*) * 100) as error_rate
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
  AND type = 'skill'
GROUP BY name
ORDER BY uses DESC
LIMIT 10;
```

## ROI por Projecto

```sql
WITH skill_savings AS (
  SELECT
    m.project_id,
    m.name,
    COUNT(*) as uses,
    (b.baseline_duration_ms - AVG(m.duration_ms))/60000 as saved_per_use_min
  FROM tblskill_agent_metrics m
  JOIN tblskill_agent_baselines b ON b.name = m.name
  WHERE m.status = 'success'
  GROUP BY m.project_id, m.name
)
SELECT
  p.name as project,
  c.company as client,
  s.name as skill,
  s.uses,
  ROUND(s.uses * s.saved_per_use_min/60, 1) as hours_saved,
  ROUND((s.uses * s.saved_per_use_min/60) * 50, 2) as value_eur
FROM skill_savings s
JOIN tblprojects p ON p.id = s.project_id
JOIN tblclients c ON c.userid = p.clientid
WHERE s.saved_per_use_min > 0
ORDER BY hours_saved DESC;
```

## Trending Semanal

```sql
SELECT
  name,
  DATE_FORMAT(created_at, '%Y-W%u') as week,
  COUNT(*) as executions,
  AVG(duration_ms) as avg_ms
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY name, week
ORDER BY name, week DESC;
```

## Query Basica via MCP

```sql
SELECT
  name,
  type,
  COUNT(*) as executions,
  AVG(duration_ms) as avg_ms,
  (SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*) * 100) as error_rate
FROM tblskill_agent_metrics
WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY name, type
ORDER BY executions DESC
LIMIT 10;
```
