Created
August 10, 2023 13:16
-
-
Save blzzua/788ec54f68935d0d3ad1597d3f52d3c1 to your computer and use it in GitHub Desktop.
Diversity index MS SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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