Đang chuẩn bị liên kết để tải về tài liệu:
Joe Celko s SQL for Smarties - Advanced SQL Programming P60
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Joe Celko s SQL for Smarties - Advanced SQL Programming P60. In the SQL database community, Joe Celko is a well-known columnist and purveyor of valuable insights. In Joe Celko's SQL for Smarties: Advanced SQL Programming, he picks up where basic SQL training and experience leaves many database professionals and offers tips, techniques, and explanations that help readers extend their capabilities to top-tier SQL programming. Although Celko denies that the book is about database theory, he nevertheless alludes to theory often to buttress his practical points. This title is not for novices, as the author points out. Instead, its intended. | 562 CHAPTER 24 REGIONS RUNS GAPS SEQUENCES AND SERIES or SELECT MIN F1.seq_nbr 1 FROM List AS F1 UNION ALL VALUE 0 WHERE L1.seq_nbr 1 NOT IN SELECT seq_nbr FROM List Finding entire gaps follows from this pattern and we get this short piece of code. SELECT s 1 AS gap_start e - 1 AS gap_end FROM SELECT L1.seq_nbr MIN L2.seq_nbr FROM List AS L1 List AS L2 WHERE L1.seq_nbr L2.seq_nbr GROUP BY L1.seq_nbr AS G s e WHERE e - 1 s Without the derived table we get SELECT L1.seq_nbr 1 AS gap_start MIN L2.seq_nbr - 1 AS gap_end FROM List AS L1 List AS L2 WHERE L1.seq_nbr L2.seq_nbr GROUP BY L1.seq_nbr HAVING MIN L2.seq_nbr - L1.seq_nbr 1 24.6 Summation of a Series While this topic is a bit more mathematical than most SQL programmers actually have to use in their work it does demonstrate the power of SQL and a little knowledge of some basic college math. The summation of a series builds a running total of the values in a table and shows the cumulative total for each value in the series. Let s create a table and some sample data. CREATE TABLE Series seq_nbr INTEGER NOT NULL PRIMARY KEY 24.6 Summation of a Series 563 val INTEGER NOT NULL answer INTEGER null means not computed yet Sequences seq_nbr val answer 1 6 6 2 41 47 3 12 59 4 51 110 5 21 131 6 70 201 7 79 280 8 62 342 This simple summation is not a problem. UPDATE Series SET answer SELECT SUM Rl.val FROM Series AS S1 WHERE R1.seq_nbr Series.seq_nbr WHERE answer IS NULL This is the form we can use for most problems of this type with only one level of summation. But things can be worse. This problem came from Francisco Moreno and on the surface it sounds easy. First create the usual table and populate it. DROP TABLE Series CREATE TABLE Series seq_nbr INTEGER NOT NULL val REAL NOT NULL answer REAL INSERT INTO Series VALUES 0 6.0 NULL 1 6.0 NULL 2 10.0 NULL 3 12.0 NULL 4 14.0 NULL 564 CHAPTER 24 REGIONS RUNS GAPS SEQUENCES AND SERIES The goal is to compute the average of the first two terms then add the third value to the .