Skip to content

Commit 5824ee2

Browse files
KappaDistributiveAndyGauge
authored andcommitted
added data aggregation example for postgres (#520)
1 parent 2ee24f4 commit 5824ee2

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/database.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66
| [Insert and Query data][ex-sqlite-insert-select] | [![rusqlite-badge]][rusqlite] | [![cat-database-badge]][cat-database] |
77
| [Create tables in a Postgres database][ex-postgres-create-tables] | [![postgres-badge]][postgres] | [![cat-database-badge]][cat-database] |
88
| [Insert and Query data][ex-postgres-insert-query-data] | [![postgres-badge]][postgres] | [![cat-database-badge]][cat-database] |
9+
| [Aggregate data][ex-postgres-aggregate-data] | [![postgres-badge]][postgres] | [![cat-database-badge]][cat-database] |
910

1011
[ex-sqlite-initialization]: database/sqlite.html#create-a-sqlite-database
1112
[ex-sqlite-insert-select]: database/sqlite.html#insert-and-select-data
1213
[ex-postgres-create-tables]: database/postgres.html#create-tables-in-a-postgres-database
1314
[ex-postgres-insert-query-data]: database/postgres.html#insert-and-query-data
15+
[ex-postgres-aggregate-data]: database/postgres.html#aggregate-data
1416

1517
{{#include links.md}}

src/database/postgres.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,6 @@
44

55
{{#include postgres/insert_query_data.md}}
66

7+
{{#include postgres/aggregate_data.md}}
8+
79
{{#include ../links.md}}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
## Aggregate data
2+
3+
[![postgres-badge]][postgres] [![cat-database-badge]][cat-database]
4+
5+
This recipe lists the nationalities of the first 7999 artists in the database of the [`Museum of Modern Art`] in descending order.
6+
7+
```rust,no_run
8+
extern crate postgres;
9+
use postgres::{Connection, Error, TlsMode};
10+
11+
struct Nation {
12+
nationality: String,
13+
count: i64,
14+
}
15+
16+
fn main() -> Result<(), Error> {
17+
let conn = Connection::connect(
18+
"postgresql://postgres:[email protected]/moma",
19+
TlsMode::None,
20+
)?;
21+
22+
for row in &conn.query
23+
("SELECT nationality, COUNT(nationality) AS count
24+
FROM artists GROUP BY nationality ORDER BY count DESC", &[])? {
25+
26+
let (nationality, count) : (Option<String>, Option<i64>)
27+
= (row.get (0), row.get (1));
28+
29+
if nationality.is_some () && count.is_some () {
30+
31+
let nation = Nation{
32+
nationality: nationality.unwrap(),
33+
count: count.unwrap(),
34+
};
35+
println!("{} {}", nation.nationality, nation.count);
36+
37+
}
38+
}
39+
40+
Ok(())
41+
}
42+
```
43+
44+
[`Museum of Modern Art`]: https://github.com/MuseumofModernArt/collection/blob/master/Artists.csv

0 commit comments

Comments
 (0)