-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetdatasettoptaxa.sql
More file actions
38 lines (36 loc) · 1.24 KB
/
getdatasettoptaxa.sql
File metadata and controls
38 lines (36 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
CREATE OR REPLACE FUNCTION ti.getdatasettoptaxa(
_datasetid int,
_topx int,
_grouptaxa CHARACTER VARYING DEFAULT NULL,
_alwaysshowtaxa CHARACTER VARYING DEFAULT NULL)
RETURNS TABLE (id integer,
taxonname character varying,
ecologicalgroupid CHAR(4))
LANGUAGE sql
AS
$function$
WITH wholesum AS (
SELECT tx.taxonid,
tx.taxonname,
ec.ecolgroupid,
row_number() OVER (ORDER BY SUM(dt.value) DESC) AS index
FROM ndb.samples AS sm
INNER JOIN ndb.data AS dt ON sm.sampleid = dt.sampleid
INNER JOIN ndb.variables AS var ON dt.variableid = var.variableid
INNER JOIN ndb.taxa AS tx ON var.taxonid = tx.taxonid
INNER JOIN ndb.ecolgroups AS ec ON tx.taxonid = ec.taxonid
WHERE var.variableelementid = ANY('{141,166}')
AND sm.datasetid = _datasetid
GROUP BY ec.ecolsetid,
ec.ecolgroupid,
tx.taxonname,
tx.taxonid,
var.variableunitsid
ORDER BY SUM(dt.value) DESC)
SELECT taxonid AS id,
taxonname AS taxon,
ecolgroupid AS ecologicalgroupid
FROM wholesum
WHERE index <= _topx
OR taxonname = ANY(SELECT unnest(string_to_array(_datasettypeidlist,',')))
$function$