select_having.sql 1.6 KB

123456789101112131415161718192021222324252627282930313233343536
  1. --
  2. -- SELECT_HAVING
  3. --
  4. -- load test data
  5. CREATE TABLE test_having (a int, b int, c char(8), d char);
  6. INSERT INTO test_having VALUES (0, 1, 'XXXX', 'A');
  7. INSERT INTO test_having VALUES (1, 2, 'AAAA', 'b');
  8. INSERT INTO test_having VALUES (2, 2, 'AAAA', 'c');
  9. INSERT INTO test_having VALUES (3, 3, 'BBBB', 'D');
  10. INSERT INTO test_having VALUES (4, 3, 'BBBB', 'e');
  11. INSERT INTO test_having VALUES (5, 3, 'bbbb', 'F');
  12. INSERT INTO test_having VALUES (6, 4, 'cccc', 'g');
  13. INSERT INTO test_having VALUES (7, 4, 'cccc', 'h');
  14. INSERT INTO test_having VALUES (8, 4, 'CCCC', 'I');
  15. INSERT INTO test_having VALUES (9, 4, 'CCCC', 'j');
  16. SELECT b, c FROM test_having
  17. GROUP BY b, c HAVING count(*) = 1 ORDER BY b, c;
  18. -- HAVING is effectively equivalent to WHERE in this case
  19. SELECT b, c FROM test_having
  20. GROUP BY b, c HAVING b = 3 ORDER BY b, c;
  21. SELECT lower(c), count(c) FROM test_having
  22. GROUP BY lower(c) HAVING count(*) > 2 OR min(a) = max(a)
  23. ORDER BY lower(c);
  24. SELECT c, max(a) FROM test_having
  25. GROUP BY c HAVING count(*) > 2 OR min(a) = max(a)
  26. ORDER BY c;
  27. -- test degenerate cases involving HAVING without GROUP BY
  28. -- Per SQL spec, these should generate 0 or 1 row, even without aggregates
  29. SELECT min(a), max(a) FROM test_having HAVING min(a) = max(a);
  30. SELECT min(a), max(a) FROM test_having HAVING min(a) < max(a);
  31. -- the really degenerate case: need not scan table at all
  32. SELECT 1 AS one FROM test_having HAVING 1 > 2;
  33. SELECT 1 AS one FROM test_having HAVING 1 < 2;
  34. -- and just to prove that we aren't scanning the table:
  35. SELECT 1 AS one FROM test_having WHERE 1/a = 1 HAVING 1 < 2;
  36. DROP TABLE test_having;