Skip to content

Instantly share code, notes, and snippets.

@blzzua
Created August 10, 2023 13:16
Show Gist options
  • Save blzzua/788ec54f68935d0d3ad1597d3f52d3c1 to your computer and use it in GitHub Desktop.
Save blzzua/788ec54f68935d0d3ad1597d3f52d3c1 to your computer and use it in GitHub Desktop.
Diversity index MS SQL
WITH SpeciesCounts AS (
SELECT
SpecieType,
COUNT(*) AS CountPerSpecies
FROM
Table
GROUP BY
SpecieType
),
TotalCount AS (
SELECT
SUM(CountPerSpecies) as TotalRowCount,
COUNT(CountPerSpecies) AS TotalSpeciesCount
FROM
SpeciesCounts
)
SELECT
(SELECT SUM(CountPerSpecies) FROM SpeciesCounts) AS TotalRowCount,
(SELECT COUNT(DISTINCT SpecieType) FROM SpeciesCounts) AS DifferentSpeciesCount,
(SELECT MAX(CountPerSpecies) FROM SpeciesCounts) AS MaxCountPerSpecies,
-SUM((CountPerSpecies * 1.0 / TotalSpeciesCount) * LOG(CountPerSpecies * 1.0 / TotalSpeciesCount)) AS ShannonIndex
FROM
SpeciesCounts
CROSS JOIN
TotalCount;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment