aa.sql 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. WITH base_call AS (SELECT personName,
  2. personPhone,
  3. COALESCE(otherName, '未知对手') AS otherName,
  4. otherPhone,
  5. DATE_TRUNC('month', callDate) AS call_month
  6. FROM call_record
  7. WHERE personName IN ('王某某')),
  8. monthly_stats AS (SELECT personName, personPhone, otherName, otherPhone, call_month, COUNT(*) AS month_call_count
  9. FROM base_call
  10. GROUP BY personName, personPhone, otherName, otherPhone, call_month),
  11. continuous_group AS (SELECT personName,
  12. personPhone,
  13. otherName,
  14. otherPhone,
  15. month_call_count,
  16. call_month,
  17. DATE_DIFF('month', DATE '2000-01-01', call_month) -
  18. ROW_NUMBER() OVER ( PARTITION BY personName, personPhone, otherName, otherPhone
  19. ORDER BY call_month ) AS cont_group_id
  20. FROM monthly_stats),
  21. qualified_groups AS (SELECT personName,
  22. personPhone,
  23. otherName,
  24. otherPhone,
  25. cont_group_id,
  26. SUM(month_call_count) AS pair_total_calls,
  27. COUNT(*) AS pair_cont_month_count,
  28. MIN(call_month) AS continuous_start_month,
  29. MAX(call_month) AS continuous_end_month
  30. FROM continuous_group
  31. GROUP BY personName, personPhone, otherName, otherPhone, cont_group_id
  32. HAVING COUNT(*) >= 2)
  33. SELECT personName,
  34. otherName,
  35. otherPhone,
  36. SUM(pair_total_calls) AS pairTotalCalls,
  37. SUM(pair_cont_month_count) AS pairContMonthCount
  38. FROM qualified_groups
  39. GROUP BY personName, otherName, otherPhone
  40. LIMIT 20