Database View Intelligence Catalog
May 24, 2026 Β· View on GitHub
Comprehensive Guide to CIA Platform Database Views
Document Type: Catalog (Living Document)
Status: Active - Continuously Updated
Last Updated: 2025-12-11
Version: 1.0
Purpose: Single source of truth for database view definitions, usage patterns, and analytical applications
Classification: Public Documentation
External References: Yes - Referenced in hack23.com blog posts and technical documentation
Maintained By: Citizen Intelligence Agency Intelligence Operations Team
π Table of Contents
- Executive Summary
- View Categories Overview
- Complete View Inventory
- Politician Views
- Party Views
- Committee Views
- Ministry/Government Views
- Vote Data Views
- Document Views
- Intelligence Views
- Application & Audit Views
- Common Usage Patterns
- View Dependency Diagram
- Performance Optimization Guide
- Cross-Reference to Intelligence Frameworks
- Appendices
Executive Summary
The Citizen Intelligence Agency (CIA) platform employs 110 database views (77 regular views + 33 materialized views) across 12 major categories to support comprehensive political intelligence analysis, open-source intelligence (OSINT) collection, and democratic accountability monitoring.
β Documentation Status: This catalog now provides comprehensive documentation for all 110 database views (100% coverage), including 5 new-style materialized views (mv_*, v1.76), 4 recreated party analysis views (v1.61), 6 election cycle views (v1.51), 3 party transition tracking views (v1.57), 3 politician career trajectory views (v1.56), 7 seasonal/election year analysis views (v1.55/v1.59/v1.60), and 1 politician career path view (v1.58) that provide META/META-level historical analysis with Swedish parliamentary election context. 15 views have detailed examples with complex queries, while 95 views have structured documentation with purpose, key metrics, sample queries, and intelligence applications.
Last Updated: 2026-04-05 (Full audit: corrected view count from 96 to 110 β 77 regular + 33 materialized β verified against full_schema.sql)
Last Validated: 2026-04-05 (v1.80 with 110 views)
Validation Method: Automated schema validation via validate-view-documentation.sh
Schema Source: service.data.impl/src/main/resources/full_schema.sql + db-changelog-1.80.xml
Documentation Coverage: 100% (110/110 views)
Validation Details: See Validation History section below
Note: Total view count updated from 96 to 110 after full audit against full_schema.sql (v1.80). Added 5 new-style materialized views (mv_*), 4 career/trajectory politician views, 7 seasonal/election year views, and 1 decision temporal trends view that were previously undercounted. Four views (party_summary, party_longitudinal_performance, party_coalition_evolution, party_electoral_trends) were recreated in v1.61 after being dropped in v1.53/v1.6 but never recreated, causing JPA entity mismatch.
Key Statistics (UPDATED 2026-04-05)
| Metric | Count | Description |
|---|---|---|
| Total Views | 110 | β UPDATED v1.80: 77 regular + 33 materialized (verified against full_schema.sql) |
| Regular Views | 77 | β UPDATED: 77 regular views (CREATE VIEW / CREATE OR REPLACE VIEW) |
| Materialized Views | 33 | β UPDATED: 28 legacy view_* materialized + 5 new mv_* materialized |
| Views Documented (Detailed) | 15 | β Views with comprehensive examples and performance characteristics |
| Views Documented (Structured) | 95 | Purpose, metrics, queries, product mappings |
| Documentation Coverage | 100% | All 110 views documented |
| Intelligence Views | 8 | Advanced analytical views (risk, anomaly, influence, crisis, momentum, dashboard, temporal trends) |
| Election Cycle Views | 6 | v1.51: META/META-level election cycle analysis across 6 frameworks |
| Party Analysis Views (v1.61) | 4 | Recreated views with 59-70 columns, advanced window functions, forecasting |
| Career Trajectory Views | 4 | v1.56/v1.58: Politician career pattern detection, role evolution, longevity analysis, career path |
| Party Transition Views | 3 | v1.57: Party switcher tracking with defection analysis and career outcomes |
| Seasonal/Election Year Views | 7 | v1.55/v1.59/v1.60: Temporal pattern analysis with seasonal decomposition and election year comparison |
| Decision Flow Views | 4 | Party, politician, ministry, temporal trends for decision analysis |
| New-Style Materialized Views | 5 | v1.76: mv_* prefix views for annual metrics, decision trends, ministry impact, party flow |
| Vote Data Views | 16 | Daily, weekly, monthly, annual ballot and voting data summaries (ballot, party, politician) |
| Application Event Views | 12 | User behavior tracking (daily, weekly, monthly, annual) |
| Document Views | 9 | Politician and party document productivity |
| Committee Views | 12 | Committee productivity, decisions, membership |
| Government/Ministry Views | 9 | Government and ministry performance tracking (includes mv_ministry_decision_impact) |
| Party Views | 19 | Party performance, decision flow, effectiveness, transitions, longitudinal analysis |
| Politician Views | 12 | Politician performance, experience, career trajectory, behavioral trends |
| Application/Audit Views | 14 | Platform usage tracking and audit trails |
| Database Size | 20 GB | Total database size (validated 2025-11-21) |
| Total Rows | 5.6M | Total rows across all tables |
| Base Tables | 93 | Core data tables |
| Indexes | 178 | Database indexes (68 missing on FK columns) |
Intelligence Value Classification
Views are classified by intelligence value for analytical operations:
- βββββ VERY HIGH: Critical intelligence products, coalition analysis, risk assessment
- ββββ HIGH: Core analytical capabilities, performance tracking, trend analysis
- βββ MEDIUM: Supporting analytics, data aggregation, reporting
- ββ LOW: Basic data access, administrative views, audit tracking
Primary Use Cases
- Political Scorecards: Individual politician performance metrics (attendance, effectiveness, productivity)
- Coalition Analysis: Party alignment matrices, government formation forecasting
- Risk Assessment: Behavioral anomaly detection, defection risk, democratic accountability
- Trend Analysis: Temporal pattern recognition, momentum tracking, predictive analytics
- Network Analysis: Influence mapping, power structure visualization, broker identification
- Document Intelligence: Legislative productivity, policy focus analysis
- Performance Monitoring: Committee effectiveness, ministry performance, party strength
Related Documentation
| Document | Link | Description |
|---|---|---|
| Business Product Document | BUSINESS_PRODUCT_DOCUMENT.md | Commercial product strategy and market analysis |
| JSON Export Specifications | json-export-specs/ | API schemas and data format specifications |
| Intelligence Data Flow Map | INTELLIGENCE_DATA_FLOW.md | Central cross-reference hub showing data pipeline |
| Intelligence Evolution Changelog | CHANGELOG_INTELLIGENCE.md | Unified intelligence capability tracking |
| Sample Data Directory | service.data.impl/sample-data/ | Actual sample CSV files for all 110 views and 54 tables |
| Intelligence Frameworks | DATA_ANALYSIS_INTOP_OSINT.md | Analysis methodologies and OSINT techniques |
| Risk Rules | RISK_RULES_INTOP_OSINT.md | 45 behavioral detection rules |
| Changelog Analysis | LIQUIBASE_CHANGELOG_INTELLIGENCE_ANALYSIS.md | Schema evolution analysis |
| Data Model | DATA_MODEL.md | Database schema and relationships |
| Schema Maintenance | service.data.impl/README-SCHEMA-MAINTENANCE.md | Database maintenance guide |
Sample Data Note: All example queries in this catalog have been verified against current sample data (verified 2026-01-01). View samples are located in service.data.impl/sample-data/view_*_sample.csv. Important data notes:
- Gender values are in Swedish:
'KVINNA'(woman) and'MAN'(man) - Status values are in Swedish:
'TjΓ€nstgΓΆrande riksdagsledamot'(active MP),'Tidigare riksdagsledamot'(former MP) - Some views may be empty due to data quality issues (see sample-data/README.md)
π Validation History
Current Status
Last Validated: 2026-04-05
Validation Method: Automated schema validation via validate-view-documentation.sh
Schema Source: service.data.impl/src/main/resources/full_schema.sql + db-changelog-1.80.xml
Coverage: 100% (110/110 views documented)
Health Score: 82/100 (per schema-health-check.sql)
Validation Methodology
The validation process ensures documentation accuracy through automated comparison:
-
Extract Schema Views: Parse full_schema.sql for CREATE VIEW statements
grep -E "^CREATE (OR REPLACE )?(MATERIALIZED )?VIEW" full_schema.sql | \ sed 's/.*VIEW //' | sed 's/ AS.*//' | sed 's/public\.//' | sort | uniq -
Extract Documented Views: Parse DATABASE_VIEW_INTELLIGENCE_CATALOG.md for view headers
grep -E "^### view_" DATABASE_VIEW_INTELLIGENCE_CATALOG.md | \ sed 's/### //' | awk '{print \$1}' | sort | uniq -
Compare Sets: Identify missing and extra views using set operations
comm -23 schema_views.txt documented_views.txt > missing_views.txt comm -13 schema_views.txt documented_views.txt > extra_views.txt -
Calculate Coverage: Compute percentage of documented views
COVERAGE=$((100 * DOCUMENTED / TOTAL)) -
Generate Report: Create validation report with findings and recommendations
Validation Schedule
- Automated: Monthly via GitHub Actions (1st of each month at 02:00 UTC)
- Manual: Can be triggered via workflow_dispatch
- On Changes: Recommended after schema or documentation modifications
Validation Procedure
To validate documentation coverage manually:
-
Run health check:
cd service.data.impl/src/main/resources/ psql -U postgres -d cia_dev -f schema-health-check.sql > health_report.txt 2>&1 grep "HEALTH SCORE" health_report.txt # Should be >80/100 -
Validate view documentation coverage:
./validate-view-documentation.sh # Reviews full_schema.sql vs DATABASE_VIEW_INTELLIGENCE_CATALOG.md -
Review findings: Check for missing or extra documented views
-
Update documentation: Add missing views or remove obsolete ones
-
Re-run validation: Confirm fixes achieve 100% coverage
Historical Validations
| Date | Coverage | Total Views | Missing | Status | Key Changes |
|---|---|---|---|---|---|
| 2025-11-20 | 10.98% | 82 | 73 | β οΈ Initial | Identified major documentation gap |
| 2025-11-21 | 100% | 82 | 0 | β Complete | Added all 73 missing views |
| 2025-11-25 | 100% | 84 | 0 | β Updated | Corrected count, validated integrity |
| 2026-04-05 | 100% | 110 | 0 | β Current | Full audit: 77 regular + 33 materialized views verified against full_schema.sql |
Coverage Progression
The documentation achieved 100% coverage through systematic validation and remediation:
- 2025-11-20: Initial validation revealed 10.98% coverage (9/82 views)
- 2025-11-21: Complete documentation added for 73 missing views
- 2025-11-25: Reverified counts (82β84 views), maintained 100% coverage
Health Metrics
Based on schema-health-check.sql (last run: 2025-11-25):
| Metric | Score | Status | Notes |
|---|---|---|---|
| Overall Health | 82/100 | β Good | Above 80/100 threshold |
| Schema Integrity | 90/100 | β Excellent | All views valid |
| Data Quality | 80/100 | β Good | Meets standards |
| Performance | 75/100 | β οΈ Acceptable | Some optimization opportunities |
| Security | 85/100 | β Good | No critical issues |
Validation Tools
- validate-view-documentation.sh: Automated validation script
- schema-health-check.sql: Database health assessment (see README-SCHEMA-MAINTENANCE.md)
- schema-validation-v2.sql: Schema coverage validation
- GitHub Actions: Automated monthly validation workflow
π Quick Reference: Finding Views for Your Analysis
| I Want To... | Navigate To |
|---|---|
| See which views support temporal analysis | Temporal Analysis Views |
| See which views support comparative analysis | Comparative Analysis Views |
| See which views support pattern recognition | Pattern Recognition Views |
| See which views support predictive intelligence | Predictive Intelligence Views |
| See which views support network analysis | Network Analysis Views |
| See complete data flow pipeline | Intelligence Data Flow Map |
| Understand how risk rules use views | Risk Rule β View Mapping |
| Browse politician views | Politician Views |
| Browse party views | Party Views |
| Browse committee views | Committee Views |
| Browse vote data views | Vote Data Views |
View Categories Overview
Category Structure
graph TB
subgraph "Data Collection Layer"
A1[Source Tables] --> B[Base Views]
end
subgraph "Aggregation Layer"
B --> C1[Vote Data Views<br/>20+ views]
B --> C2[Document Views<br/>10+ views]
B --> C3[Committee Views<br/>10+ views]
B --> C4[Ministry Views<br/>6+ views]
end
subgraph "Intelligence Analysis Layer"
C1 & C2 & C3 & C4 --> D1[Politician Views<br/>15+ views]
C1 & C2 & C3 & C4 --> D2[Party Views<br/>12+ views]
D1 & D2 --> E[Intelligence Views<br/>v1.29-v1.30]
end
subgraph "Application Layer"
E --> F1["Audit & Tracking<br/>5+ views"]
E --> F2[User Analytics<br/>4+ views]
end
style E fill:#ffeb99,stroke:#333,stroke-width:3px
style D1 fill:#e1f5ff,stroke:#333,stroke-width:2px
style D2 fill:#cce5ff,stroke:#333,stroke-width:2px
style C1 fill:#d1f2eb,stroke:#333,stroke-width:2px
style F1 fill:#fdecea,stroke:#333,stroke-width:2px
Views by Category
| Category | Count | Primary Purpose | Intelligence Value |
|---|---|---|---|
| Politician Views | 12 | Individual performance, experience, behavior, career trajectory | βββββ VERY HIGH |
| Party Views | 19 | Organizational effectiveness, coalition analysis, transitions | βββββ VERY HIGH |
| Committee Views | 12 | Legislative body productivity, decision tracking | ββββ HIGH |
| Ministry Views | 9 | Government executive performance monitoring | ββββ HIGH |
| Vote Data Views | 15+ | Ballot summaries (daily/weekly/monthly/annual) | ββββ HIGH |
| Document Views | 7+ | Legislative productivity, document tracking | βββ MEDIUM |
| Intelligence Views | 7+ | Advanced analytics, risk assessment, trends | βββββ VERY HIGH |
| Election Cycle Views | 6 | META-level election cycle analysis | βββββ VERY HIGH |
| Seasonal/Election Year Views | 7 | Temporal patterns, election proximity trends | ββββ HIGH |
| Application Views | 14 | Audit trails, user activity, session tracking | ββ LOW |
| New-Style Materialized Views | 5 | Pre-aggregated metrics for performance | ββββ HIGH |
| WorldBank Views | 1 | Economic indicator data | βββ MEDIUM |
View Evolution Timeline
| Version | Date | Key Views Introduced | Intelligence Impact |
|---|---|---|---|
| v1.0-v1.1 | 2014-11 | Base politician, party, committee views | Foundation |
| v1.2-v1.3 | 2015 | Vote summary views (daily/weekly/monthly/annual) | Temporal analysis enabled |
| v1.23-v1.24 | 2023 | Party coalition views, document summaries | Coalition analysis |
| v1.25-v1.26 | 2024 | Committee decision views, materialized views | Performance optimization |
| v1.27-v1.28 | 2024 | Politician experience scoring | Expertise tracking |
| v1.29 | 2024-11 | Intelligence dashboard, coalition alignment, anomaly detection | Advanced intelligence |
| v1.30 | 2024-11 | Behavioral trends, risk evolution, effectiveness trends | Predictive analytics |
Complete View Inventory
This section provides a complete alphabetical inventory of all 110 database views with brief descriptions. All views are now documented in this catalog with structured information including purpose, key metrics, sample queries, and intelligence applications.
Legend:
- π = Detailed documentation (comprehensive examples, performance characteristics)
- π = Structured documentation (purpose, metrics, queries, applications)
- βββββ = VERY HIGH intelligence value
- ββββ = HIGH intelligence value
- βββ = MEDIUM intelligence value
- ββ = LOW intelligence value (administrative/audit)
- π = Materialized view (requires refresh)
Application & Audit Views (14 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_application_action_event_page_annual_summary | Standard | ββ | Annual summary of user interactions by page |
| view_application_action_event_page_daily_summary | Standard | ββ | Daily summary of user interactions by page |
| view_application_action_event_page_element_annual_summary | Standard | ββ | Annual summary of UI element interactions |
| view_application_action_event_page_element_daily_summary | Standard | ββ | Daily summary of UI element interactions |
| view_application_action_event_page_element_hourly_summary | Standard | ββ | Hourly summary of UI element interactions |
| view_application_action_event_page_element_weekly_summary | Standard | ββ | Weekly summary of UI element interactions |
| view_application_action_event_page_hourly_summary | Standard | ββ | Hourly summary of user interactions by page |
| view_application_action_event_page_modes_annual_summary | Standard | ββ | Annual summary of page access modes |
| view_application_action_event_page_modes_daily_summary | Standard | ββ | Daily summary of page access modes |
| view_application_action_event_page_modes_hourly_summary | Standard | ββ | Hourly summary of page access modes |
| view_application_action_event_page_modes_weekly_summary | Standard | ββ | Weekly summary of page access modes |
| view_application_action_event_page_weekly_summary | Standard | ββ | Weekly summary of user interactions by page |
| view_audit_author_summary | Standard | ββ | Summary of data changes by author |
| view_audit_data_summary | Standard | ββ | Summary of audit trail data changes |
Committee Views (12 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_committee_productivity | Standard | ββββ | Committee productivity metrics and efficiency indicators |
| view_committee_productivity_matrix | Standard | ββββ | Matrix comparison of committee productivity |
| view_riksdagen_committee | Standard | ββββ | Committee structure, membership, and activity metrics |
| view_riksdagen_committee_ballot_decision_party_summary | π Materialized | ββββ | Party-level committee ballot decisions |
| view_riksdagen_committee_ballot_decision_politician_summary | π Materialized | ββββ | Individual politician committee ballot decisions |
| view_riksdagen_committee_ballot_decision_summary | π Materialized | ββββ | Aggregated committee ballot decision summary |
| view_riksdagen_committee_decision_type_org_summary | π Materialized | βββ | Committee decisions by type and organization |
| view_riksdagen_committee_decision_type_summary | π Materialized | βββ | Committee decisions aggregated by type |
| view_riksdagen_committee_decisions | π Materialized | ββββ | Detailed committee decision tracking |
| view_riksdagen_committee_parliament_member_proposal | Standard | βββ | Parliamentary member proposals to committees |
| view_riksdagen_committee_role_member | Standard | βββ | Committee role assignments and members |
| view_riksdagen_committee_roles | Standard | βββ | Committee role definitions and structure |
Document Views (9 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_document_data_committee_report_url | Standard | βββ | URLs for committee reports and documents |
| view_riksdagen_document_type_daily_summary | π Materialized | βββ | Daily summary of documents by type |
| view_riksdagen_org_document_daily_summary | π Materialized | βββ | Daily summary of documents by organization |
| view_riksdagen_party_document_daily_summary | π Materialized | ββββ | Daily party document productivity |
| view_riksdagen_party_document_summary | Standard | ββββ | Aggregated party document statistics |
| view_riksdagen_politician_document_daily_summary | π Materialized | ββββ | Daily politician document productivity |
| view_riksdagen_politician_document_summary | π Materialized | ββββ | Aggregated politician document statistics |
| view_riksdagen_member_proposals | Standard | βββ | Parliamentary member legislative proposals |
| mv_annual_document_metrics | π Materialized | ββββ | Pre-aggregated annual document metrics (v1.76) |
Government/Ministry Views (9 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_ministry_effectiveness_trends | Standard | βββββ | Ministry performance trends over time |
| view_ministry_productivity_matrix | Standard | βββββ | Comparative ministry productivity analysis |
| view_ministry_risk_evolution | Standard | βββββ | Evolution of ministry risk indicators |
| view_ministry_decision_impact | Standard | βββββ | Ministry proposal success rates and effectiveness (v1.35) |
| mv_ministry_decision_impact | π Materialized | βββββ | Materialized ministry decision impact for performance (v1.76) |
| view_riksdagen_goverment | Standard | ββββ | Government structure and composition |
| view_riksdagen_goverment_proposals | Standard | ββββ | Government legislative proposals |
| view_riksdagen_goverment_role_member | Standard | ββββ | Government role assignments |
| view_riksdagen_goverment_roles | Standard | ββββ | Government role definitions |
Intelligence & Risk Views (8 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_decision_temporal_trends | Standard | βββββ | Decision temporal trends and pattern analysis |
| mv_decision_temporal_trends | π Materialized | βββββ | Materialized decision temporal trends for performance (v1.76) |
| π view_party_effectiveness_trends | Standard | βββββ | Party effectiveness metrics over time |
| π view_politician_behavioral_trends | Standard | βββββ | Politician behavioral pattern analysis |
| view_politician_risk_summary | Standard | βββββ | Aggregated politician risk indicators |
| view_riksdagen_crisis_resilience_indicators | Standard | βββββ | Crisis period performance and resilience metrics |
| view_riksdagen_intelligence_dashboard | Standard | βββββ | Unified intelligence dashboard with key metrics |
| π view_riksdagen_voting_anomaly_detection | Standard | βββββ | Voting anomaly and defection risk detection |
| π view_risk_score_evolution | Standard | βββββ | Evolution of risk scores over time |
Party Views (19 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| π view_riksdagen_coalition_alignment_matrix | Standard | βββββ | Party coalition alignment and probability matrix |
| π view_riksdagen_party | Standard | βββββ | Core party information and metrics |
| view_party_performance_metrics | Standard | βββββ | Comprehensive party performance indicators |
| view_riksdagen_party_summary | Standard | ββββ | π Party assignment & document aggregation (v1.61 recreated) |
| view_riksdagen_party_ballot_support_annual_summary | Standard | ββββ | Annual party ballot support patterns |
| view_riksdagen_party_coalation_against_annual_summary | Standard | ββββ | Annual party opposition coalition patterns |
| π view_riksdagen_party_decision_flow | Standard | βββββ | Party-level proposal decision analysis (v1.35) |
| mv_party_decision_flow | π Materialized | βββββ | Materialized party decision flow for performance (v1.76) |
| view_riksdagen_party_longitudinal_performance | Standard | βββββ | π Semester performance trackingβ70 KPIs (v1.61 recreated) |
| view_riksdagen_party_coalition_evolution | Standard | βββββ | π Party-pair alliance trackingβ35 metrics (v1.61 recreated) |
| view_riksdagen_party_electoral_trends | Standard | βββββ | π Electoral performanceβ49 indicators (v1.61 recreated) |
| view_riksdagen_party_member | Standard | ββββ | Party membership roster |
| view_riksdagen_party_momentum_analysis | Standard | βββββ | Party momentum and trend analysis |
| view_riksdagen_party_role_member | Standard | βββ | Party role assignments |
| view_riksdagen_party_signatures_document_summary | Standard | βββ | Party document signature patterns |
| view_riksdagen_party_transition_history | Standard | βββββ | Party switcher tracking with historical transitions (v1.55) |
| view_riksdagen_party_defector_analysis | Standard | βββββ | Defector behavioral analysis and early warning signals (v1.55) |
| view_riksdagen_party_switcher_outcomes | Standard | βββββ | Post-transition career success metrics (v1.55) |
| view_riksdagen_person_signed_document_summary | Standard | βββ | Individual document signature summary |
Politician Views (12 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| π view_riksdagen_politician | Standard | βββββ | Core politician information and demographics |
| π view_riksdagen_politician_document | π Materialized | βββββ | Politician document authorship and productivity |
| π view_riksdagen_politician_experience_summary | Standard | βββββ | Politician experience scoring and classification |
| view_riksdagen_politician_ballot_summary | Standard | βββββ | Politician voting record summary |
| view_riksdagen_politician_influence_metrics | Standard | βββββ | Politician influence and network analysis |
| π view_riksdagen_politician_decision_pattern | Standard | βββββ | Politician decision effectiveness and committee specialization (v1.35) |
| view_riksdagen_politician_career_path_10level | Standard | βββββ | 10-level politician career path classification (v1.58) |
| view_riksdagen_politician_career_trajectory | Standard | βββββ | Politician career trajectory and pattern detection (v1.56) |
| view_riksdagen_politician_longevity_analysis | Standard | βββββ | Politician longevity and survival analysis (v1.56) |
| view_riksdagen_politician_role_evolution | Standard | βββββ | Politician role evolution and progression tracking (v1.56) |
| view_riksdagen_politician_document_daily_summary | π Materialized | ββββ | Daily politician document productivity |
| view_riksdagen_politician_document_summary | π Materialized | ββββ | Aggregated politician document statistics |
Vote Data Views (16 views)
Ballot Summary Views (5 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_riksdagen_vote_data_ballot_summary | π Materialized | ββββ | Overall ballot outcome summary |
| view_riksdagen_vote_data_ballot_summary_annual | π Materialized | ββββ | Annual ballot summary aggregation |
| view_riksdagen_vote_data_ballot_summary_daily | π Materialized | ββββ | Daily ballot summary aggregation |
| view_riksdagen_vote_data_ballot_summary_monthly | π Materialized | ββββ | Monthly ballot summary aggregation |
| view_riksdagen_vote_data_ballot_summary_weekly | π Materialized | ββββ | Weekly ballot summary aggregation |
Party Voting Views (5 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_riksdagen_vote_data_ballot_party_summary | π Materialized | βββββ | Party-level voting summary |
| view_riksdagen_vote_data_ballot_party_summary_annual | π Materialized | βββββ | Annual party voting patterns |
| view_riksdagen_vote_data_ballot_party_summary_daily | π Materialized | βββββ | Daily party voting patterns |
| view_riksdagen_vote_data_ballot_party_summary_monthly | π Materialized | βββββ | Monthly party voting patterns |
| view_riksdagen_vote_data_ballot_party_summary_weekly | π Materialized | βββββ | Weekly party voting patterns |
Politician Voting Views (5 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_riksdagen_vote_data_ballot_politician_summary | π Materialized | βββββ | Individual politician voting summary |
| view_riksdagen_vote_data_ballot_politician_summary_annual | π Materialized | βββββ | Annual politician voting patterns |
| π view_riksdagen_vote_data_ballot_politician_summary_daily | π Materialized | βββββ | Daily politician voting patterns |
| view_riksdagen_vote_data_ballot_politician_summary_monthly | π Materialized | βββββ | Monthly politician voting patterns |
| view_riksdagen_vote_data_ballot_politician_summary_weekly | π Materialized | βββββ | Weekly politician voting patterns |
Annual Voting Metrics (1 view)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| mv_annual_voting_metrics | π Materialized | ββββ | Pre-aggregated annual voting metrics (v1.76) |
Election Cycle Views (6 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_election_cycle_anomaly_pattern | Standard | βββββ | Election cycle anomaly pattern detection (v1.51) |
| view_election_cycle_comparative_analysis | Standard | βββββ | Cross-election cycle comparative analysis (v1.51) |
| view_election_cycle_decision_intelligence | Standard | βββββ | Election cycle decision intelligence metrics (v1.51) |
| view_election_cycle_network_analysis | Standard | βββββ | Election cycle network and coalition analysis (v1.51) |
| view_election_cycle_predictive_intelligence | Standard | βββββ | Election cycle predictive intelligence (v1.51) |
| view_election_cycle_temporal_trends | Standard | βββββ | Election cycle temporal trend analysis (v1.51) |
Seasonal & Election Year Views (7 views)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_riksdagen_election_proximity_trends | Standard | ββββ | Behavioral trends by proximity to elections (v1.59) |
| view_riksdagen_election_year_behavioral_patterns | Standard | ββββ | Election year vs non-election year behavioral patterns (v1.60) |
| view_riksdagen_pre_election_quarterly_activity | Standard | ββββ | Pre-election quarterly activity patterns (v1.59) |
| view_riksdagen_q4_election_year_comparison | Standard | ββββ | Q4 election year vs non-election year comparison (v1.55) |
| view_riksdagen_seasonal_activity_patterns | Standard | ββββ | Seasonal parliamentary activity patterns (v1.59) |
| view_riksdagen_seasonal_anomaly_detection | Standard | βββββ | Seasonal anomaly detection in parliamentary activity (v1.55) |
| view_riksdagen_seasonal_quarterly_activity | Standard | ββββ | Quarterly seasonal activity metrics (v1.55) |
WorldBank Data (1 view)
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_worldbank_indicator_data_country_summary | π Materialized | βββ | Economic indicators for country analysis |
Total Views: 110 (77 regular + 33 materialized)
Detailed Documentation (π): 15
Structured Documentation (π): 95
Documentation Coverage: 100%
Materialized Views: 33
Views by Intelligence Value:
- βββββ VERY HIGH: 30 views
- ββββ HIGH: 26 views
- βββ MEDIUM: 12 views
- ββ LOW: 14 views
Politician Views
Overview
Politician views provide comprehensive intelligence on individual parliamentary members, tracking their experience, behavioral patterns, voting records, document productivity, and risk indicators. These views form the foundation for individual performance scorecards and behavioral analysis.
Total Politician Views: 15+
Intelligence Value: βββββ VERY HIGH
Primary Use Cases: Performance monitoring, risk assessment, experience tracking, productivity analysis
view_riksdagen_politician βββββ
Category: Base Politician Views (v1.1)
Type: Standard View
Intelligence Value: VERY HIGH - Core Politician Profile
Business Context
Market Value: β¬15M TAM (Political Consulting segment)
Product Integration: Political Intelligence API (Product Line 1)
Revenue Impact: Core data source for β¬99/month Professional tier subscriptions
JSON Export Spec: politician-schema.md
API Endpoint: GET /api/v1/politicians, GET /api/v1/politicians/{id}
Used In Product Features:
- Politician risk scorecards (Political Consulting, Media & Journalism)
- Campaign analytics dashboards (Academic Research)
- Electoral risk assessments (Corporate Affairs)
- Party performance comparison (NGOs & Advocacy)
Target Customer Segments:
- Political Consulting (β¬15M TAM): Opposition research, candidate selection, voter targeting
- Media & Journalism (β¬8M TAM): Investigative reporting, fact-checking, political profiles
- Academic Research (β¬5M TAM): Electoral studies, political behavior analysis, comparative politics
Business Documentation: See BUSINESS_PRODUCT_DOCUMENT.md#product-line-1
Purpose
Central politician profile view aggregating basic biographical data, current party affiliation, electoral region, and active assignment status. Serves as the primary lookup table for politician identification and profile queries.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier (Riksdagen ID) | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
gender | VARCHAR(10) | Gender | 'woman', 'man' |
born_year | INTEGER | Birth year | 1972 |
party | VARCHAR(50) | Current party affiliation (short code) | 'S' (Social Democrats) |
status | VARCHAR(50) | Current assignment status | 'TjΓ€nstgΓΆrande riksdagsledamot' |
electoral_region | VARCHAR(100) | Electoral constituency | 'Stockholms kommun' |
total_assignments | INTEGER | Total career assignments | 15 |
total_days_served | INTEGER | Total days in parliament | 2847 |
first_assignment_date | DATE | Career start date | '2014-09-29' |
last_assignment_date | DATE | Most recent assignment end | '2024-11-17' |
Example Queries
1. Active Politicians by Party (Current Parliament)
SELECT
party,
COUNT(*) AS member_count,
COUNT(*) FILTER (WHERE gender = 'KVINNA') AS women_count,
COUNT(*) FILTER (WHERE gender = 'MAN') AS men_count,
ROUND(AVG(2024 - born_year), 1) AS avg_age,
ROUND(AVG(total_days_served), 0) AS avg_days_experience
FROM view_riksdagen_politician
WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot'
GROUP BY party
ORDER BY member_count DESC;
Note: Gender values in the data are Swedish: 'KVINNA' (woman) and 'MAN' (man). See view_riksdagen_politician_sample.csv for current sample data.
Output:
party | member_count | women_count | men_count | avg_age | avg_days_experience
-------+--------------+-------------+-----------+---------+--------------------
SD | 73 | 20 | 53 | 48.2 | 1825
S | 70 | 35 | 35 | 52.1 | 2347
M | 68 | 29 | 39 | 49.8 | 2103
2. Longest-Serving Active Politicians
SELECT
first_name,
last_name,
party,
total_days_served,
ROUND(total_days_served / 365.25, 1) AS years_served,
first_assignment_date,
total_assignments
FROM view_riksdagen_politician
WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot'
ORDER BY total_days_served DESC
LIMIT 20;
3. Gender Balance Analysis by Party
SELECT
party,
COUNT(*) AS total,
COUNT(*) FILTER (WHERE gender = 'KVINNA') AS women,
COUNT(*) FILTER (WHERE gender = 'MAN') AS men,
ROUND(100.0 * COUNT(*) FILTER (WHERE gender = 'KVINNA') / COUNT(*), 1) AS women_pct
FROM view_riksdagen_politician
WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot'
GROUP BY party
ORDER BY women_pct DESC;
4. New Politicians (Less than 2 Years Experience)
SELECT
first_name,
last_name,
party,
electoral_region,
first_assignment_date,
total_days_served
FROM view_riksdagen_politician
WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot'
AND total_days_served < 730 -- Less than 2 years
ORDER BY first_assignment_date DESC;
5. Electoral Region Representation
SELECT
electoral_region,
COUNT(*) AS representatives,
STRING_AGG(DISTINCT party, ', ' ORDER BY party) AS parties_represented
FROM view_riksdagen_politician
WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot'
GROUP BY electoral_region
ORDER BY representatives DESC
LIMIT 15;
Performance Characteristics
- Query Time: <10ms (indexed)
- Indexes Used:
idx_person_data_person_id,idx_person_data_party - Data Volume: ~2,000 rows (all politicians, active + historical)
- Refresh Frequency: Real-time (standard view)
- Common Filters:
status,party,person_id - Sample Data: view_riksdagen_politician_sample.csv (2,079 rows, verified 2026-01-01)
Data Sources
- Primary Table:
person_data(core politician information) - Joined Tables:
assignment_data(for assignment counts and dates)
Dependencies
- No view dependencies (built directly on source tables)
- Used by: Nearly all politician-related views
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PoliticianLazy (P-01): Provides politician identification
- PoliticianIneffectiveVoting (P-02): Links to voting analysis
- All Politician Rules: Base identification layer
Intelligence Applications
This view supports multiple analytical frameworks from DATA_ANALYSIS_INTOP_OSINT.md:
| Analysis Framework | Use Case | Example Application | Link |
|---|---|---|---|
| Temporal Analysis | Track career duration and entry cohorts | Monitor politician career trajectories over time | Framework Docs |
| Comparative Analysis | Party composition and experience levels | Compare experience distribution across parties | Framework Docs |
| Pattern Recognition | Demographic clustering analysis | Identify patterns in gender, age, regional representation | Framework Docs |
| Predictive Intelligence | Career trajectory modeling | Predict re-election likelihood based on profile | Framework Docs |
| Network Analysis | Politician identification for network construction | Base layer for building collaboration and voting networks | Framework Docs |
Intelligence Products Generated:
- π Political Scorecards - Basic identification and demographic information
- π Party Composition Reports - Gender balance, age distribution, regional representation
- π― Recruitment Analysis - New politician tracking and onboarding patterns
Data Flow: See Intelligence Data Flow Map - View to Analysis Mapping for complete data pipeline.
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Demographic Analysis: Gender, age, regional representation
- Comparative Analysis: Party composition, experience levels
- Temporal Analysis: Career duration, entry cohorts
Integration with Product Features
From BUSINESS_PRODUCT_DOCUMENT.md:
- Politician Dashboard (Product Line 1): Core profile data
- Search & Discovery (Product Line 1): Politician lookup
- Comparative Analytics (Product Line 2): Party composition
view_riksdagen_politician_experience_summary βββββ
Category: Politician Intelligence Views (v1.28)
Type: Standard View
Intelligence Value: VERY HIGH - Experience Scoring & Classification
Changelog: v1.28 OSINT Experience Tracking
Purpose
Sophisticated experience scoring system that calculates weighted experience based on assignment types, durations, and roles. Provides standardized experience classification from NOVICE to VETERAN, enabling experience-based analysis and comparative assessments.
β οΈ Data Quality Note: This view was affected by a missing role pattern issue that has been resolved.
Issue: Missing 'FΓΆrste vice talman' in talmansuppdrag scoring (affected 8 records)
Status: β Fixed in Liquibase changeset db-changelog-1.44.xml
Details: See Data Quality Analysis in README-SCHEMA-MAINTENANCE.md
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Current party affiliation | 'S' |
total_assignments | INTEGER | Total number of assignments | 15 |
total_days | INTEGER | Total days in active assignments | 2847 |
total_years | NUMERIC(10,2) | Total years experience | 7.79 |
ministerial_days | INTEGER | Days in government positions | 1095 |
committee_chair_days | INTEGER | Days as committee chair | 547 |
committee_member_days | INTEGER | Days as committee member | 1825 |
parliamentary_member_days | INTEGER | Days as MP without other roles | 380 |
total_weighted_exp | NUMERIC(15,2) | Weighted experience score | 4783.50 |
experience_level | VARCHAR(50) | Classification | 'EXPERIENCED', 'VETERAN', 'NOVICE' |
ministerial_experience | BOOLEAN | Has held government position | TRUE |
committee_leadership_exp | BOOLEAN | Has been committee chair | TRUE |
avg_assignment_duration | NUMERIC(10,2) | Average assignment length (days) | 189.80 |
Weighting System
Experience is weighted by assignment importance:
| Assignment Type | Weight Multiplier | Rationale |
|---|---|---|
| Ministerial | 2.0x | Government executive responsibility |
| Committee Chair | 1.5x | Leadership and organizational authority |
| Committee Member | 1.2x | Specialized legislative work |
| Parliamentary Member | 1.0x | Base legislative responsibility |
Weighted Experience Formula:
total_weighted_exp = (ministerial_days Γ 2.0) +
(committee_chair_days Γ 1.5) +
(committee_member_days Γ 1.2) +
(parliamentary_member_days Γ 1.0)
Experience Level Classification
| Level | Criteria | Description |
|---|---|---|
| NOVICE | < 365 days | First year, learning parliamentary procedures |
| DEVELOPING | 365-1095 days (1-3 years) | Building expertise, establishing networks |
| EXPERIENCED | 1095-2190 days (3-6 years) | Established politician, strong influence |
| VETERAN | 2190-3650 days (6-10 years) | Senior parliamentarian, institutional knowledge |
| ELDER_STATESMAN | > 3650 days (10+ years) | Parliamentary elder, mentor, historical perspective |
Example Queries
1. Experience Distribution by Party
SELECT
party,
experience_level,
COUNT(*) AS member_count,
ROUND(AVG(total_years), 1) AS avg_years,
ROUND(AVG(total_weighted_exp), 0) AS avg_weighted_exp
FROM view_riksdagen_politician_experience_summary
WHERE total_days > 0 -- Active or has history
GROUP BY party, experience_level
ORDER BY party,
CASE experience_level
WHEN 'ELDER_STATESMAN' THEN 5
WHEN 'VETERAN' THEN 4
WHEN 'EXPERIENCED' THEN 3
WHEN 'DEVELOPING' THEN 2
WHEN 'NOVICE' THEN 1
END DESC;
2. Top 20 Most Experienced Politicians (Weighted Score)
SELECT
first_name,
last_name,
party,
total_years,
total_weighted_exp,
experience_level,
ministerial_experience,
committee_leadership_exp
FROM view_riksdagen_politician_experience_summary
ORDER BY total_weighted_exp DESC
LIMIT 20;
3. Former Ministers Currently in Parliament
SELECT
first_name,
last_name,
party,
ministerial_days,
ROUND(ministerial_days / 365.25, 1) AS ministerial_years,
total_years AS total_parliamentary_years
FROM view_riksdagen_politician_experience_summary
WHERE ministerial_experience = TRUE
AND ministerial_days > 0
ORDER BY ministerial_days DESC;
4. Committee Leadership Experience by Party
SELECT
party,
COUNT(*) FILTER (WHERE committee_leadership_exp = TRUE) AS leaders_count,
COUNT(*) AS total_count,
ROUND(100.0 * COUNT(*) FILTER (WHERE committee_leadership_exp = TRUE) / COUNT(*), 1) AS leadership_pct,
ROUND(AVG(committee_chair_days) FILTER (WHERE committee_chair_days > 0), 0) AS avg_chair_days
FROM view_riksdagen_politician_experience_summary
WHERE total_days > 0
GROUP BY party
ORDER BY leadership_pct DESC;
5. Experience Gap Analysis (Novices vs Veterans)
WITH experience_extremes AS (
SELECT
party,
COUNT(*) FILTER (WHERE experience_level IN ('NOVICE', 'DEVELOPING')) AS junior_count,
COUNT(*) FILTER (WHERE experience_level IN ('VETERAN', 'ELDER_STATESMAN')) AS senior_count,
COUNT(*) AS total
FROM view_riksdagen_politician_experience_summary
WHERE total_days > 0
GROUP BY party
)
SELECT
party,
junior_count,
senior_count,
total,
ROUND(100.0 * junior_count / total, 1) AS junior_pct,
ROUND(100.0 * senior_count / total, 1) AS senior_pct,
CASE
WHEN junior_count > senior_count * 2 THEN 'HIGH_RENEWAL'
WHEN senior_count > junior_count * 2 THEN 'VETERAN_DOMINATED'
ELSE 'BALANCED'
END AS composition_assessment
FROM experience_extremes
ORDER BY party;
Performance Characteristics
- Query Time: 50-100ms (complex aggregation)
- Indexes Used:
idx_assignment_data_person,idx_assignment_data_role_code - Data Volume: ~2,000 rows (all politicians with assignments)
- Refresh Frequency: Real-time (standard view with complex calculations)
- Sample Data: view_riksdagen_politician_experience_summary_sample.csv (2,093 rows with JSON columns for detailed experience breakdown)
Data Sources
- Primary Table:
assignment_data(all assignments with date ranges) - Joined Tables:
person_data(for identification)
Dependencies
- No view dependencies (built directly on source tables)
- Future: May be materialized in v1.32 for performance
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PoliticianLackExperience (P-10): Identifies novice politicians
- PoliticianOverexperiencedDisengaged (P-11): Tracks elder statesmen
- Experience context for all politician risk rules
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Comparative Analysis: Experience benchmarking across parties
- Pattern Recognition: Experience clustering and composition
- Predictive Intelligence: Experience-performance correlation
Integration with Product Features
From BUSINESS_PRODUCT_DOCUMENT.md:
- Politician Dashboard (Product Line 1): Experience metrics
- Advanced Analytics (Product Line 2): Experience distribution
- Comparative Tools (Product Line 2): Experience benchmarking
view_politician_behavioral_trends βββββ
Category: Intelligence Views (v1.30)
Type: Standard View
Intelligence Value: VERY HIGH - Behavioral Pattern Analysis
Changelog: v1.30 OSINT Performance Tracking
Purpose
Tracks individual politician behavioral metrics (absence, effectiveness, rebellion) over time with monthly granularity over a 3-year rolling window. Includes automated classification and trend detection for early warning of performance degradation and behavioral anomalies.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier | 'Q123456' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Current party affiliation | 'S' |
year_month | DATE | Month of aggregation (first day) | '2024-10-01' |
ballot_count | INTEGER | Number of ballots in period | 45 |
avg_absence_rate | NUMERIC(5,2) | Percentage absent | 12.50 |
avg_win_rate | NUMERIC(5,2) | Percentage on winning side | 67.80 |
avg_rebel_rate | NUMERIC(5,2) | Percentage against party | 8.30 |
absence_trend | NUMERIC(5,2) | Change from previous month | +2.50 |
effectiveness_trend | NUMERIC(5,2) | Win rate change | -3.20 |
rebellion_trend | NUMERIC(5,2) | Rebel rate change | +1.10 |
ma_3month_absence | NUMERIC(5,2) | 3-month moving average absence | 11.20 |
ma_3month_win | NUMERIC(5,2) | 3-month moving average win rate | 69.00 |
ma_3month_rebel | NUMERIC(5,2) | 3-month moving average rebel rate | 7.50 |
attendance_status | VARCHAR(50) | Classification | 'MODERATE_ABSENTEEISM' |
effectiveness_status | VARCHAR(50) | Classification | 'EFFECTIVE' |
discipline_status | VARCHAR(50) | Classification | 'LOW_INDEPENDENCE' |
behavioral_assessment | VARCHAR(50) | Overall assessment | 'STANDARD_BEHAVIOR' |
Classification Thresholds
Attendance Status:
EXCELLENT_ATTENDANCE: < 5% absenceGOOD_ATTENDANCE: 5-10% absenceMODERATE_ABSENTEEISM: 10-20% absenceHIGH_ABSENTEEISM: 20-30% absenceCRITICAL_ABSENTEEISM: > 30% absence
Effectiveness Status:
HIGHLY_EFFECTIVE: > 70% win rateEFFECTIVE: 55-70% win rateMODERATE_EFFECTIVENESS: 45-55% win rateINEFFECTIVE: < 45% win rate
Discipline Status:
HIGH_INDEPENDENCE: > 15% rebellion (frequent dissent)MODERATE_INDEPENDENCE: 10-15% rebellionLOW_INDEPENDENCE: 5-10% rebellionPARTY_LINE: < 5% rebellion (high discipline)
Behavioral Assessment (Combined):
EXCELLENT_BEHAVIOR: Excellent attendance + high effectiveness + low rebellionSTANDARD_BEHAVIOR: Normal patterns across all metricsMODERATE_RISK: One metric concerning, others normalELEVATED_RISK: Multiple concerning metricsCRITICAL_CONCERN: All metrics problematic
Example Queries
1. Top 10 Politicians with Declining Attendance (Last 6 Months)
SELECT
first_name,
last_name,
party,
AVG(avg_absence_rate) AS avg_absence,
AVG(absence_trend) AS avg_trend,
COUNT(*) AS months_tracked
FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '6 months'
AND ballot_count >= 10 -- Minimum sample size
GROUP BY person_id, first_name, last_name, party
HAVING AVG(absence_trend) > 0 -- Declining attendance
ORDER BY AVG(absence_trend) DESC
LIMIT 10;
2. High-Risk Politicians (Moderate Risk or Worse)
SELECT
first_name,
last_name,
party,
year_month,
avg_absence_rate,
avg_win_rate,
avg_rebel_rate,
behavioral_assessment
FROM view_politician_behavioral_trends
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
AND behavioral_assessment IN ('MODERATE_RISK', 'ELEVATED_RISK', 'CRITICAL_CONCERN')
ORDER BY
CASE behavioral_assessment
WHEN 'CRITICAL_CONCERN' THEN 3
WHEN 'ELEVATED_RISK' THEN 2
WHEN 'MODERATE_RISK' THEN 1
END DESC,
party, last_name;
3. Party Average Comparison (Individual vs. Party Benchmark)
WITH party_averages AS (
SELECT
party,
AVG(avg_absence_rate) AS party_avg_absence,
AVG(avg_win_rate) AS party_avg_win,
AVG(avg_rebel_rate) AS party_avg_rebel
FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY party
)
SELECT
pbt.first_name,
pbt.last_name,
pbt.party,
ROUND(AVG(pbt.avg_absence_rate), 2) AS individual_absence,
ROUND(pa.party_avg_absence, 2) AS party_avg_absence,
ROUND(AVG(pbt.avg_absence_rate) - pa.party_avg_absence, 2) AS absence_vs_party,
CASE
WHEN AVG(pbt.avg_absence_rate) > pa.party_avg_absence + 10 THEN 'OUTLIER_HIGH'
WHEN AVG(pbt.avg_absence_rate) < pa.party_avg_absence - 10 THEN 'OUTLIER_LOW'
ELSE 'NORMAL'
END AS classification
FROM view_politician_behavioral_trends pbt
JOIN party_averages pa ON pa.party = pbt.party
WHERE pbt.year_month >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY pbt.person_id, pbt.first_name, pbt.last_name, pbt.party, pa.party_avg_absence
ORDER BY absence_vs_party DESC
LIMIT 30;
4. Behavioral Trend Analysis (3-Month Moving Average)
SELECT
person_id,
first_name,
last_name,
party,
year_month,
avg_absence_rate,
ma_3month_absence,
avg_absence_rate - ma_3month_absence AS deviation_from_ma,
attendance_status
FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months'
AND ballot_count >= 10
AND ABS(avg_absence_rate - ma_3month_absence) > 5 -- Significant deviation
ORDER BY ABS(avg_absence_rate - ma_3month_absence) DESC
LIMIT 20;
5. Excellence Report (Top Performers)
SELECT
first_name,
last_name,
party,
ROUND(AVG(avg_absence_rate), 2) AS avg_absence,
ROUND(AVG(avg_win_rate), 2) AS avg_win,
ROUND(AVG(avg_rebel_rate), 2) AS avg_rebel,
COUNT(DISTINCT year_month) AS months_tracked
FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months'
AND ballot_count >= 10
GROUP BY person_id, first_name, last_name, party
HAVING AVG(avg_absence_rate) < 5 -- Excellent attendance
AND AVG(avg_win_rate) > 65 -- High effectiveness
ORDER BY avg_absence ASC, avg_win DESC
LIMIT 20;
Performance Characteristics
- Query Time: 100-200ms (complex aggregation over time series)
- Indexes Used:
idx_vote_summary_daily_date_person - Data Volume: ~15,000 rows (350 politicians Γ 36 months rolling window)
- Refresh Frequency: Real-time (recalculated on query)
- Optimization Note: Candidate for materialization in v1.32
Data Sources
- Primary View:
view_riksdagen_vote_data_ballot_politician_summary_daily - Aggregation: Monthly rollup with LAG() for trend calculation
- Moving Averages: 3-month window using window functions
Dependencies
- Depends on:
view_riksdagen_vote_data_ballot_politician_summary_daily - Used by:
view_risk_score_evolution, intelligence dashboards
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PoliticianLazy (P-01):
avg_absence_rate,attendance_status - PoliticianIneffectiveVoting (P-02):
avg_win_rate,effectiveness_status - PoliticianHighRebelRate (P-03):
avg_rebel_rate,discipline_status - PoliticianDecliningEngagement (P-04): All trend metrics
- PoliticianCombinedRisk (P-05):
behavioral_assessment
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Temporal Analysis: Monthly time-series with moving averages
- Comparative Analysis: Individual vs. party benchmarking
- Pattern Recognition: Behavioral classification and clustering
- Predictive Intelligence: Trend extrapolation for forecasting
view_riksdagen_politician_document ββββ
Category: Document Views (v1.1, enhanced v1.24)
Type: Standard View
Intelligence Value: HIGH - Legislative Productivity Tracking
Purpose
Tracks all documents (motions, interpellations, written questions, proposals) authored or co-authored by individual politicians. Provides productivity metrics and policy focus analysis based on document types and submission patterns.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Party at document submission | 'S' |
document_id | VARCHAR(255) | Document identifier | 'H801234' |
document_type | VARCHAR(50) | Type of document | 'Interpellation', 'Motion' |
title | TEXT | Document title | 'Svar pΓ₯ frΓ₯ga om...' |
sub_title | TEXT | Document subtitle | Additional context |
made_public_date | DATE | Publication date | '2024-10-15' |
document_status | VARCHAR(50) | Current status | 'Besvarad', 'Bordlagd' |
org_code | VARCHAR(20) | Originating organization | 'au' (Labor committee) |
label | VARCHAR(100) | Document category/label | 'Arbetsmarknad' |
Document Types
| Type | Swedish Term | Description | Frequency |
|---|---|---|---|
| Motion | Motion | Legislative proposal by MP | Common |
| Interpellation | Interpellation | Question to minister requiring debate | Moderate |
| Written Question | Skriftlig frΓ₯ga | Written question to minister | Common |
| Simple Question | FrΓ₯ga | Simple parliamentary question | Very Common |
| EU Document | EU-dokument | EU-related document | Rare |
| Committee Proposal | UtskottsfΓΆrslag | Committee recommendation | Common |
Example Queries
1. Top 20 Most Productive Politicians (Last 12 Months)
SELECT
first_name,
last_name,
party,
COUNT(*) AS total_documents,
COUNT(*) FILTER (WHERE document_type = 'Motion') AS motions,
COUNT(*) FILTER (WHERE document_type = 'Interpellation') AS interpellations,
COUNT(*) FILTER (WHERE document_type = 'Skriftlig frΓ₯ga') AS written_questions,
MIN(made_public_date) AS first_document,
MAX(made_public_date) AS latest_document
FROM view_riksdagen_politician_document
WHERE made_public_date >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY person_id, first_name, last_name, party
ORDER BY total_documents DESC
LIMIT 20;
2. Policy Focus Analysis by Politician
SELECT
first_name,
last_name,
party,
org_code AS policy_area,
COUNT(*) AS document_count,
STRING_AGG(DISTINCT document_type, ', ') AS document_types,
MIN(made_public_date) AS first_activity,
MAX(made_public_date) AS latest_activity
FROM view_riksdagen_politician_document
WHERE made_public_date >= CURRENT_DATE - INTERVAL '24 months'
GROUP BY person_id, first_name, last_name, party, org_code
HAVING COUNT(*) >= 5 -- Minimum activity threshold
ORDER BY person_id, document_count DESC;
3. Interpellation Activity (Parliamentary Accountability)
SELECT
first_name,
last_name,
party,
COUNT(*) AS interpellation_count,
ARRAY_AGG(DISTINCT org_code ORDER BY org_code) AS ministries_questioned,
MIN(made_public_date) AS first_interpellation,
MAX(made_public_date) AS latest_interpellation
FROM view_riksdagen_politician_document
WHERE document_type = 'Interpellation'
AND made_public_date >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY person_id, first_name, last_name, party
ORDER BY interpellation_count DESC
LIMIT 30;
4. Productivity Trends (Quarterly Analysis)
WITH quarterly_productivity AS (
SELECT
person_id,
first_name,
last_name,
party,
DATE_TRUNC('quarter', made_public_date) AS quarter,
COUNT(*) AS documents_per_quarter
FROM view_riksdagen_politician_document
WHERE made_public_date >= CURRENT_DATE - INTERVAL '24 months'
GROUP BY person_id, first_name, last_name, party, DATE_TRUNC('quarter', made_public_date)
)
SELECT
first_name,
last_name,
party,
AVG(documents_per_quarter) AS avg_quarterly_documents,
MAX(documents_per_quarter) AS peak_quarter_documents,
MIN(documents_per_quarter) AS min_quarter_documents,
COUNT(DISTINCT quarter) AS quarters_active
FROM quarterly_productivity
GROUP BY person_id, first_name, last_name, party
HAVING COUNT(DISTINCT quarter) >= 4 -- At least 4 quarters of activity
ORDER BY avg_quarterly_documents DESC
LIMIT 20;
5. Cross-Party Collaboration (Co-Authored Documents)
-- This would require joining with a co-author mapping table
-- Simplified version showing single-party vs cross-party documents
SELECT
pd1.first_name,
pd1.last_name,
pd1.party,
COUNT(DISTINCT pd1.document_id) AS total_documents,
COUNT(DISTINCT CASE
WHEN pd2.party IS NOT NULL AND pd2.party != pd1.party
THEN pd1.document_id
END) AS cross_party_documents,
ROUND(100.0 * COUNT(DISTINCT CASE
WHEN pd2.party IS NOT NULL AND pd2.party != pd1.party
THEN pd1.document_id
END) / NULLIF(COUNT(DISTINCT pd1.document_id), 0), 1) AS cross_party_pct
FROM view_riksdagen_politician_document pd1
LEFT JOIN view_riksdagen_politician_document pd2
ON pd2.document_id = pd1.document_id
AND pd2.person_id != pd1.person_id
WHERE pd1.made_public_date >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY pd1.person_id, pd1.first_name, pd1.last_name, pd1.party
HAVING COUNT(DISTINCT pd1.document_id) >= 10
ORDER BY cross_party_pct DESC
LIMIT 20;
Performance Characteristics
- Query Time: 50-100ms (indexed on date and person_id)
- Indexes Used:
idx_politician_document_date_person,idx_politician_document_type - Data Volume: ~500,000 rows (all historical documents)
- Refresh Frequency: Real-time (standard view)
Data Sources
- Primary Table:
document_data(all parliamentary documents) - Joined Tables:
person_data(for politician identification)
Dependencies
- No view dependencies
- Used by:
view_riksdagen_politician_document_daily_summary
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PoliticianLowProductivity (P-06): Document count metric
- PoliticianNoDocumentsRecent (P-07): Recent activity tracking
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Productivity Analysis: Document volume and type distribution
- Policy Focus Analysis: Topic clustering and specialization
- Temporal Analysis: Activity patterns and trends
view_riksdagen_politician_ballot_summary βββββ
Category: Politician Voting Views (v1.25)
Type: Standard View
Intelligence Value: VERY HIGH - Comprehensive Voting Record Analysis
Purpose
Aggregates complete voting record for each politician across all ballots, providing win/loss percentages, absence statistics, rebellion rates, and party discipline metrics. Essential for politician performance scorecards and voting behavior analysis.
Key Metrics
- Total Votes: Lifetime ballot participation count
- Win Percentage: Percentage of votes on winning side
- Absence Percentage: Rate of missed votes
- Rebellion Rate: Votes against party line percentage
- Party Loyalty Score: Votes with party percentage
Sample Query: Top Performers
SELECT first_name, last_name, party, total_votes, win_percentage, absence_percentage
FROM view_riksdagen_politician_ballot_summary
WHERE total_votes >= 100
ORDER BY win_percentage DESC, absence_percentage ASC
LIMIT 20;
Intelligence Applications
- Performance scorecards and politician rankings
- Party discipline analysis
- Absence problem identification
- Career voting statistics
view_riksdagen_politician_influence_metrics βββββ
Category: Intelligence Views (v1.30)
Type: Standard View
Intelligence Value: VERY HIGH - Network Analysis & Power Mapping
Purpose
Calculates politician influence and network centrality metrics including degree centrality, betweenness, cross-party collaboration scores. Identifies power brokers and bridge politicians facilitating coalition formation.
Key Metrics
- Broker Score: Power broker metric (0-1 scale)
- Cross-Party Ratio: % connections outside own party
- Connectivity Level: Network position classification
- Influence Rank: Relative influence ranking
Sample Query: Power Brokers
SELECT first_name, last_name, party, broker_score, cross_party_connections, broker_classification
FROM view_riksdagen_politician_influence_metrics
WHERE broker_classification IN ('STRONG_BROKER', 'MODERATE_BROKER')
ORDER BY broker_score DESC
LIMIT 15;
Intelligence Applications
- Coalition facilitator identification
- Network power structure mapping
- Cross-bloc bridge analysis
- Influence hierarchy visualization
view_politician_risk_summary βββββ
Category: Intelligence Views (v1.30)
Type: Standard View
Intelligence Value: VERY HIGH - Current Risk State Assessment
Purpose
Provides current-state risk summary for all politicians with latest risk scores, violation counts, and risk classifications. Optimized for dashboard displays and real-time risk monitoring.
Key Metrics
- Current Risk Score: Latest aggregate risk points
- Risk Severity: CRITICAL, MAJOR, MINOR classification
- Active Violations: Current rule violation count
- Risk Trajectory: ESCALATING, STABLE, IMPROVING
Sample Query: High-Risk Dashboard
SELECT first_name, last_name, party, current_risk_score, risk_severity, active_violations
FROM view_politician_risk_summary
WHERE risk_severity IN ('CRITICAL', 'MAJOR')
ORDER BY current_risk_score DESC;
Intelligence Applications
- Real-time risk monitoring dashboards
- Alert systems for high-risk politicians
- Party risk distribution analysis
- Risk intervention prioritization
view_riksdagen_politician_decision_pattern βββββ
Category: Politician Intelligence Views (v1.35)
Type: Standard View
Intelligence Value: VERY HIGH - Decision Effectiveness & Committee Specialization
Changelog: v1.35 Politician Decision Pattern Tracking
Purpose
Tracks individual politician decision patterns from DOCUMENT_PROPOSAL_DATA, enabling analysis of politician-level proposal success rates, committee work effectiveness, and legislative productivity. Complements view_riksdagen_party_decision_flow by providing individual politician decision analytics.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Party affiliation at decision time | 'S' |
committee | VARCHAR(255) | Committee handling decision | 'UU' (Foreign Affairs) |
committee_org | VARCHAR(20) | Committee organization code | 'uu' |
decision_month | DATE | Month of aggregation (first day) | '2024-10-01' |
decision_year | INTEGER | Year of decision | 2024 |
decision_month_num | INTEGER | Month number (1-12) | 10 |
total_decisions | BIGINT | Total decisions in period | 45 |
approved_decisions | BIGINT | Decisions approved (bifall) | 32 |
rejected_decisions | BIGINT | Decisions rejected (avslag) | 8 |
referred_back_decisions | BIGINT | Decisions referred back | 3 |
other_decisions | BIGINT | Other decision outcomes | 2 |
approval_rate | NUMERIC(5,2) | Percentage approved | 71.11 |
rejection_rate | NUMERIC(5,2) | Percentage rejected | 17.78 |
earliest_decision_date | DATE | First decision in period | '2024-10-01' |
latest_decision_date | DATE | Last decision in period | '2024-10-31' |
Note: This view aggregates all decision types together. It focuses on politician-committee-month granularity for tracking decision effectiveness.
Example Queries
1. Top 10 Most Effective Politicians by Approval Rate (Last Year)
SELECT
first_name,
last_name,
party,
SUM(total_decisions) AS total_decisions,
ROUND(
100.0 * SUM(approved_decisions) / NULLIF(SUM(total_decisions), 0),
2
) AS overall_approval_rate,
COUNT(DISTINCT committee) AS committees_worked,
STRING_AGG(DISTINCT committee, ', ' ORDER BY committee) AS committees
FROM view_riksdagen_politician_decision_pattern
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY person_id, first_name, last_name, party
HAVING SUM(total_decisions) >= 5 -- Minimum sample size
ORDER BY overall_approval_rate DESC, total_decisions DESC
LIMIT 10;
2. Committee Specialist Identification
-- Identify politicians with high activity in specific committees
WITH committee_activity AS (
SELECT
person_id,
first_name,
last_name,
party,
committee,
SUM(total_decisions) AS decisions_in_committee,
ROUND(AVG(approval_rate), 2) AS avg_approval_rate
FROM view_riksdagen_politician_decision_pattern
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 1
GROUP BY person_id, first_name, last_name, party, committee
),
total_activity AS (
SELECT
person_id,
SUM(decisions_in_committee) AS total_decisions_all_committees
FROM committee_activity
GROUP BY person_id
)
SELECT
ca.first_name,
ca.last_name,
ca.party,
ca.committee,
ca.decisions_in_committee,
ROUND(
100.0 * ca.decisions_in_committee / ta.total_decisions_all_committees,
1
) AS concentration_pct,
ca.avg_approval_rate,
CASE
WHEN 100.0 * ca.decisions_in_committee / ta.total_decisions_all_committees >= 60 THEN 'SPECIALIST'
WHEN 100.0 * ca.decisions_in_committee / ta.total_decisions_all_committees >= 40 THEN 'FOCUSED'
ELSE 'DIVERSIFIED'
END AS specialization_level
FROM committee_activity ca
JOIN total_activity ta ON ta.person_id = ca.person_id
WHERE ta.total_decisions_all_committees >= 10 -- Minimum activity threshold
ORDER BY concentration_pct DESC
LIMIT 20;
3. Monthly Decision Productivity Trend
SELECT
person_id,
first_name,
last_name,
party,
decision_month,
SUM(total_decisions) AS monthly_decisions,
ROUND(AVG(approval_rate), 2) AS monthly_approval_rate,
COUNT(DISTINCT committee) AS committees_active
FROM view_riksdagen_politician_decision_pattern
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
AND person_id = '0532213467925' -- Specific politician
GROUP BY person_id, first_name, last_name, party, decision_month
ORDER BY decision_month DESC;
4. Ministry Proposal Support Patterns
-- Which politicians are most supportive of ministry proposals
SELECT
first_name,
last_name,
party,
committee_org AS ministry,
SUM(total_decisions) AS ministry_decisions,
ROUND(AVG(approval_rate), 2) AS avg_approval_rate,
SUM(approved_decisions) AS total_approved,
SUM(rejected_decisions) AS total_rejected
FROM view_riksdagen_politician_decision_pattern
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 1
GROUP BY person_id, first_name, last_name, party, committee_org
HAVING SUM(total_decisions) >= 3
ORDER BY avg_approval_rate DESC, ministry_decisions DESC
LIMIT 30;
5. Cross-Party Collaboration on Decisions
-- Identify decisions with broad cross-party approval
WITH decision_aggregates AS (
SELECT
committee,
decision_month,
COUNT(DISTINCT party) AS parties_involved,
ROUND(AVG(approval_rate), 2) AS avg_approval_across_parties,
SUM(total_decisions) AS total_decisions
FROM view_riksdagen_politician_decision_pattern
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY committee, decision_month
)
SELECT
committee,
decision_month,
parties_involved,
avg_approval_across_parties,
total_decisions,
CASE
WHEN parties_involved >= 6 AND avg_approval_across_parties >= 70 THEN 'STRONG_CONSENSUS'
WHEN parties_involved >= 4 AND avg_approval_across_parties >= 60 THEN 'MODERATE_CONSENSUS'
ELSE 'LIMITED_CONSENSUS'
END AS consensus_level
FROM decision_aggregates
WHERE total_decisions >= 5
ORDER BY avg_approval_across_parties DESC, parties_involved DESC
LIMIT 20;
Performance Characteristics
- Query Time: 100-200ms (complex aggregation with joins)
- Indexes Used:
idx_person_ref_person_id,idx_doc_proposal_committee,idx_doc_data_made_public_date - Data Volume: ~50,000 rows (depends on proposal data volume)
- Refresh Frequency: Real-time (standard view)
- Optimization: Candidate for materialization in future version
Data Sources
- Primary Table:
document_proposal_data(all proposal decisions) - Joined Tables:
document_proposal_container(proposal linkage)document_status_container(status linkage)document_data(dates and metadata)document_person_reference_co_0/da_0(person/party info)person_data(politician identification)
Dependencies
- No view dependencies (built directly on source tables)
- Complements:
view_riksdagen_party_decision_flow(party-level view) - Used by: Politician scorecards, committee analysis dashboards
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PoliticianLowProductivity (P-06): Decision count metrics
- PoliticianIneffectiveVoting (P-02): Approval rate context
- Committee Effectiveness: Specialist identification
Intelligence Applications
This view supports multiple analytical frameworks from DATA_ANALYSIS_INTOP_OSINT.md:
| Analysis Framework | Use Case | Example Application | Link |
|---|---|---|---|
| Temporal Analysis | Track decision effectiveness over time | Monitor politician approval rate trends monthly | Framework Docs |
| Comparative Analysis | Politician vs. party/committee benchmarks | Compare individual approval rates to committee averages | Framework Docs |
| Pattern Recognition | Committee specialization clustering | Identify specialists vs. generalists | Framework Docs |
| Predictive Intelligence | Forecast decision success probability | Predict proposal outcomes based on politician history | Framework Docs |
Intelligence Products Generated:
- π Politician Scorecards - Decision effectiveness metrics
- π Committee Specialist Reports - Expertise area identification
- π― Ministry Support Analysis - Government proposal alignment
- π€ Cross-Party Collaboration Tracking - Consensus-building identification
Data Flow: See Intelligence Data Flow Map - View to Analysis Mapping for complete data pipeline.
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Productivity Analysis: Decision volume and success metrics
- Specialization Analysis: Committee focus and expertise
- Comparative Analysis: Individual vs. party/committee benchmarks
- Temporal Analysis: Monthly decision patterns and trends
Integration with Product Features
From BUSINESS_PRODUCT_DOCUMENT.md:
- Politician Dashboard (Product Line 1): Decision effectiveness metrics
- Committee Analysis (Product Line 2): Specialist identification
- Comparative Analytics (Product Line 2): Decision success benchmarking
view_riksdagen_politician_document_daily_summary ββββ
Category: Document Views (v1.24)
Type: Materialized View
Intelligence Value: HIGH - Daily Document Productivity Tracking
Purpose
Daily aggregation of document submissions by politician, document type, and party. Enables temporal productivity analysis and tracks daily legislative activity patterns.
Key Columns
public_date: Document publication dateperson_id: Politician identifierparty: Party affiliation at time of submissiondocument_type: Type of document (motion, interpellation, etc.)total_documents: Count for that day
Sample Query: Recent Activity
SELECT person_id, first_name, last_name, party, SUM(total_documents) as docs_last_month
FROM view_riksdagen_politician_document_daily_summary
WHERE public_date >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY person_id, first_name, last_name, party
ORDER BY docs_last_month DESC
LIMIT 20;
Performance Notes
- Materialized: Refreshed daily at 02:00 UTC
- Query Time: <20ms (indexed)
- Use Case: Time-series analysis, daily productivity tracking
view_riksdagen_politician_document_summary ββββ
Category: Document Views (v1.24)
Type: Materialized View
Intelligence Value: HIGH - Career Document Statistics
Purpose
Lifetime document productivity summary per politician, categorizing by motion types (party, individual, committee, multi-party), propositions, and calculating productivity metrics.
Key Metrics
- Total Documents: Career document count
- Party Motions: Documents as party representative
- Individual Motions: Personal legislative proposals
- Activity Profile: Classification (Party-focused, Committee-focused, Individual-focused)
- Documents Per Year: Average annual productivity
Sample Query: Productivity Profiles
SELECT first_name, last_name, party, total_documents, activity_profile, docs_per_year
FROM view_riksdagen_politician_document_summary
WHERE total_documents >= 50
ORDER BY docs_per_year DESC
LIMIT 30;
Intelligence Applications
- Career productivity benchmarking
- Legislative style classification
- Long-term productivity trends
- Politician specialization analysis
Intelligence & Risk Views (Additional Documentation)
view_riksdagen_crisis_resilience_indicators βββββ
Category: Intelligence Views (v1.30)
Type: Standard View
Intelligence Value: VERY HIGH - Crisis Performance Assessment
Purpose
Evaluates politician performance during crisis periods (economic downturns, pandemics, political scandals) by analyzing voting consistency, attendance under pressure, and effectiveness during high-stakes periods.
Key Metrics
- Crisis Attendance Rate: Presence during critical periods
- Crisis Effectiveness: Win rate during high-stakes votes
- Stability Under Pressure: Consistency vs. normal periods
- Resilience Classification: HIGHLY_RESILIENT, RESILIENT, LOW_RESILIENCE
Sample Query: Crisis-Ready Politicians
SELECT person_id, first_name, last_name, party,
crisis_attendance_rate, crisis_effectiveness, resilience_classification
FROM view_riksdagen_crisis_resilience_indicators
WHERE resilience_classification IN ('HIGHLY_RESILIENT', 'RESILIENT')
ORDER BY crisis_effectiveness DESC
LIMIT 25;
Intelligence Applications
- Government crisis team selection
- Resilience forecasting
- Leadership assessment under stress
- Crisis management capability evaluation
view_riksdagen_voting_anomaly_detection βββββ
Category: Intelligence Views (v1.29)
Type: Standard View
Intelligence Value: VERY HIGH - Defection Risk & Anomaly Detection
Purpose
Identifies abnormal voting patterns, defection risks, and party discipline breakdowns using statistical anomaly detection. Flags politicians with unusual vote switching, cross-party alignment, or erratic behavior.
Key Metrics
- Anomaly Score: Statistical deviation from expected behavior (0-1 scale)
- Defection Risk Assessment: HIGH_DEFECTION_RISK, MODERATE_RISK, LOW_RISK
- Party Alignment Deviation: % votes deviating from party norm
- Discipline Classification: LOW_DISCIPLINE, MODERATE_DISCIPLINE, HIGH_DISCIPLINE
- Recent Anomalies: Count of recent unusual voting patterns
Sample Query: High Defection Risks
SELECT first_name, last_name, party, anomaly_score,
defection_risk_assessment, party_alignment_deviation, recent_anomalies
FROM view_riksdagen_voting_anomaly_detection
WHERE defection_risk_assessment = 'HIGH_DEFECTION_RISK'
OR recent_anomalies >= 3
ORDER BY anomaly_score DESC;
Intelligence Applications
- Party defection early warning
- Coalition stability monitoring
- Swing voter identification
- Discipline problem detection
Decision Flow Views (v1.35)
Total Views: 5
Intelligence Value: βββββ VERY HIGH
Primary Use Cases: Legislative effectiveness tracking, proposal outcome prediction, coalition analysis, government performance monitoring
Changelog: v1.35 Decision Intelligence Layer
Overview
The Decision Flow Views (introduced in v1.35) provide comprehensive analysis of legislative decision patterns, tracking proposal creation, processing, and outcomes across parties, politicians, ministries, and committees. These views enable intelligence assessment of:
- Party Legislative Effectiveness: Which parties achieve highest proposal approval rates
- Politician Proposal Success: Individual effectiveness in advancing legislative initiatives
- Ministry Policy Impact: Government ministry success in implementing policy agenda
- Decision Velocity: Legislative processing efficiency and bottleneck identification
- Coalition Decision Alignment: Cross-party agreement patterns for stability assessment
View Inventory
| View Name | Type | Intelligence Value | Description |
|---|---|---|---|
| view_riksdagen_party_decision_flow | Standard | βββββ | Party-level decision approval rates and patterns |
| view_riksdagen_politician_decision_pattern | Standard | βββββ | Individual politician proposal success tracking |
| view_ministry_decision_impact | Standard | βββββ | Ministry legislative effectiveness analysis |
| view_decision_temporal_trends | Standard | βββββ | Time-series decision patterns with moving averages |
| view_decision_outcome_kpi_dashboard | Standard | βββββ | Consolidated decision KPIs across all dimensions |
view_riksdagen_party_decision_flow βββββ
Category: Decision Intelligence (v1.35)
Type: Standard View
Intelligence Value: VERY HIGH - Party Legislative Effectiveness
Purpose
Tracks party-level proposal decision patterns from DOCUMENT_PROPOSAL_DATA, aggregating monthly approval rates, rejection rates, and committee activity. Enables comparative analysis of party legislative effectiveness and coalition decision alignment.
Key Metrics
- Approval Rate: Percentage of party proposals approved (bifall) vs. rejected (avslag)
- Decision Volume: Total decisions per party per month/year
- Committee Breadth: Number of distinct committees where party is active
- Temporal Trends: Month-over-month approval rate changes
- Coalition Alignment: Cross-party decision agreement patterns
Schema
| Column Name | Type | Description | Example |
|---|---|---|---|
party | VARCHAR(50) | Political party code | 'S' (Social Democrats) |
committee | VARCHAR(255) | Committee handling decisions | 'UU' (Foreign Affairs) |
decision_month | DATE | Month of aggregation (first day) | '2024-10-01' |
decision_year | INTEGER | Year of decision | 2024 |
decision_month_num | INTEGER | Month number (1-12) | 10 |
total_decisions | BIGINT | Total decisions in period | 45 |
approved_decisions | BIGINT | Decisions approved (bifall) | 32 |
rejected_decisions | BIGINT | Decisions rejected (avslag) | 8 |
other_decisions | BIGINT | Other decision outcomes | 5 |
approval_rate | NUMERIC | Approval percentage | 71.11 |
Sample Query: Party Effectiveness Ranking (Current Year)
SELECT
party,
COUNT(*) AS total_months,
ROUND(AVG(approval_rate), 2) AS avg_approval_rate,
COUNT(DISTINCT committee) AS committees_active,
SUM(total_decisions) AS total_decisions,
RANK() OVER (ORDER BY AVG(approval_rate) DESC) AS effectiveness_rank
FROM view_riksdagen_party_decision_flow
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY party
ORDER BY avg_approval_rate DESC;
Intelligence Applications
- Coalition Formation Analysis: Identify party combinations with highest joint approval rates
- Opposition Effectiveness: Measure which opposition parties achieve legislative success
- Government Strength: Track ruling coalition proposal success over time
- Committee Specialization: Determine which parties dominate specific policy areas
- Trend Detection: Early warning for declining party legislative effectiveness
Related Risk Rules
- D-01: Party Low Approval Rate - Triggers when party approval rate <30% for 3+ months
- D-05: Coalition Decision Misalignment - Detects coalition partner alignment <60%
Cross-References
- DATA_ANALYSIS_INTOP_OSINT.md - Decision Intelligence Framework
- RISK_RULES_INTOP_OSINT.md - Decision Pattern Risk Rules
view_riksdagen_politician_decision_pattern βββββ
Category: Decision Intelligence (v1.35)
Type: Standard View
Intelligence Value: VERY HIGH - Decision Effectiveness & Committee Specialization
Purpose
Tracks individual politician decision patterns from DOCUMENT_PROPOSAL_DATA, enabling analysis of politician-level proposal success rates, committee work effectiveness, and legislative productivity. Complements view_riksdagen_party_decision_flow by providing individual politician decision analytics.
Key Metrics
- Individual Approval Rate: Politician's proposal success rate
- Committee Specialization: Primary committees where politician is most active
- Legislative Productivity: Total proposals submitted per period
- Career Trajectory: Approval rate trends over time (improving vs. declining)
- Cross-Party Influence: Success rate compared to party average
Schema
| Column Name | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier | '0279865129018' |
first_name | VARCHAR(255) | Politician first name | 'Magdalena' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Party affiliation at decision time | 'S' |
committee | VARCHAR(255) | Committee handling decision | 'UU' (Foreign Affairs) |
decision_month | DATE | Month of aggregation (first day) | '2024-10-01' |
decision_year | INTEGER | Year of decision | 2024 |
decision_month_num | INTEGER | Month number (1-12) | 10 |
total_decisions | BIGINT | Total decisions in period | 45 |
approved_decisions | BIGINT | Decisions approved (bifall) | 32 |
rejected_decisions | BIGINT | Decisions rejected (avslag) | 8 |
other_decisions | BIGINT | Other decision outcomes | 5 |
approval_rate | NUMERIC | Approval percentage | 71.11 |
Sample Query: Top Performing Politicians (Minimum 10 Proposals)
SELECT
person_id,
first_name,
last_name,
party,
COUNT(DISTINCT committee) AS committees_active,
SUM(total_decisions) AS total_proposals,
ROUND(AVG(approval_rate), 2) AS avg_approval_rate,
RANK() OVER (ORDER BY AVG(approval_rate) DESC) AS effectiveness_rank
FROM view_riksdagen_politician_decision_pattern
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY person_id, first_name, last_name, party
HAVING SUM(total_decisions) >= 10
ORDER BY avg_approval_rate DESC
LIMIT 50;
Intelligence Applications
- Rising Political Stars: Identify high-performing politicians for advancement
- Committee Chair Effectiveness: Assess committee leadership performance
- Shadow Cabinet Analysis: Evaluate opposition leadership proposal success
- Legislative Mentorship: Target low-performing members for support
- Resignation Prediction: Detect declining effectiveness patterns (early warning)
Related Risk Rules
- D-02: Politician Proposal Ineffectiveness - Triggers when approval rate <20% with 10+ proposals
Cross-References
- DATA_ANALYSIS_INTOP_OSINT.md - Decision Intelligence Framework
- RISK_RULES_INTOP_OSINT.md - Decision Pattern Risk Rules
view_ministry_decision_impact βββββ
Category: Decision Intelligence (v1.35)
Type: Standard View
Intelligence Value: VERY HIGH - Government Policy Effectiveness & Coalition Stability
Purpose
Evaluates ministry-level legislative performance by tracking government proposal outcomes, approval rates, and processing times. Critical for assessing executive branch effectiveness, minister performance, and coalition stability.
β οΈ Data Quality Note: This view was affected by missing pattern matching for committee referrals.
Issue: Decision chamber pattern matching - 7,049 records were misclassified as "other"
Status: β Fixed in Liquibase changeset db-changelog-1.45.xml (added committee referral tracking)
Details: See Data Quality Analysis in README-SCHEMA-MAINTENANCE.md
Key Metrics
- Ministry Approval Rate: Success rate of ministry proposals
- Proposal Volume: Legislative activity by ministry
- Processing Efficiency: Average days from proposal to decision
- Quarterly Performance: Trend analysis for ministry effectiveness
- Policy Domain Success: Which policy areas achieve highest approval
Schema
| Column Name | Type | Description | Example |
|---|---|---|---|
ministry_code | VARCHAR(10) | Ministry abbreviation | 'FI' (Finance) |
ministry_name | VARCHAR(255) | Full ministry name | 'Finance Ministry' |
decision_year | INTEGER | Year of decision | 2024 |
decision_quarter | INTEGER | Quarter (1-4) | 3 |
total_proposals | BIGINT | Total ministry proposals | 78 |
approved_proposals | BIGINT | Approved proposals | 65 |
rejected_proposals | BIGINT | Rejected proposals | 8 |
other_outcomes | BIGINT | Other decision outcomes | 5 |
approval_rate | NUMERIC | Approval percentage | 83.33 |
avg_processing_days | NUMERIC | Average days to decision | 45.2 |
Sample Query: Ministry Performance Ranking (Last 4 Quarters)
SELECT
ministry_code,
ministry_name,
decision_year,
decision_quarter,
total_proposals,
approved_proposals,
ROUND(approval_rate, 2) AS approval_rate,
ROUND(avg_processing_days, 1) AS avg_processing_days,
CASE
WHEN approval_rate >= 85 THEN 'π’ Excellent'
WHEN approval_rate >= 70 THEN 'π‘ Good'
WHEN approval_rate >= 50 THEN 'π Moderate'
ELSE 'π΄ Concerning'
END AS performance_rating
FROM view_ministry_decision_impact
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 1
ORDER BY decision_year DESC, decision_quarter DESC, approval_rate DESC;
Intelligence Applications
- Minister Performance Evaluation: Objective assessment of minister effectiveness
- Coalition Friction Detection: Low approval rates indicate coalition disagreement
- Budget Effectiveness: Track which ministries deliver on policy promises
- Government Reshuffle: Identify underperforming ministries for cabinet changes
- Policy Priority Tracking: Monitor success of government's top policy areas
Related Risk Rules
- D-03: Ministry Declining Success Rate - Triggers when approval rate declines >20% QoQ
Cross-References
- DATA_ANALYSIS_INTOP_OSINT.md - Decision Intelligence Framework
- RISK_RULES_INTOP_OSINT.md - Decision Pattern Risk Rules
view_decision_temporal_trends βββββ
Category: Decision Intelligence (v1.35)
Type: Standard View
Intelligence Value: VERY HIGH - Temporal Decision Pattern Analysis
Purpose
Provides time-series analysis of legislative decision patterns with moving averages for trend detection. Enables identification of seasonal patterns, decision volume anomalies, and processing efficiency trends.
β οΈ Data Quality Note: This view was affected by missing pattern matching for committee referrals.
Issue: Decision chamber pattern matching - 7,049 records were misclassified as "other"
Status: β Fixed in Liquibase changeset db-changelog-1.45.xml (added committee referral tracking)
Details: See Data Quality Analysis in README-SCHEMA-MAINTENANCE.md
Key Metrics
- Daily Decision Volume: Number of decisions per day
- Moving Averages: 7-day and 30-day smoothed trends
- Volume Anomalies: Statistically significant spikes/drops
- Seasonal Patterns: Day-of-week and month effects
- Processing Momentum: Acceleration/deceleration in legislative activity
Schema
| Column Name | Type | Description | Example |
|---|---|---|---|
decision_day | DATE | Date of decisions | '2024-10-15' |
daily_decisions | BIGINT | Total decisions on date | 127 |
moving_avg_7d | NUMERIC | 7-day moving average | 98.43 |
moving_avg_30d | NUMERIC | 30-day moving average | 85.67 |
day_of_week | INTEGER | Day of week (0=Sunday) | 2 (Tuesday) |
week_of_year | INTEGER | Week number | 42 |
month | INTEGER | Month number | 10 |
Sample Query: Decision Volume Anomaly Detection (Z-Score > 2)
WITH volume_stats AS (
SELECT
AVG(daily_decisions) AS avg_volume,
STDDEV(daily_decisions) AS stddev_volume
FROM view_decision_temporal_trends
WHERE decision_day >= CURRENT_DATE - INTERVAL '90 days'
),
anomaly_calc AS (
SELECT
vdt.decision_day,
vdt.daily_decisions,
vdt.moving_avg_7d,
ROUND(vs.avg_volume, 2) AS baseline_avg,
ROUND(COALESCE((vdt.daily_decisions - vs.avg_volume) / NULLIF(vs.stddev_volume, 0), 0), 2) AS z_score
FROM view_decision_temporal_trends vdt
CROSS JOIN volume_stats vs
WHERE vdt.decision_day >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT
decision_day,
daily_decisions,
moving_avg_7d,
baseline_avg,
z_score,
CASE
WHEN z_score > 2 THEN 'β οΈ HIGH ANOMALY'
WHEN z_score < -2 THEN 'β οΈ LOW ANOMALY'
ELSE 'β
Normal'
END AS anomaly_status
FROM anomaly_calc
ORDER BY ABS(z_score) DESC;
Intelligence Applications
- Crisis Response Monitoring: Detect emergency legislative activity spikes
- Process Bottleneck Detection: Identify unusual decision processing delays
- Seasonal Planning: Resource allocation based on historical patterns
- Media Monitoring: Validate claims of legislative "gridlock" or "rush"
- Pre-Recess Activity: Track decision surge before parliamentary breaks
Related Risk Rules
- D-04: Decision Volume Anomaly - Triggers when z-score > 2 or < -2
Cross-References
- DATA_ANALYSIS_INTOP_OSINT.md - Decision Intelligence Framework
- RISK_RULES_INTOP_OSINT.md - Decision Pattern Risk Rules
Decision Flow Views: Common Usage Patterns
Pattern 1: Coalition Stability Assessment
Combine party decision alignment with ministry approval rates to assess coalition health.
-- Coalition Stability Score (0-100)
SELECT
'Coalition Stability' AS metric,
ROUND(AVG(pdf.approval_rate) * 0.6 + AVG(mdi.approval_rate) * 0.4, 2) AS stability_score
FROM view_riksdagen_party_decision_flow pdf
CROSS JOIN view_ministry_decision_impact mdi
WHERE pdf.party IN ('S', 'C', 'V', 'MP') -- Current coalition
AND pdf.decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
AND mdi.decision_year = EXTRACT(YEAR FROM CURRENT_DATE);
Pattern 2: Politician Career Trajectory Analysis
Track individual politician approval rate trends to predict career advancement or decline.
-- Politician Career Momentum (Improving vs. Declining)
WITH quarterly_performance AS (
SELECT
person_id,
first_name,
last_name,
decision_year,
EXTRACT(QUARTER FROM decision_month) AS quarter,
AVG(approval_rate) AS quarterly_approval_rate
FROM view_riksdagen_politician_decision_pattern
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 1
GROUP BY person_id, first_name, last_name, decision_year, quarter
)
SELECT
person_id,
first_name,
last_name,
COUNT(*) AS quarters_tracked,
ROUND(AVG(quarterly_approval_rate), 2) AS avg_approval_rate,
ROUND(REGR_SLOPE(quarterly_approval_rate, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY decision_year, quarter))::NUMERIC, 4) AS trend_slope,
CASE
WHEN REGR_SLOPE(quarterly_approval_rate, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY decision_year, quarter)) > 2 THEN 'π Rising Star'
WHEN REGR_SLOPE(quarterly_approval_rate, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY decision_year, quarter)) < -2 THEN 'π Declining'
ELSE 'β‘οΈ Stable'
END AS career_trajectory
FROM quarterly_performance
GROUP BY person_id, first_name, last_name
HAVING COUNT(*) >= 4
ORDER BY trend_slope DESC;
Pattern 3: Ministry Performance Benchmarking
Compare ministry approval rates to identify high/low performers for cabinet assessment.
-- Ministry Performance Scorecard with Peer Comparison
WITH ministry_stats AS (
SELECT
AVG(approval_rate) AS avg_approval_rate,
STDDEV(approval_rate) AS stddev_approval_rate
FROM view_ministry_decision_impact
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
)
SELECT
mdi.ministry_code,
mdi.ministry_name,
ROUND(mdi.approval_rate, 2) AS approval_rate,
ROUND(ms.avg_approval_rate, 2) AS ministry_average,
ROUND((mdi.approval_rate - ms.avg_approval_rate) / NULLIF(ms.stddev_approval_rate, 0), 2) AS z_score,
CASE
WHEN (mdi.approval_rate - ms.avg_approval_rate) / NULLIF(ms.stddev_approval_rate, 0) > 1 THEN 'βββββ Excellent'
WHEN (mdi.approval_rate - ms.avg_approval_rate) / NULLIF(ms.stddev_approval_rate, 0) > 0 THEN 'ββββ Above Average'
WHEN (mdi.approval_rate - ms.avg_approval_rate) / NULLIF(ms.stddev_approval_rate, 0) > -1 THEN 'βββ Average'
ELSE 'ββ Below Average'
END AS performance_tier
FROM view_ministry_decision_impact mdi
CROSS JOIN ministry_stats ms
WHERE mdi.decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
ORDER BY z_score DESC;
Ministry & Government Views (Complete Documentation)
view_ministry_effectiveness_trends βββββ
Category: Ministry Performance (v1.29)
Type: Standard View
Intelligence Value: VERY HIGH - Government Executive Performance
Purpose
Tracks quarterly ministry productivity including legislative output (propositions, government bills), staffing levels, and performance trends. Identifies declining ministries requiring intervention.
Key Metrics
- Documents Produced: Quarterly document output
- Legislative Documents: Props + government bills count
- Active Members: Ministry staff count
- Documents Per Member: Productivity ratio
- Productivity Level: HIGHLY_PRODUCTIVE, PRODUCTIVE, MODERATE, LOW
- Stagnation Indicator: SEVERE_DECLINE, IMPROVING, STABLE
- Effectiveness Assessment: Narrative performance evaluation
Sample Query: Ministry Performance Dashboard
SELECT name, period_start, documents_produced, legislative_documents,
active_members, documents_per_member, productivity_level, effectiveness_assessment
FROM view_ministry_effectiveness_trends
WHERE period_start >= DATE_TRUNC('year', CURRENT_DATE)
ORDER BY documents_produced DESC;
Intelligence Applications
- Government productivity monitoring
- Ministry intervention prioritization
- Executive performance scorecards
- Cabinet effectiveness evaluation
view_ministry_productivity_matrix βββββ
Category: Ministry Performance (v1.29)
Type: Standard View
Intelligence Value: VERY HIGH - Comparative Ministry Analysis
Purpose
Matrix comparison of all ministries across productivity metrics, enabling cross-ministry benchmarking and relative performance assessment.
Key Metrics
- Relative Productivity: Ministry rank by output
- Productivity Percentile: Position in distribution
- Benchmark Comparison: vs. ministry average
- Efficiency Rating: Output per staff member
- Performance Tier: TIER_1 (top 25%), TIER_2, TIER_3, TIER_4 (bottom 25%)
Sample Query: Ministry Rankings
SELECT ministry_name, total_documents_ytd, staff_count,
efficiency_rating, performance_tier, productivity_percentile
FROM view_ministry_productivity_matrix
ORDER BY productivity_percentile DESC;
Intelligence Applications
- Ministry benchmarking
- Resource allocation decisions
- Performance tier identification
- Cabinet reshuffle intelligence
view_ministry_risk_evolution βββββ
Category: Ministry Risk (v1.30)
Type: Standard View
Intelligence Value: VERY HIGH - Ministry Risk Tracking
Purpose
Temporal tracking of ministry risk indicators including output decline, understaffing, legislative inactivity, and trend deterioration. Early warning system for ministry performance problems.
Key Metrics
- Risk Score: Aggregate ministry risk points
- Risk Severity: CRITICAL, MAJOR, MINOR
- Output Risk: Document production concerns
- Staffing Risk: Understaffing indicators
- Trend Risk: Negative performance trajectory
- Risk Trajectory: ESCALATING, STABLE, IMPROVING
Sample Query: High-Risk Ministries
SELECT ministry_name, quarter, risk_score, risk_severity,
output_risk, staffing_risk, trend_risk, risk_trajectory
FROM view_ministry_risk_evolution
WHERE risk_severity IN ('CRITICAL', 'MAJOR')
OR risk_trajectory = 'ESCALATING'
ORDER BY risk_score DESC;
Intelligence Applications
- Ministry crisis detection
- Intervention prioritization
- Government stability assessment
- Cabinet risk monitoring
view_riksdagen_goverment ββββ
Category: Government Structure (v1.1)
Type: Standard View
Intelligence Value: HIGH - Government Composition Tracking
Purpose
Tracks current government structure, cabinet composition, party representation in government, and government formation dates. Core reference for executive branch analysis.
Key Columns
government_id: Unique government identifierformed_date: Government formation datedissolved_date: End date (NULL if current)prime_minister: PM namecoalition_parties: Parties in government (array)cabinet_size: Number of ministersmajority_status: MAJORITY, MINORITY, COALITION
Sample Query: Current Government
SELECT *
FROM view_riksdagen_goverment
WHERE dissolved_date IS NULL;
view_riksdagen_goverment_proposals ββββ
Category: Government Activity (v1.23)
Type: Standard View
Intelligence Value: HIGH - Executive Legislative Initiative
Purpose
Tracks government legislative proposals (propositions), passage rates, committee assignments, and approval status. Measures government legislative effectiveness.
Key Metrics
- Total Proposals: Government-initiated legislation count
- Approved Proposals: Passed by parliament
- Pending Proposals: Under consideration
- Rejection Rate: Failed proposals percentage
- Average Processing Time: Days from submission to decision
Sample Query: Recent Government Legislation
SELECT proposal_id, title, submitted_date, status, committee_assigned
FROM view_riksdagen_goverment_proposals
WHERE submitted_date >= CURRENT_DATE - INTERVAL '6 months'
ORDER BY submitted_date DESC;
view_riksdagen_goverment_role_member ββββ
Category: Government Membership (v1.1)
Type: Standard View
Intelligence Value: HIGH - Cabinet Personnel Tracking
Purpose
Maps individual politicians to government roles (minister positions), tracking appointment/dismissal dates, role durations, and government turnover.
Key Columns
person_id: Minister identifierrole_code: Ministry/position coderole_title: Minister title (e.g., "Utbildningsminister")from_date: Appointment dateto_date: End date (NULL if current)days_in_role: Duration of appointment
Sample Query: Current Cabinet
SELECT first_name, last_name, party, role_title, from_date, days_in_role
FROM view_riksdagen_goverment_role_member
WHERE to_date IS NULL
ORDER BY role_title;
view_riksdagen_goverment_roles βββ
Category: Government Structure (v1.1)
Type: Standard View
Intelligence Value: MEDIUM - Government Role Definitions
Purpose
Catalog of government roles, ministries, and position definitions. Reference data for government structure analysis.
Key Columns
role_code: Unique role identifierrole_title: Official role nameministry_category: Ministry groupingrole_level: CABINET, STATE_SECRETARY, etc.
Purpose
Aggregates ministry/government department data from assignment_data, providing ministry-level statistics including total assignments, member counts, activity periods, and current operational status. Serves as the foundational reference for ministry-level comparative analysis and government structure tracking.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
ministry_id | VARCHAR(50) | Ministry organization code | 'U', 'Ju', 'Fi', 'FΓΆ' |
ministry_name | VARCHAR(255) | Official ministry department name | 'Utrikesdepartementet' |
role_code | VARCHAR(50) | Government role code filter | 'MINISTER', 'STATSSEKRETERARE' |
total_assignments | INTEGER | Total role assignments to ministry | 47 |
total_members | INTEGER | Unique individuals assigned (COUNT DISTINCT) | 23 |
first_assignment_date | DATE | Earliest assignment date | '1995-01-01' |
last_assignment_date | DATE | Most recent assignment date | '2024-12-31' |
is_active | BOOLEAN | Ministry currently operational (to_date >= CURRENT_DATE or NULL) | TRUE |
Swedish Government Ministries
| Code | Ministry Name (Swedish) | English Name | Typical Cabinet Size |
|---|---|---|---|
| Ju | Justitiedepartementet | Ministry of Justice | 1-2 ministers |
| U | Utrikesdepartementet | Ministry of Foreign Affairs | 1-2 ministers |
| FΓΆ | FΓΆrsvarsdepartementet | Ministry of Defence | 1 minister |
| Fi | Finansdepartementet | Ministry of Finance | 1-2 ministers |
| U | Utbildningsdepartementet | Ministry of Education | 1-2 ministers |
| S | Socialdepartementet | Ministry of Health and Social Affairs | 1-3 ministers |
Note: StatsrΓ₯dsberedningen (Prime Minister's Office) is also tracked as a special ministry entity.
Example Queries
1. Current Active Ministries
SELECT
ministry_id,
ministry_name,
total_members,
total_assignments,
first_assignment_date,
last_assignment_date
FROM view_riksdagen_ministry
WHERE is_active = TRUE
ORDER BY total_members DESC;
Output:
ministry_id | ministry_name | total_members | total_assignments | first_assignment_date | last_assignment_date
-------------+-------------------------+---------------+-------------------+----------------------+---------------------
Fi | Finansdepartementet | 23 | 47 | 1995-01-01 | 2024-12-31
Ju | Justitiedepartementet | 19 | 38 | 1996-03-15 | 2024-11-30
U | Utrikesdepartementet | 18 | 35 | 1995-02-20 | 2024-10-15
2. Ministry Longevity Analysis
SELECT
ministry_id,
ministry_name,
EXTRACT(YEAR FROM AGE(last_assignment_date, first_assignment_date)) AS years_active,
total_members,
ROUND(total_assignments::NUMERIC / total_members, 2) AS avg_assignments_per_person
FROM view_riksdagen_ministry
WHERE is_active = TRUE
ORDER BY years_active DESC;
3. Ministry Activity Timeline
SELECT
ministry_name,
first_assignment_date,
last_assignment_date,
is_active,
total_members,
CASE
WHEN is_active THEN 'Currently operational'
ELSE 'Historical ministry'
END AS status
FROM view_riksdagen_ministry
ORDER BY first_assignment_date;
Intelligence Applications
Government Restructuring Analysis:
- Track ministry formation and dissolution patterns
- Identify organizational changes in government structure
- Monitor ministry expansion/contraction over time
Cabinet Stability Assessment:
- Compare member turnover rates across ministries
- Identify high-churn ministries (political instability indicator)
- Track long-term vs. short-term ministerial appointments
Comparative Ministry Analysis:
- Compare ministry sizes across government periods
- Analyze resource allocation patterns (member counts)
- Identify dominant vs. peripheral ministries
Dependencies
Source Data:
assignment_data- Raw assignment records filtered for ministry roles
Related Views:
view_riksdagen_goverment_roles- Individual role definitionsview_riksdagen_goverment_role_member- Person-to-ministry mappingsview_ministry_decision_impact- Ministry legislative effectiveness
Performance Characteristics
- Query Complexity: Medium (GROUP BY aggregation)
- Data Volume: Low (< 100 rows - one per ministry/role combination)
- Refresh Frequency: Static (updated when assignment_data changes)
- Index Recommendations: None required (small result set)
Usage Notes
Filter Criteria: The view includes assignments where:
role_codecontains 'MINISTER' (e.g., MINISTER, UTRIKESMINISTER)detailcontains 'departementet' (Swedish for "department")detailequals 'StatsrΓ₯dsberedningen' (Prime Minister's Office)
Active Status Logic: Ministry considered active if:
last_assignment_date >= CURRENT_DATE(has recent assignments)last_assignment_date IS NULL(ongoing assignments)
view_ministry_decision_impact βββββ
Category: Ministry Decision Analysis (v1.35)
Type: Standard View
Intelligence Value: VERY HIGH - Government Policy Effectiveness & Coalition Stability
Purpose
Tracks ministry-initiated proposal outcomes from DOCUMENT_PROPOSAL_DATA, enabling analysis of which government ministries have the highest/lowest success rates for their legislative proposals. Provides comprehensive insight into government policy effectiveness, ministry-parliament relations, and coalition stability indicators.
Key Metrics
- ministry_code: Government ministry/department identifier (org)
- committee: Parliamentary committee handling the proposal
- decision_type: Type of decision rendered
- decision_quarter: Quarter when decision was made (aggregated)
- decision_year: Year of decision
- quarter_num: Quarter number (1-4) for sorting and filtering
- total_proposals: Total ministry proposals in period
- approved_proposals: Count of approved proposals (bifall, godkΓ€nt, bifalla)
- rejected_proposals: Count of rejected proposals (avslag, avslΓ₯)
- referred_back_proposals: Count of proposals referred back to committee (Γ₯terfΓΆrvisning, Γ₯terfΓΆrvisa)
- other_decisions: Count of other decisions (not approved/rejected/referred back)
- approval_rate: Percentage of proposals approved (%)
- rejection_rate: Percentage of proposals rejected (%)
- earliest_proposal_date: Start of period
- latest_proposal_date: End of period
Sample Query: Ministry Success Rates (Last 2 Years)
-- Ministry proposal success rates comparison
SELECT ministry_code,
SUM(total_proposals) AS total,
ROUND(AVG(approval_rate), 2) AS avg_approval_rate,
ROUND(AVG(rejection_rate), 2) AS avg_rejection_rate,
COUNT(DISTINCT committee) AS committees_worked_with
FROM view_ministry_decision_impact
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 1
GROUP BY ministry_code
ORDER BY avg_approval_rate DESC;
Sample Query: Quarterly Ministry Performance Trends
-- Track ministry performance trends over time
SELECT ministry_code, decision_year, quarter_num,
total_proposals, approval_rate, rejection_rate
FROM view_ministry_decision_impact
WHERE ministry_code = 'U' -- Example: Ministry of Foreign Affairs
AND decision_year >= 2020
ORDER BY decision_year DESC, quarter_num DESC;
Sample Query: Committee-Ministry Relationship Analysis
-- Which committees approve ministry proposals most frequently
SELECT committee, ministry_code,
SUM(total_proposals) AS proposals,
ROUND(AVG(approval_rate), 2) AS avg_approval
FROM view_ministry_decision_impact
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 2
GROUP BY committee, ministry_code
HAVING SUM(total_proposals) >= 5 -- At least 5 proposals
ORDER BY avg_approval DESC;
Intelligence Applications
-
Government Policy Effectiveness:
- Identify ministries with low approval rates indicating policy effectiveness issues
- Track which ministries have strongest parliamentary support
- Monitor government legislative success over time
-
Coalition Stability Analysis:
- Low ministry approval rates may signal coalition tensions
- Track whether government proposals face increasing rejection
- Identify at-risk ministries with declining success rates
-
Committee-Ministry Relations:
- Analyze which committees are most supportive/critical of specific ministries
- Identify bottlenecks where ministry proposals stall
- Map institutional relationships between executive and legislative branches
-
Temporal Trend Analysis:
- Detect declining ministry effectiveness over quarters/years
- Forecast future approval rates based on historical patterns
- Identify seasonal variations in ministry legislative success
-
Policy Domain Success Patterns:
- Compare success rates across different policy domains (ministries)
- Identify high-performing vs. struggling ministries
- Resource allocation and capacity assessment
Related Views
- view_riksdagen_party_decision_flow (Issue Hack23/cia#7918) - Party-level decision patterns
- view_riksdagen_politician_decision_pattern (Issue Hack23/cia#7919) - Individual politician decisions
- view_decision_temporal_trends (Issue Hack23/cia#7922) - Temporal decision analysis
- view_ministry_effectiveness_trends - Broader ministry performance metrics
- view_riksdagen_goverment_proposals - Government legislative proposals tracking
Complementary Analysis
This view complements the existing ministry effectiveness views by adding decision outcome tracking:
- view_ministry_effectiveness_trends: Tracks document productivity
- view_ministry_productivity_matrix: Compares ministry output
- view_ministry_risk_evolution: Monitors ministry risk indicators
- view_ministry_decision_impact: Adds proposal success/failure outcomes β NEW
Together, these views provide comprehensive government performance intelligence spanning productivity, risk, and legislative effectiveness.
view_riksdagen_politician_career_trajectory βββββ
Category: Politician Intelligence Views (v1.55)
Type: Standard View
Intelligence Value: VERY HIGH - Career Pattern Detection & Predictive Analytics
Changelog: v1.55 Career Trajectory Tracking
Purpose
Tracks individual politician performance evolution across election cycles (2002-2026+), enabling career pattern detection, performance trend analysis, and resignation risk prediction. Provides META/META-level historical analysis with election cycle context for comprehensive career trajectory understanding.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Kinberg Batra' |
party | VARCHAR(50) | Current party affiliation | 'M' |
election_year | INTEGER | Election cycle year (2002-2026) | 2018 |
career_cycle_number | INTEGER | Sequential cycle in career | 3 |
total_cycles | BIGINT | Total election cycles active | 5 |
career_start_year | INTEGER | First election cycle | 2006 |
career_end_year | INTEGER | Latest election cycle | 2022 |
ballot_count | BIGINT | Votes cast in this cycle | 847 |
attendance_rate | NUMERIC | Attendance % (vs absences) | 94.3 |
win_rate | NUMERIC | Win % on party alignment votes | 87.2 |
leadership_roles | BIGINT | Leadership positions held | 3 |
documents_authored | BIGINT | Documents authored | 42 |
avg_career_attendance | NUMERIC | Career average attendance | 91.5 |
performance_vs_baseline | NUMERIC | Current vs career average | +2.8 |
career_stage | VARCHAR(50) | 'EARLY_CAREER', 'MID_CAREER', 'LATE_CAREER' | 'MID_CAREER' |
performance_trend | VARCHAR(50) | 'IMPROVING', 'DECLINING', 'STABLE', 'NEW_ENTRY' | 'IMPROVING' |
career_pattern | VARCHAR(50) | Overall pattern classification | 'RISING_STAR' |
Career Pattern Classification
| Pattern | Criteria | Intelligence Value |
|---|---|---|
| PEAK_PERFORMANCE | High attendance (>90%), stable trend, mid-late career | Retention target, mentorship candidate |
| RISING_STAR | Improving trend, early-mid career, above baseline | Promotion candidate, future leader |
| LATE_CAREER_DECLINE | Declining trend, late career, below baseline | Retirement risk, succession planning |
| STRUGGLING_NEWCOMER | Low attendance (<70%), new entry, first cycle | Support needed, attrition risk |
| CONSISTENT | Stable trend, near baseline, multiple cycles | Reliable performer, backbone |
Sample Queries
1. Identify Rising Stars (Early Career High Performers)
SELECT
first_name,
last_name,
party,
career_stage,
performance_trend,
career_pattern,
attendance_rate,
performance_vs_baseline
FROM view_riksdagen_politician_career_trajectory
WHERE career_pattern = 'RISING_STAR'
AND election_year = 2022
ORDER BY performance_vs_baseline DESC
LIMIT 20;
2. Track Individual Career Evolution
SELECT
election_year,
career_cycle_number,
attendance_rate,
win_rate,
leadership_roles,
performance_trend,
career_pattern
FROM view_riksdagen_politician_career_trajectory
WHERE person_id = '0532213467925'
ORDER BY election_year;
3. Retirement Risk Analysis (Late Career Decline)
SELECT
first_name,
last_name,
party,
career_start_year,
total_cycles,
attendance_rate,
performance_vs_baseline,
career_pattern
FROM view_riksdagen_politician_career_trajectory
WHERE career_pattern = 'LATE_CAREER_DECLINE'
AND election_year = 2022
AND total_cycles >= 4
ORDER BY attendance_rate ASC;
Intelligence Applications
- Predictive Intelligence (Framework 4): Resignation risk prediction based on declining trends
- Talent Management: Identify rising stars and succession planning candidates
- Performance Analysis: Compare early career vs late career effectiveness
- Party Strategy: Assess member retention risks and renewal needs
- Coalition Analysis: Track influential politician trajectory changes
Integration Points
- Feeds into Predictive Intelligence Framework (Framework 4) for career forecasting
- Complements view_riksdagen_politician_longevity_analysis for retention risk assessment
- Links to view_riksdagen_politician_role_evolution for career progression patterns
- Used by view_politician_risk_summary for comprehensive risk scoring
view_riksdagen_politician_role_evolution βββββ
Category: Politician Intelligence Views (v1.55)
Type: Standard View
Intelligence Value: VERY HIGH - Career Progression & Advancement Tracking
Changelog: v1.55 Role Evolution Tracking
Purpose
Tracks politician role progression through the political hierarchy, measuring advancement velocity between consecutive roles, and identifying career peaks and progression patterns (backbencher β committee β chair β minister). Critical for understanding power structure evolution and identifying fast-track careers.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Ebba' |
last_name | VARCHAR(255) | Politician last name | 'Busch' |
party | VARCHAR(50) | Party affiliation | 'KD' |
role_code | VARCHAR(255) | Role identifier | 'Partiledare' |
role_tier | VARCHAR(50) | Role classification | 'PARTY_LEADER' |
role_weight | INTEGER | Role importance score (50-1000) | 900 |
role_start | DATE | Role start date | 2015-04-25 |
role_end | DATE | Role end date | 2022-09-19 |
role_start_year | INTEGER | Start year | 2015 |
role_end_year | INTEGER | End year | 2022 |
role_instances | BIGINT | Times held this role | 1 |
total_days_in_role | INTEGER | Total days in role | 2704 |
years_in_role | INTEGER | Total years | 7 |
is_current_role | BOOLEAN | Currently active | FALSE |
role_sequence | BIGINT | Role order in career | 3 |
peak_role_weight | INTEGER | Highest role achieved | 900 |
career_first_year | INTEGER | Career start | 2002 |
career_last_year | INTEGER | Career end/current | 2022 |
progression_pattern | VARCHAR(50) | Career trajectory | 'CAREER_PEAK' |
career_level | VARCHAR(50) | Overall achievement level | 'TOP_LEADERSHIP' |
advancement_velocity | NUMERIC | Role weight increase per year | 42.50 |
Role Tier Hierarchy & Weights
| Tier | Weight | Roles | Example |
|---|---|---|---|
| MINISTER | 1000 | Government ministers, Prime Minister | 'Statsminister', 'Finansminister' |
| SPEAKER | 800 | Parliament Speaker, Vice Speakers | 'Talman', 'FΓΆrste vice talman' |
| PARTY_LEADER | 900 | Party leaders | 'Partiledare' |
| COMMITTEE_CHAIR | 600 | Committee chairs | 'OrdfΓΆrande' |
| COMMITTEE_VICE_CHAIR | 500 | Committee vice chairs | 'Vice ordfΓΆrande' |
| COMMITTEE_MEMBER | 400 | Committee members | 'Ledamot' |
| MP | 300 | Parliament members | 'Riksdagsledamot' |
| SUBSTITUTE | 100 | Substitute members | 'Suppleant' |
Progression Patterns
| Pattern | Description | Career Implication |
|---|---|---|
| ASCENDING | Steady upward progression | Successful career, increasing responsibility |
| CAREER_PEAK | Reached peak role weight | At highest achievement level |
| DESCENDING | Moving to lower tier roles | Career wind-down or party loss |
| LATERAL | Same tier, different roles | Specialization, no advancement |
| PEAK_ROLE | Highest weighted role achieved | Career pinnacle identified |
Sample Queries
1. Fast-Track Careers (High Advancement Velocity)
SELECT
first_name,
last_name,
party,
role_tier,
advancement_velocity,
career_first_year,
peak_role_weight,
progression_pattern
FROM view_riksdagen_politician_role_evolution
WHERE advancement_velocity > 50
AND career_level IN ('TOP_LEADERSHIP', 'SENIOR_LEADERSHIP')
ORDER BY advancement_velocity DESC
LIMIT 20;
2. Role Progression Timeline
SELECT
role_start_year,
role_tier,
role_code,
role_weight,
years_in_role,
progression_pattern
FROM view_riksdagen_politician_role_evolution
WHERE person_id = '0532213467925'
ORDER BY role_start_year;
3. Career Peak Analysis by Party
SELECT
party,
COUNT(*) FILTER (WHERE career_level = 'TOP_LEADERSHIP') AS top_leaders,
COUNT(*) FILTER (WHERE career_level = 'SENIOR_LEADERSHIP') AS senior_leaders,
AVG(peak_role_weight) AS avg_peak_weight,
AVG(advancement_velocity) AS avg_velocity
FROM view_riksdagen_politician_role_evolution
WHERE progression_pattern != 'LATERAL'
GROUP BY party
ORDER BY avg_peak_weight DESC;
Intelligence Applications
- Succession Planning: Identify politicians approaching career peaks
- Talent Pipeline: Track advancement velocity for fast-trackers
- Power Structure Mapping: Visualize role transitions and hierarchy
- Career Forecasting: Predict next role based on progression patterns
- Comparative Analysis: Benchmark advancement speeds across parties
Integration Points
- Links to view_riksdagen_politician_career_trajectory for performance correlation
- Feeds Predictive Intelligence Framework for promotion probability scoring
- Complements view_riksdagen_politician_experience_summary for role weighting
- Used in Network Analysis for power structure visualization
view_riksdagen_politician_longevity_analysis βββββ
Category: Politician Intelligence Views (v1.55)
Type: Standard View
Intelligence Value: VERY HIGH - Retention Risk & Career Duration Analytics
Changelog: v1.55 Longevity Analysis
Purpose
Comprehensive career longevity and activity pattern analysis measuring politician career duration, engagement levels, and identifying retention risks for active politicians. Provides dynamic continuity scores that work across any evaluation date using career span calculations.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Unique politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Margot' |
last_name | VARCHAR(255) | Politician last name | 'WallstrΓΆm' |
party | VARCHAR(50) | Party affiliation | 'S' |
status | VARCHAR(50) | Current status | 'active', 'retired' |
born_year | INTEGER | Birth year | 1953 |
career_start_date | DATE | First activity date | 1988-10-03 |
career_end_date | DATE | Last activity date | 2022-09-15 |
first_activity_year | INTEGER | First election cycle | 1988 |
last_activity_year | INTEGER | Last election cycle | 2022 |
total_career_days | INTEGER | Total career days | 12396 |
total_career_years | NUMERIC | Total years active | 33.95 |
age_at_career_start | INTEGER | Age when started | 35 |
age_at_career_end | INTEGER | Current age or age at exit | 69 |
election_cycles_active | BIGINT | Number of cycles participated | 8 |
total_votes_cast | BIGINT | Lifetime votes cast | 6842 |
total_assignments | BIGINT | Total assignments held | 18 |
is_currently_active | BOOLEAN | Currently serving | TRUE |
avg_votes_per_year | NUMERIC | Voting activity rate | 201.5 |
avg_assignments_per_year | NUMERIC | Assignment turnover | 0.53 |
career_continuity_score | NUMERIC | % of possible cycles active | 88.9 |
longevity_category | VARCHAR(50) | Duration classification | 'VETERAN_20_PLUS' |
activity_level | VARCHAR(50) | Engagement classification | 'VERY_ACTIVE' |
continuity_pattern | VARCHAR(50) | Career consistency | 'CONTINUOUS' |
career_life_stage | VARCHAR(50) | Age-based classification | 'SENIOR_ACTIVE' |
retention_risk | VARCHAR(50) | Risk assessment for active | 'HIGH_RETIREMENT_RISK' |
Longevity Categories
| Category | Criteria | Typical Profile |
|---|---|---|
| VETERAN_20_PLUS | 20+ years | Elder statesmen, institutional memory |
| LONG_SERVICE_15_20 | 15-20 years | Senior experienced politicians |
| ESTABLISHED_10_15 | 10-15 years | Established, experienced members |
| MID_CAREER_5_10 | 5-10 years | Mid-career, proven track record |
| JUNIOR_2_5 | 2-5 years | Junior members, building experience |
| NEWCOMER_UNDER_2 | <2 years | New entrants, learning phase |
Activity Levels
| Level | Votes/Year | Description |
|---|---|---|
| VERY_ACTIVE | 300+ | Highly engaged, consistent participation |
| ACTIVE | 200-299 | Regular participation, good attendance |
| MODERATE | 100-199 | Moderate engagement, average attendance |
| LOW_ACTIVITY | 50-99 | Below average participation |
| MINIMAL | <50 | Very low engagement, risk indicator |
Retention Risk Assessment
| Risk Level | Criteria | Action Required |
|---|---|---|
| HIGH_RETIREMENT_RISK | 15+ years, age 60+, veteran | Succession planning critical |
| MODERATE_ATTRITION_RISK | 10+ years, <150 votes/year | Engagement support needed |
| EARLY_EXIT_RISK | <3 years, <200 votes/year | Onboarding and support |
| ENGAGEMENT_RISK | Continuity <60%, any duration | Re-engagement strategies |
| LOW_RISK | Active, high engagement, stable | Retention secure |
Sample Queries
1. High Retirement Risk (Succession Planning)
SELECT
first_name,
last_name,
party,
total_career_years,
age_at_career_end,
longevity_category,
retention_risk,
avg_votes_per_year
FROM view_riksdagen_politician_longevity_analysis
WHERE retention_risk = 'HIGH_RETIREMENT_RISK'
AND is_currently_active = TRUE
ORDER BY total_career_years DESC;
2. Early Exit Risk Analysis
SELECT
first_name,
last_name,
party,
total_career_years,
avg_votes_per_year,
activity_level,
retention_risk
FROM view_riksdagen_politician_longevity_analysis
WHERE retention_risk = 'EARLY_EXIT_RISK'
AND is_currently_active = TRUE
ORDER BY avg_votes_per_year ASC;
3. Party Retention Health by Longevity
SELECT
party,
COUNT(*) FILTER (WHERE longevity_category IN ('VETERAN_20_PLUS', 'LONG_SERVICE_15_20')) AS veterans,
COUNT(*) FILTER (WHERE longevity_category = 'NEWCOMER_UNDER_2') AS newcomers,
COUNT(*) FILTER (WHERE retention_risk IN ('HIGH_RETIREMENT_RISK', 'MODERATE_ATTRITION_RISK')) AS at_risk,
ROUND(AVG(total_career_years), 1) AS avg_tenure,
ROUND(AVG(career_continuity_score), 1) AS avg_continuity
FROM view_riksdagen_politician_longevity_analysis
WHERE is_currently_active = TRUE
GROUP BY party
ORDER BY avg_tenure DESC;
4. Career Continuity Patterns
SELECT
continuity_pattern,
COUNT(*) AS count,
ROUND(AVG(election_cycles_active), 1) AS avg_cycles,
ROUND(AVG(career_continuity_score), 1) AS avg_score,
ROUND(AVG(total_career_years), 1) AS avg_years
FROM view_riksdagen_politician_longevity_analysis
WHERE total_career_years > 0
GROUP BY continuity_pattern
ORDER BY avg_score DESC;
Intelligence Applications
- Succession Planning: Identify high retirement risk politicians requiring replacement
- Talent Retention: Monitor engagement levels and intervene for at-risk members
- Party Strategy: Assess veteran vs newcomer balance for renewal planning
- Predictive Analytics: Forecast attrition rates and career duration probabilities
- Comparative Analysis: Benchmark longevity and continuity across parties
Integration Points
- Feeds Predictive Intelligence Framework (Framework 4) for resignation forecasting
- Links to view_riksdagen_politician_career_trajectory for performance correlation
- Complements view_riksdagen_politician_role_evolution for career pattern analysis
- Used in view_politician_risk_summary for comprehensive retention risk scoring
Party Views (Additional Documentation)
view_party_performance_metrics βββββ
Purpose: Comprehensive party performance indicators including win rates, document productivity, member activity, and comparative rankings.
Key Metrics: Party win percentage, avg documents per member, active member count, performance tier (TIER_1-TIER_4)
Sample Query: SELECT party, win_percentage, docs_per_member, performance_tier FROM view_party_performance_metrics ORDER BY performance_tier;
Applications: Party benchmarking, performance scorecards, electoral analysis
Sample Data: view_party_performance_metrics_sample.csv (41 rows - all Swedish political parties)
view_riksdagen_party_ballot_support_annual_summary ββββ
Purpose: Annual aggregation of party voting support patterns, win/loss statistics, and ballot participation rates.
Key Metrics: Year, party, total_ballots, won_ballots, win_percentage, absent_percentage
Sample Query: SELECT year, party, won_ballots, win_percentage FROM view_riksdagen_party_ballot_support_annual_summary WHERE year >= 2020 ORDER BY year DESC, win_percentage DESC;
Applications: Historical performance analysis, trend identification, electoral cycle patterns
view_riksdagen_party_coalation_against_annual_summary ββββ
Purpose: Annual summary of party opposition patterns - which parties consistently vote together AGAINST specific parties.
Key Metrics: Year, party, opposition_party, votes_against_together, opposition_alignment_rate
Sample Query: SELECT party, opposition_party, opposition_alignment_rate FROM view_riksdagen_party_coalation_against_annual_summary WHERE year = EXTRACT(YEAR FROM CURRENT_DATE) ORDER BY opposition_alignment_rate DESC;
Applications: Opposition bloc analysis, conflict mapping, adversarial relationship tracking
view_riksdagen_party_document_daily_summary ββββ
Purpose: Daily document submission counts by party and document type (materialized).
Key Metrics: public_date, party, document_type, total_documents
Sample Query: SELECT party, SUM(total_documents) as monthly_docs FROM view_riksdagen_party_document_daily_summary WHERE public_date >= CURRENT_DATE - INTERVAL '30 days' GROUP BY party ORDER BY monthly_docs DESC;
Applications: Daily productivity tracking, document type analysis, temporal patterns
view_riksdagen_party_member ββββ
Purpose: Current party membership roster with member details and assignment status.
Key Columns: party, person_id, first_name, last_name, status, electoral_region, assignment_type
Sample Query: SELECT party, COUNT(*) as members FROM view_riksdagen_party_member WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot' GROUP BY party ORDER BY members DESC;
Applications: Membership tracking, party size monitoring, regional representation analysis
view_riksdagen_party_momentum_analysis βββββ
Purpose: Party momentum indicators tracking trend direction, stability, and performance velocity.
Key Metrics: party, trend_direction (STRONG_POSITIVE, POSITIVE, STABLE, NEGATIVE), momentum_score, stability_classification
Sample Query: SELECT party, trend_direction, momentum_score FROM view_riksdagen_party_momentum_analysis ORDER BY momentum_score DESC;
Applications: Electoral forecasting, trend analysis, strategic positioning assessment
view_riksdagen_party_role_member βββ
Purpose: Party leadership roles and internal organization structure (party board, chair, secretary, etc.).
Key Columns: party, person_id, role_code, role_title, from_date, to_date
Sample Query: SELECT party, role_title, first_name, last_name FROM view_riksdagen_party_role_member WHERE to_date IS NULL ORDER BY party, role_title;
Applications: Leadership tracking, internal structure analysis
view_riksdagen_party_signatures_document_summary βββ
Purpose: Party document signature analysis - tracks which parties co-sign documents together.
Key Metrics: party, signature_count, co_signature_parties (array), cross_party_collaboration_rate
Sample Query: SELECT party, signature_count, cross_party_collaboration_rate FROM view_riksdagen_party_signatures_document_summary ORDER BY cross_party_collaboration_rate DESC;
Applications: Coalition potential assessment, collaboration pattern analysis
view_riksdagen_party_transition_history βββββ
Purpose: Tracks politicians who switched parties while serving in Riksdagen, analyzing historical transition patterns, timing relative to elections, and subsequent political career trajectories (NEW v1.55).
Key Metrics: person_id, first_name, last_name, previous_party, new_party, transition_date, transition_type, transition_year, next_election, months_until_next_election, previous_election, months_since_last_election
Sample Query: SELECT first_name, last_name, previous_party, new_party, transition_date, transition_type, months_until_next_election FROM view_riksdagen_party_transition_history ORDER BY transition_date DESC;
Applications: Party stability analysis, defection risk assessment, electoral cycle pattern recognition, career trajectory analysis
Intelligence Value: βββββ VERY HIGH - Tracks rare but politically significant events enabling predictive modeling of future defections
GitHub Issue: #8208 Historical Politician Transitions - Leaving Party While in Riksdagen
Key Features
- Transition Type Classification: Distinguishes "SWITCHED_WHILE_SERVING" (continuous service) vs "REJOINED_RIKSDAGEN" (gap >30 days)
- Election Proximity Analysis: Calculates months until next election and months since last election
- Historical Coverage: Tracks transitions since 2002 across 7 Swedish election cycles (2002-2026)
- Window Functions: Uses LAG/LEAD over assignment_data.org_code to detect party changes
Intelligence Applications
- Predictive Intelligence: Framework 4 - Defection risk modeling and early warning signals
- Temporal Analysis: Framework 1 - Electoral cycle influence on party transitions
- Risk Assessment: Framework 3 - Party stability indicators and cohesion metrics
- Strategic Forecasting: Coalition formation analysis considering defection patterns
view_riksdagen_party_defector_analysis βββββ
Purpose: Analyzes behavioral patterns of politicians who defected from their party, measuring pre/post transition voting attendance and document productivity to identify early warning signals (NEW v1.55).
Key Metrics: person_id, first_name, last_name, previous_party, new_party, transition_date, months_until_next_election, pre_transition_attendance, post_transition_attendance, attendance_change, docs_before, docs_after, defection_timing
Sample Query: SELECT first_name, last_name, previous_party, new_party, defection_timing, attendance_change FROM view_riksdagen_party_defector_analysis WHERE ABS(attendance_change) > 10 ORDER BY transition_date DESC;
Applications: Early warning system for defections, behavioral anomaly detection, engagement pattern analysis
Intelligence Value: βββββ VERY HIGH - Identifies predictive signals for party defection risk
GitHub Issue: #8208 Historical Politician Transitions - Leaving Party While in Riksdagen
Key Features
- Attendance Analysis: 6-month pre/post transition voting attendance patterns from vote_data
- Defection Timing Classification: PRE_ELECTION (β€12mo), MID_TERM (β₯36mo), NORMAL (>12mo and <36mo), UNKNOWN_TIMING (post-2026 transitions)
- Behavioral Metrics: Attendance change delta, document production before/after transition
- Early Warning Signals: Declining participation as predictor of party switching
Intelligence Applications
- Risk Assessment: Identifies politicians at risk of defection based on declining engagement
- Behavioral Analysis: Detects participation drop-offs preceding party transitions
- Predictive Modeling: Builds defection risk scores based on historical patterns
- Counterintelligence: Monitors party cohesion and loyalty indicators
view_riksdagen_party_switcher_outcomes βββββ
Purpose: Measures post-transition career success for party switchers, tracking continued MP status, re-election success, leadership positions, and subsequent political assignments (NEW v1.55).
Key Metrics: person_id, first_name, last_name, previous_party, new_party, transition_date, next_election, months_until_next_election, total_subsequent_assignments, total_days_served_after_switch, continued_as_active_mp, served_in_next_election, attained_leadership_post_switch, post_switch_roles, current_status
Sample Query: SELECT first_name, last_name, previous_party, new_party, continued_as_active_mp, served_in_next_election, attained_leadership_post_switch FROM view_riksdagen_party_switcher_outcomes ORDER BY transition_date DESC;
Applications: Career trajectory analysis, defection outcome assessment, party switching viability evaluation
Intelligence Value: βββββ VERY HIGH - Quantifies career consequences of party transitions
GitHub Issue: #8208 Historical Politician Transitions - Leaving Party While in Riksdagen
Key Features
- Career Outcome Metrics: Total subsequent assignments, days served after transition
- Electoral Success: Tracks continued MP status and service in next election cycle
- Leadership Attainment: Identifies leadership positions gained post-transition (Partiledare, Gruppledare, etc.)
- NULL-Safe Handling: Handles transitions after last defined election (2026-09-13)
Intelligence Applications
- Strategic Assessment: Evaluates career viability of party switching decisions
- Predictive Intelligence: Models defection success rates by timing and target party
- Historical Analysis: Tracks long-term consequences of political realignment
- Coalition Dynamics: Assesses impact of defections on party strength and government formation
view_riksdagen_person_signed_document_summary βββ
Purpose: Individual politician document signature patterns and co-signing behavior.
Key Metrics: person_id, total_signatures, solo_documents, co_signed_documents, collaboration_rate
Sample Query: SELECT first_name, last_name, party, collaboration_rate FROM view_riksdagen_person_signed_document_summary WHERE total_signatures >= 50 ORDER BY collaboration_rate DESC LIMIT 20;
Applications: Collaboration analysis, legislative style assessment
view_riksdagen_member_proposals βββ
Purpose: Parliamentary member legislative proposals (motions) submitted to Riksdagen.
Key Columns: id, document_type, title, made_public_date, org (committee), status
Sample Query: SELECT title, made_public_date, org, status FROM view_riksdagen_member_proposals WHERE made_public_date >= CURRENT_DATE - INTERVAL '3 months' ORDER BY made_public_date DESC;
Applications: Legislative initiative tracking, proposal success rate analysis
Vote Data Views (Complete Documentation)
Overview
Vote data views provide temporal aggregations of ballot outcomes, party voting patterns, and politician voting records at daily, weekly, monthly, and annual granularities. All vote summary views are materialized and refreshed daily at 02:00 UTC for optimal query performance.
Ballot-Level Vote Summaries (5 views) ββββ
Views: view_riksdagen_vote_data_ballot_summary, _daily, _weekly, _monthly, _annual
Purpose: Aggregate ballot outcomes with winner/loser counts, total votes, and decision types.
Key Metrics: ballot_id, vote_date, total_votes_cast, winning_side_count, losing_side_count, decision_type
Sample Query (Daily):
SELECT vote_date, COUNT(DISTINCT ballot_id) as ballots_count,
SUM(total_votes_cast) as total_votes
FROM view_riksdagen_vote_data_ballot_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY vote_date
ORDER BY vote_date DESC;
Applications: Parliamentary activity monitoring, voting frequency analysis, decision type trends
Party-Level Vote Summaries (5 views) βββββ
Views: view_riksdagen_vote_data_ballot_party_summary, _daily, _weekly, _monthly, _annual
Purpose: Party voting behavior aggregated by time period with win rates, absence rates, and discipline metrics.
Key Metrics: party, vote_date/period, total_ballots, won_ballots, lost_ballots, absent_votes, win_percentage, absence_percentage, party_discipline_score
Sample Query (Monthly):
SELECT month_start, party, won_ballots, win_percentage, absence_percentage
FROM view_riksdagen_vote_data_ballot_party_summary_monthly
WHERE month_start >= DATE_TRUNC('year', CURRENT_DATE)
ORDER BY month_start DESC, win_percentage DESC;
Applications: Party effectiveness tracking, temporal performance analysis, coalition strength assessment
Politician-Level Vote Summaries (5 views) βββββ
Views: view_riksdagen_vote_data_ballot_politician_summary, _daily (documented), _weekly, _monthly, _annual
Purpose: Individual politician voting records aggregated by time period with win rates, absence, and rebellion metrics.
Key Metrics: person_id, vote_date/period, ballots_participated, won_votes, lost_votes, absent_votes, rebellion_votes, win_percentage, absence_percentage, rebellion_rate
Sample Query (Annual):
SELECT year, person_id, first_name, last_name, party,
ballots_participated, win_percentage, absence_percentage
FROM view_riksdagen_vote_data_ballot_politician_summary_annual
WHERE year = EXTRACT(YEAR FROM CURRENT_DATE)
ORDER BY win_percentage DESC
LIMIT 30;
Applications: Politician performance scorecards, behavioral trend analysis, absence tracking
Intelligence Applications
These views are CRITICAL for the CIA platform's intelligence capabilities:
| Analysis Framework | Use Case | Supported Granularities | Link |
|---|---|---|---|
| Temporal Analysis | Track voting behavior changes over time | Daily, Weekly, Monthly, Annual | Framework Docs |
| Comparative Analysis | Benchmark politicians against peers | Annual, Monthly | Framework Docs |
| Pattern Recognition | Detect behavioral anomalies and clusters | All granularities | Framework Docs |
| Predictive Intelligence | Forecast future voting behavior and risks | Monthly, Annual | Framework Docs |
Risk Rules Supported: These views power most politician risk rules including:
- #1 PoliticianLazy (Absenteeism)
- #2 PoliticianIneffectiveVoting (Effectiveness)
- #3 PoliticianHighRebelRate (Party Discipline)
- #4 PoliticianDecliningEngagement (Trend Analysis)
Intelligence Products Generated:
- π Political Scorecards - Performance rankings by win rate, absence, productivity
- β οΈ Risk Assessments - Behavioral anomaly detection and risk scoring
- π Trend Reports - Temporal analysis of engagement and effectiveness
- π― Predictive Alerts - Early warning system for declining performance
Data Flow: Intelligence Data Flow Map - Vote Data Views
Committee Views (Complete Documentation)
view_riksdagen_committee ββββ
Purpose: Committee structure, membership, and activity metrics for all Riksdagen committees.
Key Columns: committee_code, committee_name, member_count, active_proposals, decision_count, chair_person_id
Sample Query: SELECT committee_name, member_count, active_proposals FROM view_riksdagen_committee ORDER BY active_proposals DESC;
Applications: Committee workload analysis, membership tracking, productivity assessment
view_committee_productivity ββββ
Purpose: Committee productivity metrics with decision counts, processing times, and efficiency indicators.
Key Metrics: committee_code, decisions_per_quarter, avg_processing_days, productivity_level (HIGH, MODERATE, LOW)
Sample Query: SELECT committee_name, decisions_per_quarter, productivity_level FROM view_committee_productivity ORDER BY decisions_per_quarter DESC;
Applications: Committee efficiency analysis, resource allocation, bottleneck identification
view_committee_productivity_matrix ββββ
Purpose: Matrix comparison of all committees across productivity dimensions (decisions, proposals, processing speed).
Key Metrics: committee_code, productivity_rank, efficiency_percentile, workload_tier
Sample Query: SELECT committee_name, productivity_rank, efficiency_percentile FROM view_committee_productivity_matrix ORDER BY productivity_rank;
Applications: Cross-committee benchmarking, performance tier classification
view_riksdagen_committee_ballot_decision_party_summary ββββ
Purpose: Party-level voting behavior in committee ballots (materialized).
Key Metrics: committee_code, ballot_id, party, votes_for, votes_against, party_position
Sample Query: SELECT committee_code, party, COUNT(*) as decisions, SUM(votes_for) as total_support FROM view_riksdagen_committee_ballot_decision_party_summary GROUP BY committee_code, party;
Applications: Party committee alignment analysis, voting coalition patterns
view_riksdagen_committee_ballot_decision_politician_summary ββββ
Purpose: Individual politician voting in committee ballots (materialized).
Key Metrics: committee_code, ballot_id, person_id, vote_decision, alignment_with_party
Sample Query: SELECT person_id, first_name, last_name, COUNT(*) as committee_votes FROM view_riksdagen_committee_ballot_decision_politician_summary GROUP BY person_id, first_name, last_name ORDER BY committee_votes DESC LIMIT 20;
Applications: Committee participation tracking, individual voting patterns
view_riksdagen_committee_ballot_decision_summary ββββ
Purpose: Aggregated committee ballot outcomes with winner/loser counts (materialized).
Key Metrics: committee_code, ballot_id, decision_date, total_votes, votes_for, votes_against, decision_outcome
Sample Query: SELECT committee_code, COUNT(*) as total_decisions FROM view_riksdagen_committee_ballot_decision_summary GROUP BY committee_code ORDER BY total_decisions DESC;
Applications: Committee decision volume analysis, outcome tracking
view_riksdagen_committee_decisions ββββ
Purpose: Detailed committee decisions including proposal handling, recommendations, and approval status (materialized).
Key Metrics: decision_id, committee_code, proposal_id, decision_type, decision_date, recommendation, status
Sample Query: SELECT committee_code, decision_type, COUNT(*) as count FROM view_riksdagen_committee_decisions WHERE decision_date >= CURRENT_DATE - INTERVAL '12 months' GROUP BY committee_code, decision_type;
Applications: Decision type analysis, proposal success rates, committee workload
view_riksdagen_committee_decision_type_org_summary βββ
Purpose: Committee decisions aggregated by type and organization (materialized).
Key Metrics: committee_code, org_code, decision_type, total_decisions
Sample Query: SELECT committee_code, decision_type, SUM(total_decisions) as count FROM view_riksdagen_committee_decision_type_org_summary GROUP BY committee_code, decision_type ORDER BY count DESC;
Applications: Decision type distribution, organizational pattern analysis
view_riksdagen_committee_decision_type_summary βββ
Purpose: Simplified committee decision aggregation by type (materialized).
Key Metrics: committee_code, decision_type, decision_count
Sample Query: SELECT * FROM view_riksdagen_committee_decision_type_summary ORDER BY committee_code, decision_count DESC;
Applications: Quick decision type reference, committee specialization
view_riksdagen_committee_parliament_member_proposal βββ
Purpose: Parliamentary member proposals assigned to specific committees.
Key Columns: proposal_id, committee_code, person_id, proposal_type, submitted_date, status
Sample Query: SELECT committee_code, COUNT(*) as proposals FROM view_riksdagen_committee_parliament_member_proposal GROUP BY committee_code ORDER BY proposals DESC;
Applications: Committee workload assessment, proposal routing analysis
view_riksdagen_committee_role_member βββ
Purpose: Committee role assignments (chair, vice-chair, members) with assignment dates.
Key Columns: committee_code, person_id, role_code, role_title, from_date, to_date
Sample Query: SELECT committee_code, role_title, first_name, last_name FROM view_riksdagen_committee_role_member WHERE to_date IS NULL ORDER BY committee_code, role_title;
Applications: Committee leadership tracking, membership history
view_riksdagen_committee_roles βββ
Purpose: Committee role definitions and structure (metadata).
Key Columns: role_code, role_title, committee_code, role_level
Sample Query: SELECT * FROM view_riksdagen_committee_roles ORDER BY committee_code, role_level;
Applications: Role reference data, committee structure documentation
Document Views (Additional Documentation)
view_document_data_committee_report_url βββ
Purpose: URLs for committee reports and documents for external reference/linking.
Key Columns: document_id, committee_code, report_url_xml, report_url_html
Sample Query: SELECT document_id, committee_code, report_url_html FROM view_document_data_committee_report_url WHERE committee_code = 'au' LIMIT 10;
Applications: Document linking, external system integration
view_riksdagen_org_document_daily_summary βββ
Purpose: Daily document submissions by organization/committee (materialized).
Key Metrics: public_date, org_code, document_type, total_documents
Sample Query: SELECT org_code, SUM(total_documents) as monthly_docs FROM view_riksdagen_org_document_daily_summary WHERE public_date >= CURRENT_DATE - INTERVAL '30 days' GROUP BY org_code ORDER BY monthly_docs DESC;
Applications: Organizational productivity tracking, temporal document patterns
view_riksdagen_document_type_daily_summary βββ
Purpose: Daily document type distribution across entire Riksdagen (materialized).
Key Metrics: public_date, document_type, total_documents
Sample Query: SELECT document_type, SUM(total_documents) as yearly_count FROM view_riksdagen_document_type_daily_summary WHERE public_date >= DATE_TRUNC('year', CURRENT_DATE) GROUP BY document_type ORDER BY yearly_count DESC;
Applications: Document type trend analysis, legislative activity monitoring
Application & Audit Views (Complete Documentation)
Application Action Event Views (12 views) ββ
Purpose: Track user interactions with CIA platform pages, UI elements, and access modes at various time granularities.
Key Metrics: action_date/period, page_name, element_name, action_type, event_count, unique_users
Applications: User behavior analytics, feature usage tracking, platform optimization, engagement analysis
view_application_action_event_page_annual_summary ββ
Purpose: Annual summary of user interactions with platform pages.
Key Metrics: year, page_name, total_events, unique_users, avg_events_per_user
Sample Query: SELECT year, page_name, total_events FROM view_application_action_event_page_annual_summary WHERE year >= 2024 ORDER BY year DESC, total_events DESC;
Applications: Annual usage trends, page popularity analysis, long-term engagement tracking
view_application_action_event_page_daily_summary ββ
Purpose: Daily summary of user interactions with platform pages.
Key Metrics: action_date, page_name, event_count, unique_users
Sample Query: SELECT action_date, page_name, SUM(event_count) as total FROM view_application_action_event_page_daily_summary WHERE action_date >= CURRENT_DATE - 7 GROUP BY action_date, page_name ORDER BY action_date DESC;
Applications: Daily usage monitoring, page traffic analysis, user engagement tracking
view_application_action_event_page_element_annual_summary ββ
Purpose: Annual summary of user interactions with UI elements within pages.
Key Metrics: year, page_name, element_name, total_clicks, unique_users
Sample Query: SELECT year, page_name, element_name, total_clicks FROM view_application_action_event_page_element_annual_summary WHERE year >= 2024 ORDER BY total_clicks DESC;
Applications: Feature usage analysis, UI/UX optimization, element effectiveness tracking
view_application_action_event_page_element_daily_summary ββ
Purpose: Daily summary of user interactions with UI elements within pages.
Key Metrics: action_date, page_name, element_name, click_count, unique_users
Sample Query: SELECT action_date, element_name, SUM(click_count) as clicks FROM view_application_action_event_page_element_daily_summary WHERE action_date >= CURRENT_DATE - 7 GROUP BY action_date, element_name ORDER BY clicks DESC;
Applications: Daily feature monitoring, UI element tracking, user interaction patterns
view_application_action_event_page_element_hourly_summary ββ
Purpose: Hourly summary of user interactions with UI elements within pages.
Key Metrics: action_timestamp, page_name, element_name, click_count, unique_users
Sample Query: SELECT DATE_TRUNC('hour', action_timestamp) as hour, element_name, SUM(click_count) FROM view_application_action_event_page_element_hourly_summary WHERE action_timestamp >= NOW() - INTERVAL '24 hours' GROUP BY hour, element_name;
Applications: Real-time monitoring, peak usage detection, hourly engagement patterns
view_application_action_event_page_element_weekly_summary ββ
Purpose: Weekly summary of user interactions with UI elements within pages.
Key Metrics: week_start_date, page_name, element_name, total_clicks, unique_users
Sample Query: SELECT week_start_date, element_name, SUM(total_clicks) as clicks FROM view_application_action_event_page_element_weekly_summary WHERE week_start_date >= CURRENT_DATE - 30 GROUP BY week_start_date, element_name ORDER BY clicks DESC;
Applications: Weekly trend analysis, UI element performance, engagement patterns
view_application_action_event_page_hourly_summary ββ
Purpose: Hourly summary of user interactions with platform pages.
Key Metrics: action_timestamp, page_name, event_count, unique_users
Sample Query: SELECT DATE_TRUNC('hour', action_timestamp) as hour, page_name, SUM(event_count) FROM view_application_action_event_page_hourly_summary WHERE action_timestamp >= NOW() - INTERVAL '24 hours' GROUP BY hour, page_name ORDER BY hour DESC;
Applications: Real-time traffic monitoring, peak hour detection, load balancing
view_application_action_event_page_modes_annual_summary ββ
Purpose: Annual summary of user access modes (desktop, mobile, tablet) by page.
Key Metrics: year, page_name, access_mode, event_count, unique_users
Sample Query: SELECT year, access_mode, SUM(event_count) as total FROM view_application_action_event_page_modes_annual_summary WHERE year >= 2024 GROUP BY year, access_mode ORDER BY total DESC;
Applications: Device usage trends, platform optimization, responsive design decisions
view_application_action_event_page_modes_daily_summary ββ
Purpose: Daily summary of user access modes (desktop, mobile, tablet) by page.
Key Metrics: action_date, page_name, access_mode, event_count, unique_users
Sample Query: SELECT action_date, access_mode, SUM(event_count) as total FROM view_application_action_event_page_modes_daily_summary WHERE action_date >= CURRENT_DATE - 7 GROUP BY action_date, access_mode ORDER BY action_date DESC;
Applications: Daily device analytics, mobile vs desktop usage, accessibility monitoring
view_application_action_event_page_modes_hourly_summary ββ
Purpose: Hourly summary of user access modes (desktop, mobile, tablet) by page.
Key Metrics: action_timestamp, page_name, access_mode, event_count, unique_users
Sample Query: SELECT DATE_TRUNC('hour', action_timestamp) as hour, access_mode, SUM(event_count) FROM view_application_action_event_page_modes_hourly_summary WHERE action_timestamp >= NOW() - INTERVAL '24 hours' GROUP BY hour, access_mode;
Applications: Real-time device monitoring, peak usage by device type
view_application_action_event_page_modes_weekly_summary ββ
Purpose: Weekly summary of user access modes (desktop, mobile, tablet) by page.
Key Metrics: week_start_date, page_name, access_mode, event_count, unique_users
Sample Query: SELECT week_start_date, access_mode, SUM(event_count) as total FROM view_application_action_event_page_modes_weekly_summary WHERE week_start_date >= CURRENT_DATE - 30 GROUP BY week_start_date, access_mode ORDER BY total DESC;
Applications: Weekly device trends, platform strategy decisions
view_application_action_event_page_weekly_summary ββ
Purpose: Weekly summary of user interactions with platform pages.
Key Metrics: week_start_date, page_name, event_count, unique_users
Sample Query: SELECT week_start_date, page_name, SUM(event_count) as total FROM view_application_action_event_page_weekly_summary WHERE week_start_date >= CURRENT_DATE - 90 GROUP BY week_start_date, page_name ORDER BY week_start_date DESC;
Applications: Weekly engagement tracking, page popularity trends, user activity patterns
view_audit_author_summary ββ
Purpose: Data change audit trail by author/user.
Key Metrics: author_id, total_changes, tables_modified, last_change_date
Sample Query: SELECT author_id, total_changes, tables_modified FROM view_audit_author_summary ORDER BY total_changes DESC;
Applications: Change tracking, data governance, audit compliance
view_audit_data_summary ββ
Purpose: Aggregated audit trail statistics (inserts, updates, deletes by table).
Key Metrics: table_name, insert_count, update_count, delete_count, last_modified
Sample Query: SELECT table_name, insert_count, update_count, delete_count FROM view_audit_data_summary ORDER BY (insert_count + update_count + delete_count) DESC;
Applications: Data modification monitoring, audit reporting, change volume analysis
WorldBank Data View
view_worldbank_indicator_data_country_summary βββ
Purpose: Economic indicators for Sweden from World Bank data (materialized).
Key Metrics: country_code, indicator_id, year, indicator_value, indicator_name
Sample Query: SELECT year, indicator_name, indicator_value FROM view_worldbank_indicator_data_country_summary WHERE country_code = 'SWE' AND indicator_id = 'NY.GDP.MKTP.CD' ORDER BY year DESC;
Applications: Economic context for political analysis, GDP trends, macro-economic indicators
Party Views
Overview
Party views provide organizational-level intelligence on Swedish political parties, tracking electoral performance, coalition behavior, internal discipline, decision effectiveness, performance trends, and longitudinal analysis across election cycles (2002-2026). These views enable coalition analysis, party comparison, government formation forecasting, and historical trend analysis.
Total Party Views: 16 (NEW: 4 Recreated Party Analysis views v1.61 + Party Transition Tracking v1.57 + Party Decision Flow v1.35)
Intelligence Value: βββββ VERY HIGH
Primary Use Cases: Coalition analysis, party performance monitoring, electoral forecasting, bloc alignment, legislative effectiveness, longitudinal trend analysis, election cycle patterns, coalition evolution tracking
New in v1.61: 4 views recreated after v1.53/v1.6 drops:
view_riksdagen_party_summary- Party-level assignment and document aggregation (59 columns)view_riksdagen_party_longitudinal_performance- Semester-based performance tracking with 70 KPIs and advanced window functionsview_riksdagen_party_coalition_evolution- Party-pair alliance tracking with 35 coalition metricsview_riksdagen_party_electoral_trends- Electoral performance analysis with 49 forecasting indicators
view_riksdagen_party βββββ
Category: Base Party Views (v1.1, enhanced multiple versions)
Type: Standard View
Intelligence Value: VERY HIGH - Core Party Profile
Business Context
Market Value: β¬8M TAM (Media & Journalism segment)
Product Integration: Political Intelligence API, Advanced Analytics Suite
Revenue Impact: Essential for β¬6,000/month Professional and β¬15,000/month Enterprise tiers
JSON Export Spec: party-schema.md
API Endpoint: GET /api/v1/parties, GET /api/v1/parties/{id}
Used In Product Features:
- Party performance dashboards (Corporate Government Affairs, NGOs & Advocacy)
- Coalition stability monitoring (Political Parties, Political Consulting)
- Comparative party analysis (Media & Journalism, Academic Research)
- Voting pattern analysis (All segments)
Target Customer Segments:
- Media & Journalism (β¬8M TAM): Investigative reporting, election coverage, political analysis
- Corporate Affairs (β¬12M TAM): Government relations, stakeholder monitoring, regulatory risk
- Political Consulting (β¬15M TAM): Coalition forecasting, opposition research, campaign strategy
- Academic Research (β¬5M TAM): Political science research, party system analysis
Business Documentation: See BUSINESS_PRODUCT_DOCUMENT.md#product-line-1
Purpose
Central party profile view aggregating party identification, current member counts, parliamentary representation, and organizational metadata. Serves as the primary reference for party-level analysis and coalition mapping.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
party | VARCHAR(50) | Party short code (primary key) | 'S', 'M', 'SD', 'C', 'V', 'KD', 'L', 'MP' |
party_name | VARCHAR(255) | Full party name | 'Socialdemokraterna' |
party_english_name | VARCHAR(255) | English translation | 'Social Democrats' |
member_count | INTEGER | Current active members | 70 |
website | VARCHAR(255) | Official party website | 'https://www.socialdemokraterna.se' |
registered_date | DATE | Registration date | '1889-04-23' |
party_size_category | VARCHAR(50) | Classification | 'MAJOR', 'MEDIUM', 'SMALL' |
bloc_alignment | VARCHAR(50) | Political bloc | 'LEFT_BLOC', 'RIGHT_BLOC', 'INDEPENDENT' |
Swedish Political Parties
| Code | Party Name (Swedish) | English Name | Bloc | Historical Seats |
|---|---|---|---|---|
| S | Socialdemokraterna | Social Democrats | LEFT | 70-110 |
| M | Moderaterna | Moderate Party | RIGHT | 68-107 |
| SD | Sverigedemokraterna | Sweden Democrats | RIGHT* | 62-73 |
| C | Centerpartiet | Centre Party | RIGHT | 22-31 |
| V | VΓ€nsterpartiet | Left Party | LEFT | 21-28 |
| KD | Kristdemokraterna | Christian Democrats | RIGHT | 19-25 |
| L | Liberalerna | Liberals | RIGHT | 16-24 |
| MP | MiljΓΆpartiet | Green Party | LEFT | 16-25 |
*Note: SD traditionally excluded from coalitions but increasingly influential
Bloc Structure
LEFT_BLOC (Red-Green):
- S (Social Democrats) - Traditional lead party
- V (Left Party) - Socialist/left-wing
- MP (Green Party) - Environmental focus
RIGHT_BLOC (Alliance/TidΓΆ):
- M (Moderate Party) - Traditional lead party
- C (Centre Party) - Liberal-conservative (sometimes swing)
- KD (Christian Democrats) - Conservative
- L (Liberals) - Classical liberal
- SD (Sweden Democrats) - Nationalist (conditionally included post-2022)
Example Queries
1. Current Parliament Composition
SELECT
party,
party_name,
member_count,
bloc_alignment,
ROUND(100.0 * member_count / SUM(member_count) OVER (), 2) AS seat_percentage,
party_size_category
FROM view_riksdagen_party
WHERE member_count > 0
ORDER BY member_count DESC;
Output:
party | party_name | member_count | bloc | seat_percentage | category
-------+------------------------+--------------+---------+----------------+---------
SD | Sverigedemokraterna | 73 | RIGHT | 20.92 | MAJOR
S | Socialdemokraterna | 70 | LEFT | 20.06 | MAJOR
M | Moderaterna | 68 | RIGHT | 19.48 | MAJOR
2. Bloc Strength Analysis
SELECT
bloc_alignment,
COUNT(DISTINCT party) AS party_count,
SUM(member_count) AS total_seats,
ROUND(100.0 * SUM(member_count) / (SELECT SUM(member_count) FROM view_riksdagen_party), 2) AS bloc_percentage,
STRING_AGG(party || ' (' || member_count || ')', ', ' ORDER BY member_count DESC) AS parties
FROM view_riksdagen_party
WHERE member_count > 0
GROUP BY bloc_alignment
ORDER BY total_seats DESC;
3. Historical Party Comparison (Requires Join with Election Data)
SELECT
rp.party,
rp.party_name,
rp.member_count AS current_seats,
ed.previous_seats,
rp.member_count - ed.previous_seats AS seat_change,
ROUND(100.0 * (rp.member_count - ed.previous_seats) / NULLIF(ed.previous_seats, 0), 1) AS change_pct
FROM view_riksdagen_party rp
LEFT JOIN election_data ed ON ed.party = rp.party AND ed.election_year = 2022
WHERE rp.member_count > 0
ORDER BY seat_change DESC;
4. Party Size Distribution
SELECT
party_size_category,
COUNT(*) AS party_count,
STRING_AGG(party || ' (' || member_count || ')', ', ' ORDER BY member_count DESC) AS parties,
SUM(member_count) AS total_members
FROM view_riksdagen_party
WHERE member_count > 0
GROUP BY party_size_category
ORDER BY
CASE party_size_category
WHEN 'MAJOR' THEN 1
WHEN 'MEDIUM' THEN 2
WHEN 'SMALL' THEN 3
END;
5. Coalition Viability Matrix (Seat Count Combinations)
WITH party_combos AS (
SELECT
p1.party AS party_1,
p1.member_count AS seats_1,
p2.party AS party_2,
p2.member_count AS seats_2,
p1.member_count + p2.member_count AS combined_seats
FROM view_riksdagen_party p1
CROSS JOIN view_riksdagen_party p2
WHERE p1.party < p2.party -- Avoid duplicates
AND p1.member_count > 0
AND p2.member_count > 0
)
SELECT
party_1,
party_2,
combined_seats,
CASE
WHEN combined_seats >= 175 THEN 'MAJORITY_POSSIBLE'
WHEN combined_seats >= 165 THEN 'CLOSE_TO_MAJORITY'
ELSE 'INSUFFICIENT'
END AS coalition_viability
FROM party_combos
WHERE combined_seats >= 165 -- Near majority threshold (175/349)
ORDER BY combined_seats DESC;
Performance Characteristics
- Query Time: <5ms (small table, indexed)
- Indexes Used: Primary key on
party - Data Volume: ~15 rows (active + historical parties)
- Refresh Frequency: Real-time (updated with member assignments)
Data Sources
- Primary Table: Aggregation from
person_dataandassignment_data - Party Registry:
sweden_political_partyfor official information
Dependencies
- No view dependencies
- Used by: Nearly all party-related views
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PartyWeakSupport (Y-01): Member count for strength assessment
- PartyCoalitionUnstable (Y-02): Bloc alignment for coalition analysis
- All party-level risk rules use this as base reference
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Comparative Analysis: Party-to-party comparisons
- Coalition Analysis: Government formation scenarios
- Power Structure: Parliamentary balance assessment
view_party_effectiveness_trends βββββ
Category: Intelligence Views (v1.30)
Type: Standard View
Intelligence Value: VERY HIGH - Party Performance Tracking
Changelog: v1.30 OSINT Party Effectiveness Monitoring
Purpose
Comprehensive party-level performance tracking with monthly time-series analysis of voting effectiveness, member discipline, legislative productivity, and coalition behavior. Enables trend detection and comparative party performance assessment.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
party | VARCHAR(50) | Party code | 'S' |
year_month | DATE | Month of analysis | '2024-10-01' |
active_members | INTEGER | Members active in voting | 68 |
avg_party_absence_rate | NUMERIC(5,2) | Average absence across members | 8.50 |
avg_party_win_rate | NUMERIC(5,2) | Average effectiveness | 72.30 |
avg_party_discipline | NUMERIC(5,2) | Party cohesion (100 - rebel rate) | 94.20 |
total_documents | INTEGER | Documents produced this month | 145 |
interpellations_filed | INTEGER | Questions to government | 23 |
motions_submitted | INTEGER | Legislative proposals | 67 |
committee_participation | NUMERIC(5,2) | Committee activity level | 88.50 |
absence_trend | NUMERIC(5,2) | Month-over-month change | -1.20 |
effectiveness_trend | NUMERIC(5,2) | Win rate change | +2.50 |
discipline_trend | NUMERIC(5,2) | Cohesion change | +0.80 |
productivity_trend | INTEGER | Document count change | +12 |
ma_3month_effectiveness | NUMERIC(5,2) | 3-month moving average | 71.80 |
party_performance_status | VARCHAR(50) | Classification | 'STRONG_PERFORMANCE' |
coalition_potential_score | NUMERIC(5,2) | Reliability metric (0-100) | 87.50 |
Performance Classifications
Party Performance Status:
EXCELLENT_PERFORMANCE: High effectiveness, low absence, high disciplineSTRONG_PERFORMANCE: Above average across all metricsMODERATE_PERFORMANCE: Average performance, some weaknessesCONCERNING_PERFORMANCE: Multiple problematic indicatorsPOOR_PERFORMANCE: Systematic performance issues
Coalition Potential Score (0-100): Calculated from:
- Party discipline (40% weight) - Cohesion indicator
- Attendance rates (30% weight) - Reliability indicator
- Effectiveness trends (30% weight) - Momentum indicator
Example Queries
1. Current Party Performance Rankings
SELECT
party,
active_members,
ROUND(avg_party_absence_rate, 2) AS absence_rate,
ROUND(avg_party_win_rate, 2) AS win_rate,
ROUND(avg_party_discipline, 2) AS discipline,
total_documents,
party_performance_status,
ROUND(coalition_potential_score, 2) AS coalition_score
FROM view_party_effectiveness_trends
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
ORDER BY coalition_potential_score DESC;
2. Party Performance Trends (Last 12 Months)
SELECT
party,
COUNT(*) AS months_tracked,
ROUND(AVG(avg_party_win_rate), 2) AS avg_effectiveness_12mo,
ROUND(AVG(avg_party_absence_rate), 2) AS avg_absence_12mo,
ROUND(AVG(avg_party_discipline), 2) AS avg_discipline_12mo,
ROUND(AVG(effectiveness_trend), 2) AS avg_trend,
SUM(total_documents) AS total_docs_12mo
FROM view_party_effectiveness_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY party
ORDER BY avg_effectiveness_12mo DESC;
3. Party Momentum Analysis (Improving vs. Declining)
WITH recent_trends AS (
SELECT
party,
AVG(effectiveness_trend) AS avg_effectiveness_trend,
AVG(discipline_trend) AS avg_discipline_trend,
AVG(productivity_trend) AS avg_productivity_trend
FROM view_party_effectiveness_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY party
)
SELECT
party,
ROUND(avg_effectiveness_trend, 2) AS effectiveness_momentum,
ROUND(avg_discipline_trend, 2) AS discipline_momentum,
ROUND(avg_productivity_trend, 0) AS productivity_momentum,
CASE
WHEN avg_effectiveness_trend > 2 AND avg_discipline_trend > 0 THEN 'STRONG_MOMENTUM'
WHEN avg_effectiveness_trend > 0 THEN 'POSITIVE_MOMENTUM'
WHEN avg_effectiveness_trend < -2 THEN 'DECLINING'
ELSE 'STABLE'
END AS momentum_assessment
FROM recent_trends
ORDER BY avg_effectiveness_trend DESC;
4. Comparative Party Analysis (Bloc-Level Aggregation)
WITH party_bloc AS (
SELECT
CASE
WHEN pef.party IN ('S', 'V', 'MP') THEN 'LEFT_BLOC'
WHEN pef.party IN ('M', 'KD', 'L', 'C', 'SD') THEN 'RIGHT_BLOC'
ELSE 'OTHER'
END AS bloc,
pef.*
FROM view_party_effectiveness_trends pef
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
)
SELECT
bloc,
COUNT(DISTINCT party) AS party_count,
SUM(active_members) AS total_members,
ROUND(AVG(avg_party_win_rate), 2) AS bloc_avg_effectiveness,
ROUND(AVG(avg_party_discipline), 2) AS bloc_avg_discipline,
ROUND(AVG(coalition_potential_score), 2) AS bloc_avg_coalition_score
FROM party_bloc
GROUP BY bloc
ORDER BY bloc_avg_effectiveness DESC;
5. Party Productivity Analysis (Legislative Output)
SELECT
party,
year_month,
total_documents,
interpellations_filed,
motions_submitted,
ROUND(interpellations_filed::NUMERIC / NULLIF(active_members, 0), 2) AS interpellations_per_member,
ROUND(total_documents::NUMERIC / NULLIF(active_members, 0), 2) AS documents_per_member,
productivity_trend
FROM view_party_effectiveness_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '6 months'
ORDER BY party, year_month DESC;
``$
#### \text{Performance} \text{Characteristics}
- **\text{Query} \text{Time}:** 150-250\text{ms} (\text{complex} \text{multi}-\text{source} \text{aggregation})
- **\text{Indexes} \text{Used}:** \text{Multiple} \text{indexes} \text{on} \text{vote}, \text{document}, \text{and} \text{assignment} \text{tables}
- **\text{Data} \text{Volume}:** ~500 \text{rows} (8 \text{parties} \times 60+ \text{months})
- **\text{Refresh} \text{Frequency}:** \text{Real}-\text{time} (\text{recalculated} \text{on} \text{query})
- **\text{Optimization}:** \text{Strong} \text{candidate} \text{for} \text{materialization}
#### \text{Data} \text{Sources}
- **\text{Vote} \text{Data}:** $view_riksdagen_vote_data_ballot_party_summary_daily` (aggregated monthly)
- **Document Data:** `view_riksdagen_party_document_summary`
- **Member Data:** `view_riksdagen_party` (active member counts)
#### Dependencies
- Depends on: Multiple vote and document summary views
- Used by: `view_riksdagen_intelligence_dashboard`, coalition analysis tools
#### Risk Rules Supported
From [RISK_RULES_INTOP_OSINT.md](RISK_RULES_INTOP_OSINT.md):
- **PartyWeakSupport (Y-01)**: Effectiveness and trend metrics
- **PartyCoalitionUnstable (Y-02)**: Coalition potential score
- **PartyLowDiscipline (Y-03)**: `avg_party_discipline` metric
- **PartyDecliningProductivity (Y-04)**: Document trends
#### Intelligence Frameworks Applicable
From [DATA_ANALYSIS_INTOP_OSINT.md](DATA_ANALYSIS_INTOP_OSINT.md):
- **Temporal Analysis**: Time-series tracking with moving averages
- **Comparative Analysis**: Inter-party and bloc-level comparison
- **Predictive Intelligence**: Momentum analysis for forecasting
- **Coalition Analysis**: Reliability scoring for government formation
---
### view_riksdagen_coalition_alignment_matrix βββββ
**Category:** Intelligence Views (v1.29)
**Type:** Standard View
**Intelligence Value:** VERY HIGH - Coalition Formation Analysis
**Changelog:** v1.29 OSINT Coalition Intelligence
#### Purpose
Party-pair voting alignment matrix tracking 2-year rolling window of shared voting patterns. Calculates alignment rates, identifies natural coalition partners, and provides automated intelligence assessment of partnership viability for government formation forecasting.
#### Key Columns
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `party_1` | VARCHAR(50) | First party | 'M' |
| `party_2` | VARCHAR(50) | Second party | 'KD' |
| `alignment_rate` | NUMERIC(5,2) | Percentage voting together | 89.50 |
| `shared_votes` | INTEGER | Number of ballots both voted on | 1247 |
| `votes_aligned` | INTEGER | Times voted the same way | 1116 |
| `votes_opposed` | INTEGER | Times voted oppositely | 131 |
| `coalition_likelihood` | VARCHAR(50) | Viability classification | 'VERY_HIGH' |
| `bloc_relationship` | VARCHAR(50) | Bloc classification | 'RIGHT_BLOC_INTERNAL' |
| `intelligence_assessment` | TEXT | Automated commentary | 'Strong natural coalition partners...' |
#### Coalition Likelihood Classifications
| Classification | Alignment Rate | Description |
|---------------|----------------|-------------|
| **VERY_HIGH** | β₯ 80% | Strong natural partners, consistent alignment |
| **HIGH** | β₯ 65% | Viable coalition, good compatibility |
| **MEDIUM** | β₯ 50% | Possible with negotiations, some differences |
| **LOW** | β₯ 35% | Difficult coalition, fundamental disagreements |
| **VERY_LOW** | < 35% | Coalition highly unlikely, opposing ideologies |
#### Bloc Relationship Types
- **LEFT_BLOC_INTERNAL**: S-V, S-MP, V-MP (traditional red-green alliances)
- **RIGHT_BLOC_INTERNAL**: M-KD, M-L, M-C, KD-L, etc. (Alliance partners)
- **CROSS_BLOC**: S-C, M-S (centrist cooperation, "Grand Coalition")
- **SD_RELATIONSHIP**: Any party paired with SD (Sweden Democrats)
- **UNAFFILIATED**: Other combinations
#### Example Queries
**1. Current Coalition Viability Matrix (All Party Pairs)**
```sql
SELECT
party_1,
party_2,
ROUND(alignment_rate, 2) AS alignment,
shared_votes,
coalition_likelihood,
bloc_relationship
FROM view_riksdagen_coalition_alignment_matrix
WHERE shared_votes >= 100 -- Sufficient sample size
ORDER BY alignment_rate DESC;
Output:
party_1 | party_2 | alignment | shared_votes | coalition_likelihood | bloc_relationship
---------+---------+-----------+--------------+---------------------+-------------------
M | KD | 89.50 | 1247 | VERY_HIGH | RIGHT_BLOC_INTERNAL
S | V | 87.20 | 1198 | VERY_HIGH | LEFT_BLOC_INTERNAL
KD | L | 82.30 | 1156 | VERY_HIGH | RIGHT_BLOC_INTERNAL
2. Potential Government Coalitions (Majority Analysis)
WITH party_seats AS (
SELECT party, member_count AS seats
FROM view_riksdagen_party
WHERE member_count > 0
),
coalition_combos AS (
SELECT
cam.party_1,
cam.party_2,
ps1.seats AS seats_1,
ps2.seats AS seats_2,
ps1.seats + ps2.seats AS combined_seats,
cam.alignment_rate,
cam.coalition_likelihood
FROM view_riksdagen_coalition_alignment_matrix cam
JOIN party_seats ps1 ON ps1.party = cam.party_1
JOIN party_seats ps2 ON ps2.party = cam.party_2
WHERE cam.coalition_likelihood IN ('VERY_HIGH', 'HIGH')
)
SELECT
party_1,
party_2,
combined_seats,
ROUND(alignment_rate, 2) AS alignment,
coalition_likelihood,
CASE
WHEN combined_seats >= 175 THEN 'MAJORITY'
WHEN combined_seats >= 165 THEN 'NEAR_MAJORITY'
ELSE 'INSUFFICIENT'
END AS government_viability
FROM coalition_combos
WHERE combined_seats >= 165
ORDER BY combined_seats DESC, alignment_rate DESC;
3. Cross-Bloc Cooperation Opportunities
SELECT
party_1,
party_2,
ROUND(alignment_rate, 2) AS alignment,
shared_votes,
coalition_likelihood,
intelligence_assessment
FROM view_riksdagen_coalition_alignment_matrix
WHERE bloc_relationship = 'CROSS_BLOC'
AND alignment_rate >= 50 -- Realistic cooperation threshold
ORDER BY alignment_rate DESC;
4. Sweden Democrats Coalition Potential
SELECT
CASE
WHEN party_1 = 'SD' THEN party_2
ELSE party_1
END AS other_party,
ROUND(alignment_rate, 2) AS alignment_with_sd,
shared_votes,
coalition_likelihood,
intelligence_assessment
FROM view_riksdagen_coalition_alignment_matrix
WHERE party_1 = 'SD' OR party_2 = 'SD'
ORDER BY alignment_rate DESC;
5. Coalition Stability Trends (Requires Time-Series Extension)
-- Current vs Historical Comparison (if view extended with time dimension)
SELECT
party_1,
party_2,
ROUND(alignment_rate, 2) AS current_alignment,
LAG(ROUND(alignment_rate, 2)) OVER (
PARTITION BY party_1, party_2
ORDER BY analysis_date
) AS previous_alignment,
ROUND(alignment_rate - LAG(alignment_rate) OVER (
PARTITION BY party_1, party_2
ORDER BY analysis_date
), 2) AS alignment_change
FROM view_riksdagen_coalition_alignment_matrix
WHERE analysis_date >= CURRENT_DATE - INTERVAL '24 months'
ORDER BY party_1, party_2, analysis_date DESC;
``$
#### \text{Performance} \text{Characteristics}
- **\text{Query} \text{Time}:** 200-400\text{ms} (\text{complex} \text{cross}-\text{join} \text{aggregation})
- **\text{Indexes} \text{Used}:** \text{Vote} \text{summary} \text{indexes}, \text{party} \text{indexes}
- **\text{Data} \text{Volume}:** ~36 \text{rows} (8 \text{active} \text{parties} \times 8 = 64 \text{pairs}, \text{minus} \text{self}-\text{pairs})
- **\text{Refresh} \text{Frequency}:** \text{Daily} \text{recalculation} \text{recommended}
- **\text{Optimization}:** \text{Strong} \text{candidate} \text{for} \text{materialized} \text{view}
#### \text{Data} \text{Sources}
- **\text{Primary} \text{View}:** $view_riksdagen_vote_data_ballot_party_summary_daily`
- **Calculation:** Cross-join of parties with alignment calculation
- **Window:** Rolling 2-year period for stability
#### Dependencies
- Depends on: `view_riksdagen_vote_data_ballot_party_summary_daily`
- Used by: `view_riksdagen_intelligence_dashboard`, coalition forecasting tools
#### Risk Rules Supported
From [RISK_RULES_INTOP_OSINT.md](RISK_RULES_INTOP_OSINT.md):
- **PartyCoalitionUnstable (Y-02)**: Alignment metrics for stability assessment
- **PartyIsolated (Y-05)**: Identifies parties with low alignment across board
#### Intelligence Frameworks Applicable
From [DATA_ANALYSIS_INTOP_OSINT.md](DATA_ANALYSIS_INTOP_OSINT.md):
- **Coalition Analysis**: Primary use case - government formation forecasting
- **Network Analysis**: Party relationship mapping
- **Predictive Intelligence**: Election outcome scenario planning
- **Comparative Analysis**: Bloc cohesion vs. cross-bloc cooperation
---
### view_riksdagen_party_decision_flow βββββ
**Category:** Decision Flow Views (NEW in v1.35)
**Type:** Standard View
**Intelligence Value:** VERY HIGH - Party Legislative Effectiveness
**Changelog:** v1.35 Party Decision Flow Analysis
#### Purpose
Aggregates proposal decision data by party, enabling analysis of party-level legislative effectiveness, coalition alignment on proposals, committee influence, and temporal decision patterns. Provides comprehensive party scorecards showing success rates in getting proposals approved or rejected.
#### Key Columns
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `party` | VARCHAR(255) | Party short code | 'S', 'M', 'SD' |
| `committee` | VARCHAR(255) | Committee processing proposal | 'Finansutskottet' |
| `decision_type` | VARCHAR(255) | Type of decision | 'UtlΓ₯tande', 'BetΓ€nkande' |
| `committee_org` | VARCHAR(255) | Committee organization code | 'FiU' |
| `decision_month` | TIMESTAMP | Month of decision (truncated) | '2024-10-01 00:00:00' |
| `decision_year` | NUMERIC | Year of decision | 2024 |
| `decision_month_num` | NUMERIC | Month number (1-12) | 10 |
| `total_proposals` | BIGINT | Total proposals processed | 45 |
| `approved_proposals` | BIGINT | Proposals approved (bifall) | 32 |
| `rejected_proposals` | BIGINT | Proposals rejected (avslag) | 10 |
| `referred_back_proposals` | BIGINT | Proposals referred back | 2 |
| `other_decisions` | BIGINT | Other decision outcomes | 1 |
| `approval_rate` | NUMERIC(5,2) | Percentage approved | 71.11 |
| `rejection_rate` | NUMERIC(5,2) | Percentage rejected | 22.22 |
| `earliest_decision_date` | DATE | First decision in period | '2024-10-01' |
| `latest_decision_date` | DATE | Last decision in period | '2024-10-31' |
#### Swedish Decision Terms
The view recognizes Swedish parliamentary decision terminology:
| Swedish Term | English | Aggregation Column |
|-------------|---------|-------------------|
| **Bifall** / Bifalla / GodkΓ€nt | Approval/Accepted | `approved_proposals` |
| **Avslag** / AvslΓ₯ | Rejection/Denied | `rejected_proposals` |
| **Γ
terfΓΆrvisning** / Γ
terfΓΆrvisa | Referral back to committee | `referred_back_proposals` |
#### Example Queries
**1. Party Success Rates (Current Year)**
```sql
SELECT
party,
SUM(total_proposals) AS total,
SUM(approved_proposals) AS approved,
SUM(rejected_proposals) AS rejected,
ROUND(
100.0 * SUM(approved_proposals) / NULLIF(SUM(total_proposals), 0),
2
) AS overall_approval_rate
FROM view_riksdagen_party_decision_flow
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY party
ORDER BY overall_approval_rate DESC;
Output:
party | total | approved | rejected | overall_approval_rate
-------+-------+----------+----------+---------------------
S | 234 | 178 | 42 | 76.07
M | 198 | 145 | 38 | 73.23
SD | 156 | 102 | 45 | 65.38
2. Committee Effectiveness by Party
SELECT
committee,
party,
SUM(total_proposals) AS proposals,
SUM(approved_proposals) AS approved,
ROUND(
100.0 * SUM(approved_proposals) / NULLIF(SUM(total_proposals), 0),
2
) AS approval_rate
FROM view_riksdagen_party_decision_flow
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 1
GROUP BY committee, party
HAVING SUM(total_proposals) >= 10 -- Minimum threshold for statistical relevance
ORDER BY committee, approval_rate DESC;
3. Temporal Trends - Party Success Over Time
SELECT
party,
decision_year,
decision_month_num,
TO_CHAR(decision_month, 'YYYY-MM') AS month,
SUM(total_proposals) AS proposals,
SUM(approved_proposals) AS approved,
ROUND(AVG(approval_rate), 2) AS avg_approval_rate
FROM view_riksdagen_party_decision_flow
WHERE decision_month >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY party, decision_year, decision_month_num, decision_month
ORDER BY party, decision_year DESC, decision_month_num DESC;
4. Coalition Alignment Analysis
Compare decision patterns between government and opposition parties:
WITH party_decisions AS (
SELECT
party,
SUM(total_proposals) AS total,
SUM(approved_proposals) AS approved,
SUM(rejected_proposals) AS rejected,
ROUND(
100.0 * SUM(approved_proposals) / NULLIF(SUM(total_proposals), 0),
2
) AS approval_rate
FROM view_riksdagen_party_decision_flow
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY party
)
SELECT
pd.*,
CASE
WHEN party IN ('M', 'SD', 'KD', 'L') THEN 'GOVERNMENT'
WHEN party IN ('S', 'V', 'MP', 'C') THEN 'OPPOSITION'
ELSE 'OTHER'
END AS bloc,
ROUND(approval_rate - (SELECT AVG(approval_rate) FROM party_decisions), 2) AS vs_avg
FROM party_decisions pd
ORDER BY bloc, approval_rate DESC;
5. Committee Influence by Party (Which committees favor which parties?)
SELECT
committee,
party,
SUM(total_proposals) AS proposals,
ROUND(AVG(approval_rate), 2) AS avg_approval_rate,
RANK() OVER (PARTITION BY committee ORDER BY AVG(approval_rate) DESC) AS party_rank
FROM view_riksdagen_party_decision_flow
WHERE decision_year >= EXTRACT(YEAR FROM CURRENT_DATE) - 2
GROUP BY committee, party
HAVING SUM(total_proposals) >= 5
ORDER BY committee, party_rank;
6. Decision Pattern Analysis (Approval vs Rejection Trends)
SELECT
decision_year,
party,
SUM(total_proposals) AS total,
SUM(approved_proposals) AS approved,
SUM(rejected_proposals) AS rejected,
SUM(referred_back_proposals) AS referred_back,
ROUND(100.0 * SUM(approved_proposals) / NULLIF(SUM(total_proposals), 0), 2) AS approval_pct,
ROUND(100.0 * SUM(rejected_proposals) / NULLIF(SUM(total_proposals), 0), 2) AS rejection_pct
FROM view_riksdagen_party_decision_flow
WHERE decision_year >= 2020
GROUP BY decision_year, party
ORDER BY decision_year DESC, party;
7. Government vs Opposition Success Rates
WITH bloc_classification AS (
SELECT
*,
CASE
WHEN party IN ('M', 'SD', 'KD', 'L') THEN 'GOVERNMENT_BLOC'
WHEN party IN ('S', 'V', 'MP', 'C') THEN 'OPPOSITION_BLOC'
ELSE 'INDEPENDENT'
END AS political_bloc
FROM view_riksdagen_party_decision_flow
WHERE decision_year = EXTRACT(YEAR FROM CURRENT_DATE)
)
SELECT
political_bloc,
COUNT(DISTINCT party) AS party_count,
SUM(total_proposals) AS total_proposals,
SUM(approved_proposals) AS approved_proposals,
ROUND(
100.0 * SUM(approved_proposals) / NULLIF(SUM(total_proposals), 0),
2
) AS bloc_approval_rate
FROM bloc_classification
GROUP BY political_bloc
ORDER BY bloc_approval_rate DESC;
Performance Characteristics
- Query Time: 50-200ms (depends on date range and aggregation)
- Indexes: Base table indexes on proposal data and document data
- Data Volume: Typically 500-2000 rows per year (varies by proposal activity)
- Refresh: Real-time (standard view)
- Optimization: For heavy analytical use, consider materializing
Data Sources
Primary Tables:
document_proposal_data- Proposal details and decisionsdocument_proposal_container- Linkage structuredocument_status_container- Status informationdocument_data- Document metadata and datesdocument_person_reference_da_0- Party attribution
Join Path:
document_proposal_data
β document_proposal_container (proposal_document_proposal_c_0)
β document_status_container (document_proposal_document_s_0)
β document_data (document_document_status_con_0)
β document_person_reference_co_0 (document_person_reference_co_1)
β document_person_reference_da_0 (document_person_reference_li_1)
Dependencies
- Depends on: Base tables (no view dependencies)
- Used by: Party scorecards, coalition analysis, committee effectiveness dashboards
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PartyWeakSupport (Y-01): Low approval rates indicate weak legislative position
- PartyCoalitionUnstable (Y-02): Divergent approval rates indicate coalition stress
- PartyLowDiscipline (Y-03): Inconsistent decision patterns suggest internal divisions
- PartyIsolated (Y-05): Low approval rates across committees indicate marginalization
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
| Framework | Application | Example Analysis |
|---|---|---|
| Temporal Analysis | Track party effectiveness trends over time | Monthly approval rate trajectories |
| Comparative Analysis | Party-to-party effectiveness comparison | Government vs opposition success rates |
| Pattern Recognition | Identify committee specializations | Which parties succeed in which committees |
| Predictive Intelligence | Forecast proposal outcomes | Based on party sponsorship and committee |
| Coalition Analysis | Assess coalition alignment on decisions | Do coalition partners have similar approval rates? |
Intelligence Products Generated:
- π Party Legislative Scorecards - Success rates, committee effectiveness
- π€ Coalition Alignment Reports - Decision pattern convergence/divergence
- π Committee Influence Maps - Which parties control which committees
- π Temporal Effectiveness Trends - Is party legislative power growing or declining?
Data Flow: See Intelligence Data Flow Map - Party Views for complete data pipeline.
Integration with Product Features
From BUSINESS_PRODUCT_DOCUMENT.md:
- Party Dashboard (Product Line 1): Legislative effectiveness metrics
- Coalition Analysis (Product Line 2): Formation scenario modeling
- Committee Analytics (Product Line 2): Committee influence assessment
- Comparative Analytics (Product Line 2): Party-to-party benchmarking
Intelligence Applications
1. Party Scorecards
- Legislative effectiveness tracking (approval vs rejection rates)
- Committee specialization identification
- Temporal trend analysis (improving or declining)
2. Coalition Analysis
- Government formation scenarios (which parties work well together on proposals?)
- Coalition stability assessment (diverging approval rates = coalition stress)
- Cross-bloc cooperation opportunities
3. Committee Effectiveness
- Party influence in different committees
- Committee chair performance (approval rates under their leadership)
- Proposal routing optimization (which committee most favorable for party's proposals)
4. Strategic Intelligence
- Early warning: Declining approval rates signal weakening position
- Opportunity identification: High approval rates in specific committees
- Opposition strategy: Which proposals have best chance of success?
5. OSINT Research Applications
- Academic research on legislative effectiveness
- Journalism: Data-driven political analysis
- Citizen engagement: Understanding how parties perform on proposals
- Think tanks: Evidence-based policy recommendations
Notes
- Empty Data Warning: View will be empty if
document_proposal_datahas no records with party references - Swedish Language: Decision terms use official Riksdag Swedish terminology
- Party Attribution: Requires person reference data linking documents to parties
- Historical Analysis: Effective for analyzing any time period with available data
view_riksdagen_party_summary ββββ
Category: Party Views (v1.61 - Recreated)
Type: Standard View
Intelligence Value: HIGH - Party Assignment & Document Aggregation
Changelog: v1.61 Recreation after v1.6 drop
π Purpose
Aggregates assignment data and document statistics at party level. Provides comprehensive party-level metrics including assignments, days served across different roles, active members, document production, and collaboration patterns. Foundation view for party comparison and performance tracking.
Note: Originally created in early versions, dropped in v1.6, and recreated in v1.61 after JPA entity mismatch discovery.
π Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
party | VARCHAR(50) | Party short code (PK) | 'S', 'M', 'SD' |
first_assignment_date | DATE | First party assignment | '2002-10-01' |
last_assignment_date | DATE | Most recent assignment | '2024-12-15' |
total_assignments | BIGINT | All assignments across members | 2847 |
current_assignments | BIGINT | Active assignments | 156 |
total_days_served | BIGINT | Total service days (all roles) | 890456 |
total_days_served_parliament | BIGINT | Parliamentary service days | 456789 |
total_days_served_committee | BIGINT | Committee service days | 234567 |
total_days_served_government | BIGINT | Government service days | 123456 |
total_days_served_eu | BIGINT | EU representative days | 12345 |
total_days_served_speaker | BIGINT | Speaker role days | 5678 |
total_days_served_party | BIGINT | Party leadership days | 45678 |
active | BOOLEAN | Has any active members | true |
active_parliament | BOOLEAN | Has parliamentary members | true |
active_government | BOOLEAN | Has government members | false |
active_committee | BOOLEAN | Has committee members | true |
total_active | BIGINT | Count of active members | 68 |
total_active_parliament | BIGINT | Active parliamentarians | 68 |
total_active_government | BIGINT | Active government members | 0 |
total_active_committee | BIGINT | Active committee members | 102 |
total_documents | BIGINT | Documents produced | 8542 |
avg_documents_per_member | NUMERIC | Avg docs per member | 125.62 |
total_party_motions | BIGINT | Party-wide motions | 234 |
total_individual_motions | BIGINT | Individual member motions | 5678 |
very_high_activity_members | BIGINT | Members with >100 docs | 12 |
high_activity_members | BIGINT | Members with 50-100 docs | 23 |
medium_activity_members | BIGINT | Members with 10-49 docs | 28 |
low_activity_members | BIGINT | Members with <10 docs | 5 |
currently_active_members | BIGINT | Active in last year | 64 |
total_documents_last_year | BIGINT | Docs last 12 months | 1245 |
avg_documents_last_year | NUMERIC | Avg docs/member last year | 19.45 |
π‘ Example SQL Queries
1. Party Activity Comparison
SELECT
party,
total_active_parliament AS current_seats,
total_documents AS lifetime_docs,
total_documents_last_year AS recent_docs,
ROUND(avg_documents_per_member, 2) AS productivity,
very_high_activity_members + high_activity_members AS productive_members,
ROUND(100.0 * currently_active_members / NULLIF(total_active, 0), 2) AS active_pct
FROM view_riksdagen_party_summary
WHERE active = true
ORDER BY current_seats DESC;
2. Government vs Opposition Experience
SELECT
party,
active_parliament,
active_government,
total_days_served_government AS govt_experience_days,
ROUND(total_days_served_government::NUMERIC / 365.25, 1) AS govt_experience_years,
total_days_served_parliament AS parliament_days,
ROUND(100.0 * total_days_served_government / NULLIF(total_days_served_parliament, 0), 2) AS govt_pct
FROM view_riksdagen_party_summary
WHERE active = true
ORDER BY govt_experience_days DESC;
3. Member Activity Distribution
SELECT
party,
total_active AS members,
very_high_activity_members AS very_high,
high_activity_members AS high,
medium_activity_members AS medium,
low_activity_members AS low,
ROUND(100.0 * very_high_activity_members / NULLIF(total_active, 0), 1) AS elite_pct
FROM view_riksdagen_party_summary
WHERE active = true
ORDER BY elite_pct DESC;
β‘ Performance Characteristics
- Query Time: <10ms (small result set, indexed on PK)
- Indexes Used: Primary key on
party - Data Volume: ~10-15 rows (active parties)
- Refresh Frequency: Real-time (standard view)
- Dependencies: Aggregates from
view_riksdagen_politiciananddocument_data
π Dependencies
Upstream:
view_riksdagen_politician- Individual politician aggregationsdocument_data- Document production metricsdocument_status_container- Document linkagedocument_person_reference_*- Party attribution
Downstream:
- Used by other party comparison queries
- Foundation for party performance analysis
π― Framework Integration
Comparative Analysis:
- Party-to-party productivity comparison
- Government vs opposition experience metrics
- Member activity distribution analysis
Temporal Analysis:
- Service duration tracking across roles
- Historical vs current activity patterns
Pattern Recognition:
- High vs low productivity member identification
- Party activity classification patterns
π― Use Cases
- Party Scorecard Generation - Comprehensive party profiles with assignments, activity, and productivity
- Experience Assessment - Track party expertise in government, committees, parliament
- Member Activity Analysis - Identify high-performing and low-performing member distributions
- Coalition Capacity Assessment - Evaluate party governance experience for coalition formation
view_riksdagen_party_longitudinal_performance βββββ
Category: Party Views (v1.61 - Recreated from v1.53)
Type: Standard View
Intelligence Value: VERY HIGH - Advanced Longitudinal Analysis with Window Functions
Changelog: v1.53 Original, v1.61 Recreated
π Purpose
Tracks party performance evolution across election cycles (2002-2026+) with semester granularity, employing advanced window functions (RANK, PERCENT_RANK, NTILE, LAG, LEAD, STDDEV_POP) for trend detection, performance tier classification, predictive forecasting, and volatility assessment. Enables cross-cycle comparative analysis with Swedish parliamentary context (autumn/spring semesters, pre-election dynamics).
Key Innovation: Combines 7 types of window functions with 3-semester moving averages, z-score calculations, and composite performance indices for sophisticated trend analysis.
π¬ Statistical Methodology
Window Function Coverage:
- RANK() - Party ranking by win rate, participation, size, approval, productivity, discipline (6 dimensions)
- PERCENT_RANK() - Percentile positioning (0.0-1.0) for comparative analysis
- NTILE(4) - Quartile-based performance tiers (1=top 25%, 4=bottom 25%)
- LAG() - Previous semester metrics for trend detection (6 metrics tracked)
- LEAD() - Next semester metrics for predictive forecasting (3 forward-looking metrics)
- STDDEV_POP() - Volatility measurement (sector-wide and party-specific)
- AVG() ROWS BETWEEN 2 PRECEDING - 3-semester moving averages for smoothing
Composite Indices:
- Composite Performance Index: Win rate (35%) + Participation (25%) + Approval (20%) + Size (10%) + Productivity (10%)
- Discipline Effectiveness Score: Participation (50%) + Inverse rebel rate (50%)
- Legislative Effectiveness Index: Win rate (35%) + Participation (25%) + Approval (25%) + Discipline (15%)
π Key Columns (70 Total)
Primary Keys (Composite):
| Column | Type | Description | Example |
|---|---|---|---|
party | VARCHAR(50) | Party code | 'S' |
election_cycle_id | TEXT | Election cycle | '2018-2021' |
semester | TEXT | Semester | 'autumn', 'spring' |
Core Metrics (14 columns):
| Column | Type | Description | Example |
|---|---|---|---|
cycle_year | INTEGER | Year in 4-year cycle (1-4) | 3 |
calendar_year | INTEGER | Actual year | 2024 |
total_ballots | BIGINT | Ballots in semester | 847 |
participation_rate | NUMERIC | Attendance % | 92.5 |
win_rate | NUMERIC | Win % on ballots | 67.8 |
approval_rate | NUMERIC | Decision approval % | 71.2 |
active_members | BIGINT | Member count | 68 |
documents_last_year | BIGINT | Documents produced | 1245 |
avg_rebel_rate | NUMERIC | Party dissent rate | 3.2 |
Ranking Metrics (12 columns - RANK & PERCENT_RANK):
rank_by_win_rate,rank_by_participation,rank_by_size,rank_by_approval,rank_by_productivity,rank_by_disciplinepercentile_win_rate,percentile_participation,percentile_approval,percentile_productivityquartile_by_win_rate,quartile_by_overall_performance
Temporal Metrics (12 columns - LAG & LEAD):
prev_semester_win_rate,prev_semester_participation,prev_semester_members,prev_semester_approvalnext_semester_win_rate,next_semester_participation,next_semester_members- Plus 5 more LAG metrics
Change Metrics (7 columns):
win_rate_change_absolute,win_rate_change_pct,participation_change_absolutemembership_change,approval_rate_change,documents_change,discipline_change
Trajectory Classifications (2 columns):
trajectory_win_rate: ASCENDING, RECOVERING, STABLE, DECLINING, DESCENDING, BASELINEtrajectory_participation: IMPROVING, STABLE, DECLINING, BASELINE
Composite Scores (3 columns):
composite_performance_index(0-100)discipline_effectiveness_score(0-100)legislative_effectiveness_score(0-100)
Volatility Metrics (4 columns + 2 classifications):
stddev_win_rate_sector,stddev_win_rate_party,stddev_participation_sector,stddev_participation_partyvolatility_classification: HIGH_VOLATILITY, MODERATE_VOLATILITY, LOW_VOLATILITYstability_classification: UNSTABLE, MODERATELY_STABLE, STABLE
Predictive Indicators (4 columns):
forecast_trend: EXPECTED_IMPROVEMENT, EXPECTED_DECLINE, EXPECTED_STABLE, NO_FORECASTtrend_deviation_from_ma(vs 3-semester moving average)trend_position: UNDERPERFORMING_VS_TREND, ON_TREND, OVERPERFORMING_VS_TRENDtrajectory_confidence_score(0-100)
Performance Tiers (2 columns):
performance_tier: ELITE_PERFORMER, STRONG_PERFORMER, MODERATE_PERFORMER, WEAK_PERFORMERproductivity_tier: HIGHLY_PRODUCTIVE, MODERATELY_PRODUCTIVE, LOW_PRODUCTIVITY, VERY_LOW_PRODUCTIVITY
Early Warning Flags (1 column):
early_warning_flag: CRITICAL_DECLINE, MODERATE_DECLINE, CRITICAL_PARTICIPATION_DROP, MODERATE_PARTICIPATION_DROP, NORMAL
Election Context Flags (3 columns):
is_pre_election_spring,is_election_autumn,is_election_cycle_end
π‘ Example SQL Queries
1. Current Performance Rankings with Trajectory
SELECT
party,
semester,
win_rate,
rank_by_win_rate,
performance_tier,
trajectory_win_rate,
forecast_trend,
ROUND(composite_performance_index, 2) AS performance_index
FROM view_riksdagen_party_longitudinal_performance
WHERE election_cycle_id = '2022-2025'
AND calendar_year = 2024
AND semester = 'autumn'
ORDER BY rank_by_win_rate;
2. Identify Rising Stars (Improving Performance)
SELECT
party,
election_cycle_id,
calendar_year,
semester,
win_rate,
win_rate_change_absolute,
trajectory_win_rate,
performance_tier,
ROUND(momentum_z_score_win_rate, 2) AS momentum_significance
FROM view_riksdagen_party_longitudinal_performance
WHERE trajectory_win_rate IN ('ASCENDING', 'RECOVERING')
AND calendar_year >= 2022
ORDER BY win_rate_change_absolute DESC
LIMIT 20;
3. Volatility Analysis (High-Risk Parties)
SELECT
party,
ROUND(AVG(win_rate), 2) AS avg_win_rate,
ROUND(MAX(stddev_win_rate_party), 2) AS volatility,
volatility_classification,
COUNT(*) AS semesters_tracked,
STRING_AGG(DISTINCT early_warning_flag, ', ') AS warnings
FROM view_riksdagen_party_longitudinal_performance
WHERE calendar_year >= 2020
GROUP BY party, volatility_classification
ORDER BY volatility DESC;
4. Pre-Election Performance Surges
SELECT
party,
election_cycle_id,
calendar_year,
win_rate,
prev_semester_win_rate,
win_rate_change_absolute AS pre_election_surge,
participation_rate,
documents_last_year
FROM view_riksdagen_party_longitudinal_performance
WHERE is_pre_election_spring = true
AND calendar_year >= 2014
ORDER BY pre_election_surge DESC;
5. Performance Tier Transitions
WITH tier_changes AS (
SELECT
party,
calendar_year,
semester,
performance_tier,
LAG(performance_tier) OVER (PARTITION BY party ORDER BY calendar_year, semester) AS prev_tier
FROM view_riksdagen_party_longitudinal_performance
WHERE calendar_year >= 2018
)
SELECT
party,
calendar_year,
semester,
prev_tier || ' β ' || performance_tier AS tier_transition,
CASE
WHEN performance_tier < prev_tier THEN 'PROMOTED'
WHEN performance_tier > prev_tier THEN 'DEMOTED'
ELSE 'STABLE'
END AS direction
FROM tier_changes
WHERE prev_tier IS NOT NULL
AND performance_tier != prev_tier
ORDER BY calendar_year DESC, party;
6. Predictive Accuracy Assessment
SELECT
party,
calendar_year,
semester,
forecast_trend,
CASE
WHEN forecast_trend = 'EXPECTED_IMPROVEMENT' AND next_semester_win_rate > win_rate THEN 'CORRECT'
WHEN forecast_trend = 'EXPECTED_DECLINE' AND next_semester_win_rate < win_rate THEN 'CORRECT'
WHEN forecast_trend = 'EXPECTED_STABLE' AND ABS(next_semester_win_rate - win_rate) < 3 THEN 'CORRECT'
ELSE 'INCORRECT'
END AS forecast_accuracy
FROM view_riksdagen_party_longitudinal_performance
WHERE next_semester_win_rate IS NOT NULL
AND calendar_year >= 2020;
``$
#### β‘ \text{Performance} \text{Characteristics}
- **\text{Query} \text{Time}:** 100-300\text{ms} (\text{complex} \text{window} \text{functions})
- **\text{Indexes} \text{Suggested}:** \text{Composite} \text{index} \text{on} (\text{party}, \text{election\_cycle\_id}, \text{cycle\_year}, \text{semester})
- **\text{Data} \text{Volume}:** ~800-1200 \text{rows} (8-10 \text{parties} \times 6 \text{cycles} \times 8 \text{semesters}/\text{cycle})
- **\text{Refresh} \text{Frequency}:** \text{Real}-\text{time} (\text{standard} \text{view})
- **\text{Optimization} \text{Note}:** \text{Consider} \text{materialization} \text{for} \text{heavy} \text{analytical} \text{workloads}
#### π \text{Dependencies}
**\text{Upstream}:**
- $view_riksdagen_vote_data_ballot_party_summary_annual` - Core voting metrics
- `view_party_performance_metrics` - Current performance scores
**Downstream:**
- Party trend dashboards
- Election forecasting models
- Coalition stability analysis
#### π― Framework Integration
**Temporal Analysis:**
- Cross-cycle performance evolution
- Semester-to-semester trends
- Pre-election behavioral shifts
**Comparative Analysis:**
- Party-to-party ranking across 6 dimensions
- Percentile-based competitive positioning
- Quartile tier classification
**Pattern Recognition:**
- Trajectory pattern detection (ASCENDING, DECLINING, STABLE)
- Volatility classification (HIGH, MODERATE, LOW)
- Early warning signal identification
**Predictive Intelligence:**
- Next-semester performance forecasting
- Trajectory confidence scoring
- Trend deviation alerts
#### π― Use Cases
1. **Election Forecasting** - Predict party performance based on historical trajectories and moving averages
2. **Coalition Planning** - Assess party reliability via volatility metrics and discipline scores
3. **Performance Benchmarking** - Compare parties using percentile ranks and composite indices
4. **Trend Analysis** - Detect multi-semester trends with LAG/LEAD analysis and moving averages
5. **Risk Assessment** - Identify high-volatility parties with early warning flags
6. **Pre-Election Intelligence** - Track behavioral changes in pre-election semesters
---
### view_riksdagen_party_coalition_evolution βββββ
**Category:** Party Views (v1.61 - Recreated from v1.53)
**Type:** Standard View
**Intelligence Value:** VERY HIGH - Coalition Dynamics & Alliance Tracking
**Changelog:** v1.53 Original, v1.61 Recreated
#### π Purpose
Tracks party-pair alliance and coalition behavior across election cycles with semester granularity. Analyzes voting alignment, coalition strength, breakup risk, strategic shifts, and volatility through advanced window functions. Enables coalition formation forecasting and alliance stability assessment.
**Key Innovation:** Pairwise party analysis with alignment rate calculation, coalition strength rankings, realignment detection, and breakup risk scoring. Employs window functions for temporal tracking and volatility measurement.
#### π¬ Statistical Methodology
**Alignment Calculation:**
``$
\text{Alignment} \text{Rate} = (\text{Aligned} \text{Ballots} / \text{Total} \text{Joint} \text{Ballots}) \times 100
\text{Aligned} \text{Ballot} = \text{Both} \text{parties} \text{vote} \text{same} \text{direction} (\text{both} \text{YES} \text{or} \text{both} \text{NO})
$``
**Vote Divergence:**
Avg Vote Divergence = AVG(|Party1_YES% - Party2_YES%|)
**Stability Score Formula:**
``$
\text{Stability} \text{Score} = (\text{Alignment\_Rate} \times 40%) +
((100 - \text{Avg\_Vote\_Divergence}) \times 30%) +
((100 - \text{Vote\_Divergence\_StdDev}) \times 30%)
$``
**Breakup Risk Scoring:**
- Alliance < 50% and previously β₯ 65%: **90% risk**
- Alliance < 50% with high volatility (stddev > 15): **75% risk**
- Alliance < 65% with decline > 10 points: **60% risk**
- High volatility (stddev > 15): **50% risk**
- Alliance < 50%: **40% risk**
- Recent decline > 8 points: **30% risk**
- Otherwise: **10% risk** (baseline)
#### π Key Columns (35 Total)
**Primary Keys (Composite):**
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `party_1` | VARCHAR(50) | First party (alphabetically) | 'M' |
| `party_2` | VARCHAR(50) | Second party (alphabetically) | 'S' |
| `election_cycle_id` | TEXT | Election cycle | '2018-2021' |
**Core Metrics (13 columns):**
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `semester` | TEXT | Semester (autumn/spring) | 'autumn' |
| `cycle_year` | INTEGER | Year in cycle (1-4) | 3 |
| `calendar_year` | INTEGER | Actual year | 2024 |
| `joint_voting_days` | BIGINT | Days both voted | 156 |
| `joint_ballots` | BIGINT | Total shared ballots | 847 |
| `aligned_ballots` | BIGINT | Ballots voted same | 623 |
| `alignment_rate` | NUMERIC | % of aligned votes | 73.5 |
| `avg_vote_divergence` | NUMERIC | Avg % difference | 26.5 |
| `vote_divergence_stddev` | NUMERIC | Consistency metric | 18.3 |
**Ranking Metrics (9 columns):**
- `rank_by_alignment` - Coalition strength rank (1 = strongest)
- `rank_by_activity` - Joint ballot activity rank
- `rank_by_consistency` - Vote divergence consistency rank
- `percentile_alignment` - Alignment percentile (0.0-1.0)
- `percentile_cohesion` - Cohesion percentile
- `quartile_coalition_strength` - Strength quartile (1-4)
**Temporal Metrics (10 columns - LAG & LEAD):**
- `prev_semester_alignment`, `prev_semester_joint_ballots`, `prev_semester_divergence`
- `next_semester_alignment`, `next_semester_divergence`
**Change Metrics (4 columns):**
- `alignment_change_absolute`, `alignment_change_pct`
- `activity_change`, `divergence_change`
**Coalition Classifications (7 columns):**
| Column | Type | Values | Description |
|--------|------|--------|-------------|
| `coalition_strength` | TEXT | VERY_STRONG (β₯80%), STRONG (β₯65%), MODERATE (β₯50%), WEAK (β₯35%), OPPOSITION (<35%) | Alliance strength tier |
| `coalition_trend` | TEXT | RAPIDLY_STRENGTHENING (+15), STRENGTHENING (+8), IMPROVING (+3), STABLE, DECLINING (-3), WEAKENING (-8), RAPIDLY_WEAKENING (-15) | Direction of change |
| `strategic_shift` | TEXT | COALITION_FORMATION, COALITION_BREAKUP, MAJOR_REALIGNMENT (Β±20), SIGNIFICANT_SHIFT (Β±10), MINOR_SHIFT (Β±5), STABLE | Major realignments |
| `volatility_classification` | TEXT | HIGHLY_VOLATILE (>15), MODERATELY_VOLATILE (>10), SLIGHTLY_VOLATILE (>5), STABLE_PAIR | Alliance stability |
| `consistency_classification` | TEXT | INCONSISTENT (>20), MODERATE (<10), HIGH_CONSISTENCY | Vote pattern consistency |
| `coalition_tier` | TEXT | ELITE_COALITION (top 25%), STRONG_TIER (50-75%), MODERATE_TIER (25-50%), WEAK_TIER (bottom 25%) | Percentile-based tier |
| `bridge_classification` | TEXT | CORE_COALITION_BRIDGE, STRONG_BRIDGE, MODERATE_BRIDGE, WEAK_BRIDGE | Network centrality |
**Predictive Metrics (7 columns):**
- `forecast_trend`: EXPECTED_STRENGTHENING, EXPECTED_WEAKENING, EXPECTED_STABLE, NO_FORECAST
- `alignment_deviation_from_ma`: Deviation from 3-semester moving average
- `trend_position`: BELOW_TREND, ON_TREND, ABOVE_TREND
- `momentum_z_score`: Statistical significance of alignment change
- `stability_score` (0-100): Composite stability index
- `breakup_risk_score` (0-100): Coalition dissolution probability
- `realignment_probability`: HIGH, MODERATE, LOW, VERY_LOW
**Network Metrics (2 columns):**
- `coalition_density_score`: Alignment Γ activity weight
- `bridge_classification`: Coalition network position
#### π‘ Example SQL Queries
**1. Current Coalition Landscape**
```sql
SELECT
party_1,
party_2,
alignment_rate,
coalition_strength,
coalition_trend,
rank_by_alignment,
ROUND(stability_score, 2) AS stability,
breakup_risk_score AS risk
FROM view_riksdagen_party_coalition_evolution
WHERE election_cycle_id = '2022-2025'
AND calendar_year = 2024
AND semester = 'autumn'
AND coalition_strength IN ('VERY_STRONG_COALITION', 'STRONG_COALITION')
ORDER BY rank_by_alignment;
2. Coalition Formation Detection
SELECT
party_1,
party_2,
calendar_year,
semester,
prev_semester_alignment AS before,
alignment_rate AS after,
alignment_change_absolute AS change,
strategic_shift
FROM view_riksdagen_party_coalition_evolution
WHERE strategic_shift = 'COALITION_FORMATION'
AND calendar_year >= 2018
ORDER BY calendar_year DESC, alignment_rate DESC;
3. Breakup Risk Assessment
SELECT
party_1,
party_2,
election_cycle_id,
alignment_rate,
coalition_trend,
breakup_risk_score,
ROUND(stability_score, 2) AS stability,
volatility_classification
FROM view_riksdagen_party_coalition_evolution
WHERE breakup_risk_score >= 50
AND calendar_year = 2024
ORDER BY breakup_risk_score DESC;
4. Cross-Bloc Cooperation Analysis
WITH bloc_pairs AS (
SELECT
*,
CASE
WHEN party_1 IN ('S', 'V', 'MP') AND party_2 IN ('M', 'SD', 'KD', 'L') THEN 'CROSS_BLOC'
WHEN party_1 IN ('S', 'V', 'MP') AND party_2 IN ('S', 'V', 'MP') THEN 'LEFT_BLOC'
WHEN party_1 IN ('M', 'SD', 'KD', 'L') AND party_2 IN ('M', 'SD', 'KD', 'L') THEN 'RIGHT_BLOC'
END AS bloc_type
FROM view_riksdagen_party_coalition_evolution
WHERE calendar_year >= 2022
)
SELECT
bloc_type,
ROUND(AVG(alignment_rate), 2) AS avg_alignment,
COUNT(*) AS pair_count,
STRING_AGG(DISTINCT party_1 || '-' || party_2, ', ') AS examples
FROM bloc_pairs
GROUP BY bloc_type
ORDER BY avg_alignment DESC;
5. Volatile Coalition Tracking
SELECT
party_1,
party_2,
ROUND(AVG(alignment_rate), 2) AS avg_alignment,
ROUND(MAX(stddev_alignment_pair), 2) AS volatility,
COUNT(*) AS semesters,
STRING_AGG(DISTINCT coalition_trend ORDER BY coalition_trend, ', ') AS trends_observed
FROM view_riksdagen_party_coalition_evolution
WHERE volatility_classification IN ('HIGHLY_VOLATILE_PAIR', 'MODERATELY_VOLATILE_PAIR')
AND calendar_year >= 2018
GROUP BY party_1, party_2
ORDER BY volatility DESC;
6. Elite Coalition Bridges (Network Centrality)
SELECT
party_1,
party_2,
alignment_rate,
percentile_alignment,
percentile_cohesion,
bridge_classification,
coalition_density_score
FROM view_riksdagen_party_coalition_evolution
WHERE bridge_classification IN ('CORE_COALITION_BRIDGE', 'STRONG_BRIDGE')
AND calendar_year = 2024
ORDER BY coalition_density_score DESC;
``$
#### β‘ \text{Performance} \text{Characteristics}
- **\text{Query} \text{Time}:** 150-400\text{ms} (\text{party} \text{pair} \text{cartesian} \text{join} + \text{window} \text{functions})
- **\text{Indexes} \text{Suggested}:** \text{Composite} \text{index} \text{on} (\text{party\_1}, \text{party\_2}, \text{election\_cycle\_id}, \text{cycle\_year}, \text{semester})
- **\text{Data} \text{Volume}:** ~2800-4200 \text{rows} (28-45 \text{party} \text{pairs} \times 6 \text{cycles} \times 8 \text{semesters}/\text{cycle})
- **\text{Refresh} \text{Frequency}:** \text{Real}-\text{time} (\text{standard} \text{view})
- **\text{Minimum} \text{Activity} \text{Filter}:** \text{Requires} β₯5 \text{joint} \text{voting} \text{days} \text{per} \text{semester}
#### π \text{Dependencies}
**\text{Upstream}:**
- $view_riksdagen_vote_data_ballot_party_summary_annual` - Party voting data
**Downstream:**
- Coalition formation forecasting
- Government stability analysis
- Bloc alignment tracking
#### π― Framework Integration
**Network Analysis:**
- Party relationship mapping
- Coalition bridge identification
- Cross-bloc cooperation patterns
**Temporal Analysis:**
- Coalition evolution tracking
- Strategic realignment detection
- Breakup timeline analysis
**Comparative Analysis:**
- Alliance strength ranking
- Cross-cycle coalition comparison
- Bloc cohesion assessment
**Predictive Intelligence:**
- Breakup risk forecasting
- Realignment probability
- Next-semester alignment prediction
#### π― Use Cases
1. **Government Formation** - Identify viable coalition combinations based on historical alignment
2. **Coalition Stability Monitoring** - Track breakup risk and volatility for existing governments
3. **Strategic Realignment Detection** - Identify major shifts in party alliances
4. **Cross-Bloc Analysis** - Detect emerging cooperation patterns between left/right blocs
5. **Network Centrality** - Identify "bridge" parties critical to coalition formation
6. **Pre-Election Intelligence** - Track alliance shifts before elections
---
### view_riksdagen_party_electoral_trends βββββ
**Category:** Party Views (v1.61 - Recreated from v1.53)
**Type:** Standard View
**Intelligence Value:** VERY HIGH - Electoral Performance & Seat Forecasting
**Changelog:** v1.53 Original, v1.61 Recreated
#### π Purpose
Analyzes party electoral performance across election cycles with semester granularity, tracking seat counts (via active member proxy), electoral growth trajectories, performance tiers, and election readiness. Employs window functions for trend analysis, percentile ranking, and predictive seat forecasting.
**Key Innovation:** Combines performance metrics with seat proxies and electoral forecasting. Uses moving averages, z-scores, and composite indices for multi-dimensional electoral strength assessment.
#### π¬ Statistical Methodology
**Seat Count Proxy:**
Seat Count Proxy = Active Members (from view_party_performance_metrics) Note: Actual seat allocation data not directly available, using active member count as proxy
**Composite Electoral Score Formula:**
``$
\text{Electoral} \text{Score} = (\text{Seat\_Count\_Normalized} \times 50%) +
(\text{Win\_Rate} \times 30%) +
(\text{Documents\_Normalized} \times 20%)
\text{where} \text{normalized} = (\text{value} / \text{max\_value\_in\_semester}) \times \text{scale\_factor}
$``
**Legislative Effectiveness Index:**
``$
\text{Legislative} \text{Effectiveness} = (\text{Win\_Rate} \times 35%) +
(\text{Participation\_Rate} \times 25%) +
(\text{Approval\_Rate} \times 25%) +
((100 - \text{Rebel\_Rate}) \times 15%)
$``
**Election Readiness Score** (pre-election spring semester only):
``$
\text{Readiness} = (\text{Win\_Rate} \times 30%) +
(\text{Participation\_Rate} \times 20%) +
(\text{Approval\_Rate} \times 20%) +
(\text{Seat\_Normalized} \times 20%) +
(\text{Productivity\_Normalized} \times 10%)
$``
#### π Key Columns (49 Total)
**Primary Keys (Composite):**
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `party` | VARCHAR(50) | Party code | 'S' |
| `election_cycle_id` | TEXT | Election cycle | '2018-2021' |
**Core Metrics (13 columns):**
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `semester` | TEXT | Semester | 'spring' |
| `cycle_year` | INTEGER | Year in cycle (1-4) | 4 |
| `calendar_year` | INTEGER | Actual year | 2022 |
| `ballots_participated` | BIGINT | Ballots voted on | 847 |
| `win_rate` | NUMERIC | Win % | 67.8 |
| `yes_rate` | NUMERIC | Yes vote % | 52.3 |
| `approval_rate` | NUMERIC | Approval % | 71.2 |
| `participation_rate` | NUMERIC | Attendance % | 92.5 |
| `seat_count_proxy` | BIGINT | Active members (seat estimate) | 68 |
| `documents_produced` | BIGINT | Documents authored | 1245 |
| `avg_rebel_rate` | NUMERIC | Party dissent rate | 3.2 |
**Ranking Metrics (9 columns):**
- `rank_by_seats` - Size-based ranking
- `rank_by_win_rate` - Performance ranking
- `rank_by_productivity` - Document output ranking
- `rank_by_engagement` - Participation ranking
- `rank_by_effectiveness` - Approval rate ranking
- `percentile_seats`, `percentile_win_rate`, `percentile_productivity`
- `quartile_by_size`, `quartile_by_performance`
**Temporal Metrics (11 columns - LAG & LEAD):**
- `prev_semester_seats`, `prev_semester_win_rate`, `prev_semester_documents`, `prev_semester_participation`
- `next_semester_seats`, `next_semester_win_rate`
- Plus stddev metrics: `stddev_seats_sector`, `stddev_win_rate_sector`, `stddev_seats_party`, `stddev_win_rate_party`
- Moving averages: `ma_3semester_seats`, `ma_3semester_win_rate`
**Change Metrics (6 columns):**
- `seat_change_absolute`, `seat_change_pct`
- `win_rate_change_absolute`, `win_rate_change_pct`
- `documents_change`
**Electoral Classifications (8 columns):**
| Column | Type | Values | Description |
|--------|------|--------|-------------|
| `electoral_trend` | TEXT | SURGING (+10), STRONG_GROWTH (+5), GROWTH (+1), STABLE, DECLINE (-1), STRONG_DECLINE (-5), COLLAPSING (-10) | Seat trajectory |
| `party_size_category` | TEXT | DOMINANT (β₯100), MAJOR (β₯75), LARGE (β₯50), MEDIUM (β₯30), SMALL (β₯15), MINOR (<15) | Size classification |
| `volatility_classification` | TEXT | HIGHLY_VOLATILE (>15), MODERATELY_VOLATILE (>10), SLIGHTLY_VOLATILE (>5), STABLE_PARTY | Electoral stability |
| `seat_forecast` | TEXT | EXPECTED_GROWTH, EXPECTED_DECLINE, EXPECTED_SLIGHT_GROWTH, EXPECTED_SLIGHT_DECLINE, EXPECTED_STABLE, NO_FORECAST | Next semester prediction |
| `performance_forecast` | TEXT | EXPECTED_IMPROVEMENT, EXPECTED_DETERIORATION, EXPECTED_STABLE, NO_FORECAST | Performance direction |
| `trend_position_seats` | TEXT | SIGNIFICANTLY_ABOVE_TREND (+5), ABOVE_TREND (+2), ON_TREND, BELOW_TREND (-2), SIGNIFICANTLY_BELOW_TREND (-5) | vs Moving Average |
| `electoral_tier` | TEXT | TOP_ELECTORAL_TIER (top 25%), UPPER_MID_TIER (50-75%), LOWER_MID_TIER (25-50%), BOTTOM_TIER (bottom 25%) | Percentile tier |
| `electoral_warning_flag` | TEXT | CRITICAL_SEAT_LOSS, SIGNIFICANT_SEAT_LOSS, CRITICAL_PERFORMANCE_DROP, CRITICAL_ENGAGEMENT_DROP, SEAT_LOSS, PERFORMANCE_WARNING, NORMAL | Alert system |
**Composite Scores (3 columns):**
- `composite_electoral_score` (0-100): Multi-dimensional electoral strength
- `legislative_effectiveness_index` (0-100): Policy influence capacity
- `election_readiness_score` (0-100): Pre-election preparedness (spring semester only)
**Momentum & Deviation Metrics (5 columns):**
- `seat_deviation_from_ma`: Seats vs 3-semester moving average
- `momentum_z_score_seats`: Statistical significance of seat change
- `momentum_z_score_win_rate`: Statistical significance of performance change
- `projected_seat_change`: Linear projection based on LAG/LEAD
- Early warning and cycle context flags
**Election Context Flags (3 columns):**
- `is_pre_election_period` - Final spring before election
- `is_election_period` - Autumn during election year
- `is_post_election_period` - First spring after election
#### π‘ Example SQL Queries
**1. Current Electoral Standings**
```sql
SELECT
party,
seat_count_proxy AS current_seats,
rank_by_seats,
party_size_category,
electoral_tier,
ROUND(composite_electoral_score, 2) AS electoral_strength,
electoral_trend,
seat_change_absolute AS momentum
FROM view_riksdagen_party_electoral_trends
WHERE election_cycle_id = '2022-2025'
AND calendar_year = 2024
AND semester = 'autumn'
ORDER BY rank_by_seats;
2. Election Readiness Assessment (Pre-Election)
SELECT
party,
seat_count_proxy,
ROUND(election_readiness_score, 2) AS readiness,
ROUND(win_rate, 2) AS win_rate,
ROUND(participation_rate, 2) AS turnout,
documents_produced,
electoral_trend
FROM view_riksdagen_party_electoral_trends
WHERE is_pre_election_period = true
AND calendar_year >= 2018
ORDER BY calendar_year DESC, readiness DESC;
3. Electoral Momentum Tracking
SELECT
party,
calendar_year,
seat_count_proxy AS seats,
seat_change_absolute AS change,
seat_change_pct AS change_pct,
electoral_trend,
ROUND(momentum_z_score_seats, 2) AS momentum_significance
FROM view_riksdagen_party_electoral_trends
WHERE calendar_year >= 2018
AND electoral_trend IN ('SURGING', 'STRONG_GROWTH', 'STRONG_DECLINE', 'COLLAPSING')
ORDER BY calendar_year DESC, ABS(momentum_z_score_seats) DESC;
4. Volatility Risk Analysis
SELECT
party,
ROUND(AVG(seat_count_proxy), 1) AS avg_seats,
ROUND(MAX(stddev_seats_party), 2) AS seat_volatility,
volatility_classification,
COUNT(*) AS semesters_tracked,
MAX(seat_count_proxy) - MIN(seat_count_proxy) AS seat_range
FROM view_riksdagen_party_electoral_trends
WHERE calendar_year >= 2018
GROUP BY party, volatility_classification
ORDER BY seat_volatility DESC;
5. Electoral Forecast Accuracy
WITH forecasts AS (
SELECT
party,
calendar_year,
semester,
seat_count_proxy AS current_seats,
next_semester_seats,
seat_forecast,
CASE
WHEN seat_forecast = 'EXPECTED_GROWTH' AND next_semester_seats > seat_count_proxy THEN 'CORRECT'
WHEN seat_forecast = 'EXPECTED_DECLINE' AND next_semester_seats < seat_count_proxy THEN 'CORRECT'
WHEN seat_forecast = 'EXPECTED_STABLE' AND ABS(next_semester_seats - seat_count_proxy) <= 2 THEN 'CORRECT'
ELSE 'INCORRECT'
END AS accuracy
FROM view_riksdagen_party_electoral_trends
WHERE next_semester_seats IS NOT NULL
AND calendar_year >= 2020
)
SELECT
party,
COUNT(*) AS forecasts_made,
SUM(CASE WHEN accuracy = 'CORRECT' THEN 1 ELSE 0 END) AS correct,
ROUND(100.0 * SUM(CASE WHEN accuracy = 'CORRECT' THEN 1 ELSE 0 END) / COUNT(*), 2) AS accuracy_pct
FROM forecasts
GROUP BY party
ORDER BY accuracy_pct DESC;
6. Early Warning System
SELECT
party,
calendar_year,
semester,
seat_count_proxy,
electoral_warning_flag,
seat_change_absolute,
win_rate_change_absolute,
electoral_trend,
ROUND(composite_electoral_score, 2) AS overall_score
FROM view_riksdagen_party_electoral_trends
WHERE electoral_warning_flag != 'NORMAL'
AND calendar_year >= 2022
ORDER BY
CASE electoral_warning_flag
WHEN 'CRITICAL_SEAT_LOSS' THEN 1
WHEN 'SIGNIFICANT_SEAT_LOSS' THEN 2
WHEN 'CRITICAL_PERFORMANCE_DROP' THEN 3
WHEN 'CRITICAL_ENGAGEMENT_DROP' THEN 4
ELSE 5
END,
calendar_year DESC;
7. Post-Election vs Pre-Election Comparison
WITH pre_post AS (
SELECT
party,
calendar_year,
CASE
WHEN is_pre_election_period THEN 'PRE_ELECTION'
WHEN is_post_election_period THEN 'POST_ELECTION'
END AS election_phase,
seat_count_proxy,
win_rate,
participation_rate,
documents_produced
FROM view_riksdagen_party_electoral_trends
WHERE (is_pre_election_period = true OR is_post_election_period = true)
AND calendar_year >= 2014
)
SELECT
party,
calendar_year AS election_year,
MAX(CASE WHEN election_phase = 'PRE_ELECTION' THEN seat_count_proxy END) AS pre_seats,
MAX(CASE WHEN election_phase = 'POST_ELECTION' THEN seat_count_proxy END) AS post_seats,
MAX(CASE WHEN election_phase = 'POST_ELECTION' THEN seat_count_proxy END) -
MAX(CASE WHEN election_phase = 'PRE_ELECTION' THEN seat_count_proxy END) AS seat_change
FROM pre_post
GROUP BY party, calendar_year
ORDER BY calendar_year DESC, seat_change DESC;
β‘ Performance Characteristics
- Query Time: 120-350ms (party-level aggregation + window functions)
- Indexes Suggested: Composite index on (party, election_cycle_id, cycle_year, semester)
- Data Volume: ~800-1000 rows (8-10 parties Γ 6 cycles Γ 8 semesters/cycle)
- Refresh Frequency: Real-time (standard view)
- Seat Count Limitation: Uses active member proxy; not actual seat allocation data
π Dependencies
Upstream:
view_riksdagen_vote_data_ballot_party_summary_annual- Voting performanceview_party_performance_metrics- Seat count proxy, document production
Downstream:
- Election forecasting models
- Coalition viability analysis
- Electoral trend reporting
π― Framework Integration
Temporal Analysis:
- Cross-cycle electoral evolution
- Pre-election vs post-election patterns
- Moving average trend smoothing
Comparative Analysis:
- Party-to-party electoral ranking
- Percentile-based tier classification
- Government vs opposition growth rates
Pattern Recognition:
- Electoral trend classification (SURGING, COLLAPSING)
- Volatility pattern detection
- Early warning signal identification
Predictive Intelligence:
- Seat forecast generation
- Trajectory confidence scoring
- Election readiness assessment
π― Use Cases
- Election Forecasting - Project seat counts based on historical trends and moving averages
- Electoral Risk Assessment - Identify parties with high volatility and seat loss warnings
- Pre-Election Analysis - Measure party readiness and campaign momentum
- Post-Election Evaluation - Compare predicted vs actual electoral outcomes
- Coalition Viability - Assess party sizes for government formation scenarios
- Trend Analysis - Track long-term growth/decline patterns across cycles
- Early Warning System - Alert on critical performance degradation
Vote Data Views
Overview
Vote data views provide temporal aggregations of parliamentary voting records at multiple granularities (daily, weekly, monthly, annual) for ballots, parties, and individual politicians. These materialized views enable efficient time-series analysis and performance tracking.
Total Vote Views: 20+
Intelligence Value: ββββ HIGH
Primary Use Cases: Temporal analysis, performance trending, absence tracking, effectiveness metrics
View Hierarchy
graph TB
A[vote_data<br/>Source Table] --> B[view_riksdagen_vote_data_ballot_summary]
B --> C1[view_riksdagen_vote_data_ballot_summary_daily]
B --> C2[view_riksdagen_vote_data_ballot_summary_weekly]
B --> C3[view_riksdagen_vote_data_ballot_summary_monthly]
B --> C4[view_riksdagen_vote_data_ballot_summary_annual]
A --> D[view_riksdagen_vote_data_ballot_party_summary]
D --> E1[view_riksdagen_vote_data_ballot_party_summary_daily]
D --> E2[view_riksdagen_vote_data_ballot_party_summary_weekly]
D --> E3[view_riksdagen_vote_data_ballot_party_summary_monthly]
D --> E4[view_riksdagen_vote_data_ballot_party_summary_annual]
A --> F[view_riksdagen_vote_data_ballot_politician_summary]
F --> G1[view_riksdagen_vote_data_ballot_politician_summary_daily]
F --> G2[view_riksdagen_vote_data_ballot_politician_summary_weekly]
F --> G3[view_riksdagen_vote_data_ballot_politician_summary_monthly]
F --> G4[view_riksdagen_vote_data_ballot_politician_summary_annual]
style B fill:#d1f2eb,stroke:#333,stroke-width:2px
style D fill:#d1f2eb,stroke:#333,stroke-width:2px
style F fill:#d1f2eb,stroke:#333,stroke-width:2px
style C1 fill:#e1f5ff,stroke:#333,stroke-width:2px
style E1 fill:#cce5ff,stroke:#333,stroke-width:2px
style G1 fill:#ffeb99,stroke:#333,stroke-width:2px
Materialized Views Summary
All vote summary views are materialized for performance optimization:
| View Category | Granularity | Materialized | Refresh | Use Case |
|---|---|---|---|---|
| Ballot Summaries | Daily/Weekly/Monthly/Annual | β | Daily 02:00 | Overall chamber statistics |
| Party Summaries | Daily/Weekly/Monthly/Annual | β | Daily 02:00 | Party performance tracking |
| Politician Summaries | Daily/Weekly/Monthly/Annual | β | Daily 02:00 | Individual MP monitoring |
Common Metrics Across All Vote Views
| Metric | Description | Calculation |
|---|---|---|
ballot_count | Number of votes | COUNT(DISTINCT ballot_id) |
yes_votes | Total "Ja" votes | SUM(CASE vote = 'Ja') |
no_votes | Total "Nej" votes | SUM(CASE vote = 'Nej') |
abstain_votes | Total "AvstΓ₯r" votes | SUM(CASE vote = 'AvstΓ₯r') |
absent_votes | Total absences | SUM(CASE vote = 'FrΓ₯nvarande') |
absence_rate | Percentage absent | 100.0 * absent / total |
win_rate | Percentage on winning side | 100.0 * wins / participated |
rebel_rate | Percentage against party | 100.0 * party_opposition / participated |
view_riksdagen_vote_data_ballot_politician_summary_daily βββββ
Category: Vote Data Views (v1.2, materialized v1.25)
Type: Materialized View
Intelligence Value: VERY HIGH - Individual Daily Performance Tracking
Purpose
Daily aggregation of individual politician voting behavior, tracking presence, effectiveness, and party discipline. Foundation for all behavioral trend analysis and risk assessment calculations. Most frequently queried vote view.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
vote_date | DATE | Voting date | '2024-10-15' |
intressent_id | VARCHAR(255) | Politician ID | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Party affiliation | 'S' |
ballot_count | INTEGER | Ballots this day | 12 |
yes_votes | INTEGER | "Ja" votes | 7 |
no_votes | INTEGER | "Nej" votes | 4 |
abstain_votes | INTEGER | Abstentions | 0 |
absent_votes | INTEGER | Times absent | 1 |
total_votes | INTEGER | Total voting opportunities | 12 |
absence_rate | NUMERIC(5,2) | Daily absence percentage | 8.33 |
win_rate | NUMERIC(5,2) | Percentage on winning side | 75.00 |
rebel_rate | NUMERIC(5,2) | Percentage against party | 5.00 |
party_consensus_agree | INTEGER | Votes with party consensus | 10 |
party_consensus_disagree | INTEGER | Votes against party consensus | 1 |
Example Queries
1. Daily Absence Report (Recent Activity)
SELECT
vote_date,
first_name,
last_name,
party,
ballot_count,
absent_votes,
ROUND(absence_rate, 2) AS absence_pct
FROM view_riksdagen_vote_data_ballot_politician_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '7 days'
AND absent_votes > 0
ORDER BY vote_date DESC, absence_rate DESC;
2. Monthly Performance Aggregation (for Trend Analysis)
SELECT
DATE_TRUNC('month', vote_date) AS month,
intressent_id,
first_name,
last_name,
party,
SUM(ballot_count) AS total_ballots,
SUM(absent_votes) AS total_absences,
ROUND(100.0 * SUM(absent_votes) / NULLIF(SUM(ballot_count), 0), 2) AS monthly_absence_rate,
ROUND(AVG(win_rate), 2) AS avg_win_rate,
ROUND(AVG(rebel_rate), 2) AS avg_rebel_rate
FROM view_riksdagen_vote_data_ballot_politician_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY DATE_TRUNC('month', vote_date), intressent_id, first_name, last_name, party
HAVING SUM(ballot_count) >= 10 -- Minimum activity threshold
ORDER BY intressent_id, month DESC;
3. Perfect Attendance Recognition
WITH recent_activity AS (
SELECT
intressent_id,
first_name,
last_name,
party,
SUM(ballot_count) AS total_ballots,
SUM(absent_votes) AS total_absences,
COUNT(DISTINCT vote_date) AS days_active
FROM view_riksdagen_vote_data_ballot_politician_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY intressent_id, first_name, last_name, party
)
SELECT
first_name,
last_name,
party,
total_ballots,
days_active
FROM recent_activity
WHERE total_absences = 0
AND total_ballots >= 50 -- Significant activity
ORDER BY total_ballots DESC;
4. High Rebellion Rate Detection
SELECT
vote_date,
first_name,
last_name,
party,
ballot_count,
ROUND(rebel_rate, 2) AS rebellion_pct,
party_consensus_disagree AS rebellion_count
FROM view_riksdagen_vote_data_ballot_politician_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '30 days'
AND rebel_rate > 15 -- High rebellion threshold
AND ballot_count >= 5 -- Sufficient sample
ORDER BY rebel_rate DESC, vote_date DESC;
5. Daily Performance Outliers (Statistical Anomalies)
WITH daily_stats AS (
SELECT
vote_date,
AVG(absence_rate) AS avg_absence,
STDDEV(absence_rate) AS stddev_absence,
AVG(win_rate) AS avg_win,
STDDEV(win_rate) AS stddev_win
FROM view_riksdagen_vote_data_ballot_politician_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '90 days'
AND ballot_count >= 5
GROUP BY vote_date
)
SELECT
vd.vote_date,
vd.first_name,
vd.last_name,
vd.party,
ROUND(vd.absence_rate, 2) AS absence_rate,
ROUND(ds.avg_absence, 2) AS daily_avg_absence,
ROUND((vd.absence_rate - ds.avg_absence) / NULLIF(ds.stddev_absence, 0), 2) AS absence_z_score
FROM view_riksdagen_vote_data_ballot_politician_summary_daily vd
JOIN daily_stats ds ON ds.vote_date = vd.vote_date
WHERE vd.vote_date >= CURRENT_DATE - INTERVAL '30 days'
AND ABS((vd.absence_rate - ds.avg_absence) / NULLIF(ds.stddev_absence, 0)) > 2 -- 2 standard deviations
ORDER BY ABS((vd.absence_rate - ds.avg_absence) / NULLIF(ds.stddev_absence, 0)) DESC
LIMIT 20;
Performance Characteristics
- Query Time: <50ms (materialized, indexed)
- Indexes Used:
idx_vote_summary_daily_date_person,idx_vote_summary_daily_party_date - Data Volume: ~1.5 million rows (350 politicians Γ ~4,000 sitting days)
- Refresh Frequency: Daily 02:00 UTC
- Storage: ~200 MB (materialized)
Data Sources
- Primary Table:
vote_data(raw voting records) - Aggregation: Daily GROUP BY politician
- Enhancements: Party consensus calculations, win/loss tracking
Dependencies
- No view dependencies (built from source table)
- Used by:
view_politician_behavioral_trends,view_risk_score_evolution, all politician performance views
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PoliticianLazy (P-01):
absence_rate,absent_votes - PoliticianIneffectiveVoting (P-02):
win_rate - PoliticianHighRebelRate (P-03):
rebel_rate,party_consensus_disagree - All politician performance rules depend on this view
Election Cycle Views (NEW v1.51)
Overview
Election Cycle Views (v1.51) provide META/META-level historical analysis of Swedish parliamentary activity across election cycles, incorporating Swedish parliamentary temporal context (4-year cycles, autumn/spring semesters, pre-election significance). These views aggregate existing advanced analytics with election cycle dimensions to enable cross-cycle comparative analysis and election-aware intelligence.
Total Election Cycle Views: 6
Intelligence Value: βββββ VERY HIGH
Type: META/META Level (aggregate existing views only)
Changelog: v1.51 - GitHub Issue #8205
Primary Use Cases: Election forecasting, cross-cycle analysis, pre-election behavioral patterns, coalition stability trends, legislative effectiveness by cycle phase
Swedish Parliamentary Context
- Elections: Every 4 years since 1994 (second Sunday in September): 1994, 1998, 2002, 2006, 2010, 2014, 2018, 2022, 2026...
- Parliamentary Periods: Start second Tuesday in September after elections
- Autumn Semester: Mid-September to ~January 25
- Spring Semester: ~January 26 to next September
- Pre-Election Significance: Final spring semester before election (campaign impact, policy shifts, attendance spikes/drops, coalition volatility)
Framework Coverage
All 6 analytical frameworks are explicitly covered with corresponding views:
| Framework | View | Supporting Views | Risk Rules | Operational |
|---|---|---|---|---|
| Temporal Analysis | view_election_cycle_temporal_trends | 35 views | 20+ rules | 100% |
| Comparative Analysis | view_election_cycle_comparative_analysis | 26 views | 15+ rules | 100% |
| Predictive Intelligence | view_election_cycle_predictive_intelligence | 14 views | 8/8 rules | 100% |
| Network Analysis | view_election_cycle_network_analysis | 11 views | 3/4 rules | 75% |
| Decision Intelligence | view_election_cycle_decision_intelligence | 5 views | 5/5 rules | 100% |
| Pattern Recognition | view_election_cycle_anomaly_pattern | 23 views | 12/13 rules | 92% |
View Inventory
| View Name | Framework | Intelligence Value | Description |
|---|---|---|---|
| view_election_cycle_temporal_trends | Temporal Analysis | βββββ | Attendance, ballots, violations by cycle/semester |
| view_election_cycle_comparative_analysis | Comparative Analysis | βββββ | Party-level metrics comparison by cycle/semester |
| view_election_cycle_predictive_intelligence | Predictive Intelligence | βββββ | Risk forecasts and trajectory analysis by cycle |
| view_election_cycle_network_analysis | Network Analysis | βββββ | Coalition alignment structure by election cycle |
| view_election_cycle_decision_intelligence | Decision Intelligence | βββββ | Proposal success rates and effectiveness by cycle |
| view_election_cycle_anomaly_pattern | Pattern Recognition | βββββ | Anomaly detection and risk pattern aggregation by cycle |
view_election_cycle_temporal_trends βββββ
Category: Election Cycle Views (v1.51)
Type: Standard View (META/META level)
Framework: Temporal Analysis (35 supporting views)
Intelligence Value: VERY HIGH - Cross-Cycle Temporal Intelligence
Purpose
Aggregates longitudinal trends for attendance, bill proposals, voting activity, and committee participation across election cycles with semester granularity. Enables analysis of how political behavior varies across the 4-year election cycle and between autumn/spring semesters, with special emphasis on pre-election periods.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
election_cycle_id | TEXT | Election cycle identifier | '2018-2022', '2022-2026' |
cycle_year | INTEGER | Year within 4-year cycle (1-4) | 3 |
calendar_year | INTEGER | Actual calendar year | 2024 |
semester | TEXT | Semester (autumn/spring) | 'spring' |
is_pre_election_semester | BOOLEAN | TRUE for final spring before election | true |
months_until_election | INTEGER | Countdown to next election | 6 |
active_politicians | BIGINT | Count of active politicians | 349 |
avg_attendance_rate | NUMERIC(5,2) | Average attendance percentage | 87.50 |
total_ballots | BIGINT | Total ballots in period | 1250 |
total_votes | BIGINT | Total votes cast | 425000 |
avg_win_rate | NUMERIC(5,2) | Average win rate percentage | 45.80 |
avg_rebel_rate | NUMERIC(5,2) | Average rebel rate percentage | 12.30 |
violation_count | BIGINT | Total violations detected | 45 |
distinct_ballots | BIGINT | Count of unique ballots | 1200 |
Source Views (META Level)
- view_politician_behavioral_trends: Monthly behavioral metrics (absence, win, rebel rates)
- view_riksdagen_vote_data_ballot_politician_summary_monthly: Voting pattern aggregations
Example Queries
1. Pre-Election Semester Analysis
SELECT
election_cycle_id,
calendar_year,
avg_attendance_rate,
avg_rebel_rate,
violation_count
FROM view_election_cycle_temporal_trends
WHERE is_pre_election_semester = true
ORDER BY calendar_year DESC
LIMIT 3;
2. Cross-Cycle Comparison
SELECT
election_cycle_id,
cycle_year,
semester,
avg_attendance_rate,
avg_rebel_rate
FROM view_election_cycle_temporal_trends
WHERE semester = 'spring' AND cycle_year = 4
ORDER BY election_cycle_id;
Intelligence Applications
- Election Forecasting: Analyze pre-election behavioral patterns
- Temporal Trends: Track how metrics evolve across 4-year cycles
- Attendance Patterns: Identify election-related attendance spikes/drops
- Coalition Stability: Monitor rebel rates approaching elections
- Cross-Cycle Benchmarking: Compare current cycle to historical patterns
view_election_cycle_comparative_analysis βββββ
Category: Election Cycle Views (v1.51)
Type: Standard View (META/META level)
Framework: Comparative Analysis (26 supporting views)
Purpose
Party-level comparative analysis across election cycles with semester granularity, enabling cross-party and cross-cycle performance benchmarking.
Key Columns
| Column | Type | Description |
|---|---|---|
election_cycle_id | TEXT | Election cycle identifier |
cycle_year | INTEGER | Year within cycle (1-4) |
semester | TEXT | Semester (autumn/spring) |
party | TEXT | Political party abbreviation |
total_votes_party | BIGINT | Total party votes |
avg_yes_percentage | NUMERIC(5,2) | Average yes vote percentage |
avg_absence_percentage | NUMERIC(5,2) | Average absence rate |
avg_rebel_percentage | NUMERIC(5,2) | Average rebellion rate |
party_member_count | BIGINT | Active party members |
Source Views
- view_riksdagen_vote_data_ballot_party_summary_monthly
view_election_cycle_predictive_intelligence βββββ
Category: Election Cycle Views (v1.51)
Framework: Predictive Intelligence (14 supporting views)
Purpose
Forecasts, risk spikes, and predictive intelligence signals by election cycle and semester.
Key Columns
| Column | Type | Description |
|---|---|---|
risk_forecast_category | TEXT | Predicted risk level |
politicians_at_risk | BIGINT | Count with escalating risk |
avg_risk_score_change | NUMERIC(5,2) | Average risk delta |
predicted_high_absenteeism | BIGINT | Forecast attendance issues |
predicted_coalition_volatility | BIGINT | High rebel trend count |
Source Views
- view_risk_score_evolution
- view_politician_behavioral_trends
view_election_cycle_network_analysis βββββ
Category: Election Cycle Views (v1.51)
Framework: Network Analysis (11 supporting views)
Purpose
Coalition structure and network trend mapping per election cycle and semester.
Key Columns
| Column | Type | Description |
|---|---|---|
party_a | TEXT | First party in pair |
party_b | TEXT | Second party in pair |
alignment_score | NUMERIC(5,2) | Voting alignment percentage |
coalition_strength | TEXT | Strength classification |
Source Views
- view_riksdagen_coalition_alignment_matrix
view_election_cycle_decision_intelligence βββββ
Category: Election Cycle Views (v1.51)
Framework: Decision Intelligence (5 supporting views)
Purpose
Policy success, coalition stability, and legislative outcome analysis by election cycle and semester.
Key Columns
| Column | Type | Description |
|---|---|---|
party | TEXT | Political party |
total_proposals | BIGINT | Total proposals submitted |
approved_proposals | BIGINT | Successfully approved proposals |
avg_approval_rate | NUMERIC(5,2) | Approval success percentage |
decision_effectiveness | TEXT | Effectiveness classification |
Source Views
- view_riksdagen_party_decision_flow
view_election_cycle_anomaly_pattern βββββ
Category: Election Cycle Views (v1.51)
Type: Standard View (META/META level)
Framework: Pattern Recognition (23 supporting views)
Intelligence Value: VERY HIGH - Anomaly Detection & Risk Pattern Intelligence
Purpose
Multi-source anomaly pattern detection aggregating risk score evolution, voting anomaly classification, and politician risk summaries across election cycles and semesters. Identifies risk escalation patterns, behavioral outliers, and anomaly acceleration trends with windowed statistics including semester-over-semester change tracking.
Key Columns
| Column | Type | Description |
|---|---|---|
election_cycle_id | TEXT | Election cycle identifier (e.g., '2018-2022') |
anomaly_type | TEXT | Pattern classification type |
politician_count_with_risk | BIGINT | Politicians with HIGH/CRITICAL risk severity |
avg_risk_score | NUMERIC(5,2) | Average risk score across cycle |
risk_escalations | BIGINT | Count of risk severity escalations |
high_anomaly_count | BIGINT | Frequent/consistent rebel count |
avg_total_rebellions | NUMERIC(5,2) | Average rebellion count |
strong_consensus_rebels | BIGINT | Politicians with 5+ strong consensus rebellions |
avg_risk_score_prs | NUMERIC(5,2) | Average risk score from politician risk summary |
high_risk_politicians | BIGINT | HIGH/CRITICAL risk level politicians |
risk_trend | TEXT | Risk trajectory (escalating/improving/stable) |
anomaly_acceleration | BIGINT | Change in anomaly count vs previous semester |
Sample Query
SELECT election_cycle_id, semester, avg_risk_score,
high_anomaly_count, risk_trend, anomaly_acceleration
FROM view_election_cycle_anomaly_pattern
WHERE risk_trend = 'escalating'
ORDER BY election_cycle_id, cycle_year, semester;
Source Views
- view_risk_score_evolution
- view_riksdagen_voting_anomaly_detection
- view_politician_risk_summary
Intelligence Views
Overview
Intelligence views (v1.29-v1.30) represent advanced analytical capabilities combining multiple data sources for risk assessment, trend analysis, and predictive intelligence. These views implement sophisticated algorithms for behavioral classification, anomaly detection, and coalition analysis.
Total Intelligence Views: 15+
Intelligence Value: βββββ VERY HIGH
Primary Use Cases: Risk assessment, trend forecasting, coalition analysis, anomaly detection, dashboard aggregation
View Categories
| View Type | Examples | Purpose |
|---|---|---|
| Behavioral Trends | politician_behavioral_trends, party_effectiveness_trends | Time-series performance tracking |
| Risk Assessment | risk_score_evolution, politician_risk_summary | Automated risk scoring |
| Coalition Analysis | coalition_alignment_matrix | Government formation forecasting |
| Network Intelligence | politician_influence_metrics | Power structure mapping |
| Dashboard Aggregation | riksdagen_intelligence_dashboard | Unified intelligence products |
| Crisis Analysis | crisis_resilience_indicators | Crisis period performance assessment |
| Anomaly Detection | voting_anomaly_detection | Behavioral outlier identification |
view_riksdagen_crisis_resilience_indicators βββββ
Category: Intelligence Views (v1.29)
Type: Standard View
Intelligence Value: VERY HIGH - Crisis Performance Assessment
Changelog: v1.29 Crisis Resilience Analysis
Purpose
Sophisticated crisis resilience analysis comparing politician performance during high-activity "crisis" periods versus normal periods. Automatically identifies crisis periods (ballot volume >150% of average), then calculates individual resilience metrics including attendance, party discipline, and performance consistency. Provides resilience classification from HIGHLY_RESILIENT to LOW_RESILIENCE.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Party affiliation | 'S' |
status | VARCHAR(100) | Current status | 'TjΓ€nstgΓΆrande riksdagsledamot' |
crisis_period_votes | BIGINT | Votes during crisis periods | 145 |
crisis_definitive_votes | BIGINT | Definitive votes (Ja/Nej) in crisis | 132 |
crisis_absences | BIGINT | Absences during crisis | 13 |
crisis_absence_rate | DOUBLE PRECISION | Crisis absence rate (0.0-1.0) | 0.090 (9%) |
normal_votes | BIGINT | Votes during normal periods | 320 |
normal_absences | BIGINT | Absences during normal periods | 28 |
normal_absence_rate | DOUBLE PRECISION | Normal absence rate (0.0-1.0) | 0.088 (8.8%) |
absence_delta | DOUBLE PRECISION | Crisis - Normal absence rate | 0.002 (0.2%) |
aligned_crisis_votes | BIGINT | Votes aligned with party in crisis | 125 |
crisis_party_alignment_rate | DOUBLE PRECISION | Party discipline in crisis (0.0-1.0) | 0.947 (94.7%) |
resilience_score | NUMERIC(10,2) | Overall resilience score (0-100) | 87.5 |
resilience_classification | TEXT | Resilience level | 'HIGHLY_RESILIENT' |
attendance_resilience | TEXT | Attendance-specific resilience | 'RESILIENT' |
discipline_resilience | TEXT | Discipline-specific resilience | 'HIGHLY_RESILIENT' |
Crisis Period Detection
Algorithm:
- Calculate average monthly ballot count (last 2 years)
- Identify months with ballot count >150% of average as "crisis periods"
- Remaining months classified as "normal periods"
- Compare individual performance across both period types
Example Crisis Triggers:
- Budget crises requiring extensive voting
- Government formation periods
- Major legislative pushes
- Political scandals requiring multiple votes
- Emergency legislation periods
Resilience Score Calculation
Formula:
$ \text{resilience\_score} = 100 - ( (\text{crisis\_absence\_rate} \times 40) + ((1 - \text{crisis\_party\_alignment\_rate}) \times 40) + (\text{max}(0, \text{absence\_delta}) \times 20) ) $
Components:
- 40% weight: Crisis absence rate (lower is better)
- 40% weight: Crisis party discipline (higher is better)
- 20% weight: Absence rate increase in crisis (lower is better)
Resilience Classification Thresholds:
| Score Range | Classification | Description |
|---|---|---|
| 90-100 | HIGHLY_RESILIENT | Excellent crisis performance |
| 75-89 | RESILIENT | Good crisis performance |
| 60-74 | MODERATE_RESILIENCE | Adequate crisis performance |
| 45-59 | VULNERABLE | Below average crisis performance |
| 0-44 | LOW_RESILIENCE | Poor crisis performance |
Example Queries
1. Identify Most Resilient Politicians
SELECT
first_name,
last_name,
party,
resilience_score,
resilience_classification,
crisis_absence_rate,
crisis_party_alignment_rate,
crisis_period_votes
FROM view_riksdagen_crisis_resilience_indicators
WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot'
ORDER BY resilience_score DESC
LIMIT 20;
2. Identify Vulnerable Politicians in Crisis
SELECT
first_name,
last_name,
party,
resilience_classification,
crisis_absence_rate,
normal_absence_rate,
absence_delta,
crisis_party_alignment_rate
FROM view_riksdagen_crisis_resilience_indicators
WHERE resilience_classification IN ('VULNERABLE', 'LOW_RESILIENCE')
AND status = 'TjΓ€nstgΓΆrande riksdagsledamot'
ORDER BY resilience_score ASC;
3. Party-Level Crisis Resilience Analysis
SELECT
party,
COUNT(*) AS member_count,
ROUND(AVG(resilience_score), 1) AS avg_resilience,
COUNT(*) FILTER (WHERE resilience_classification = 'HIGHLY_RESILIENT') AS highly_resilient,
COUNT(*) FILTER (WHERE resilience_classification IN ('VULNERABLE', 'LOW_RESILIENCE')) AS vulnerable,
ROUND(AVG(crisis_absence_rate) * 100, 1) AS avg_crisis_absence_pct,
ROUND(AVG(crisis_party_alignment_rate) * 100, 1) AS avg_crisis_discipline_pct
FROM view_riksdagen_crisis_resilience_indicators
WHERE status = 'TjΓ€nstgΓΆrande riksdagsledamot'
GROUP BY party
ORDER BY avg_resilience DESC;
4. Crisis Performance Degradation Detection
SELECT
first_name,
last_name,
party,
normal_absence_rate,
crisis_absence_rate,
absence_delta,
ROUND(absence_delta * 100, 1) AS absence_increase_pct
FROM view_riksdagen_crisis_resilience_indicators
WHERE absence_delta > 0.05 -- Absence rate increased by >5% in crisis
AND status = 'TjΓ€nstgΓΆrande riksdagsledamot'
ORDER BY absence_delta DESC;
Performance Characteristics
- Query Time: 800-2000ms (complex window functions and multi-period aggregation)
- Refresh Frequency: Real-time (recalculates on each query)
- Data Volume: ~350 rows (all politicians with voting history)
- Optimization: Consider materializing for faster dashboard queries
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Crisis Analysis: Performance under pressure assessment
- Predictive Intelligence: Future crisis performance forecasting
- Comparative Analysis: Party resilience benchmarking
- Risk Assessment: Vulnerability identification
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- PoliticianLazy (P-01): Crisis absence patterns
- PoliticianIneffectiveVoting (P-02): Crisis effectiveness degradation
- PartyRebelVoting (P-04): Crisis discipline breakdown
Use Cases
- Government Formation: Assess coalition partner reliability under pressure
- Ministry Appointments: Identify crisis-capable ministers
- Early Warning: Detect politicians who crack under pressure
- Party Strength: Evaluate party discipline during crises
- Historical Analysis: Study performance during past crises (budget, coalition, scandal)
Purpose
Unified intelligence dashboard aggregating key metrics from five core intelligence dimensions into a single real-time overview. Provides at-a-glance assessment of political stability, coalition dynamics, defection risks, influence networks, and crisis readiness. Designed for executive-level intelligence briefings and rapid situational awareness.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
parties_gaining_momentum | BIGINT | Parties with positive trend direction | 3 |
parties_losing_momentum | BIGINT | Parties with negative trend direction | 2 |
volatile_parties | BIGINT | Parties with volatile/highly volatile classification | 1 |
high_probability_coalitions | BIGINT | Coalition pairs with strong likelihood | 4 |
cross_bloc_alliances | BIGINT | Strong/moderate cross-bloc coalitions | 2 |
high_defection_risks | BIGINT | Politicians with frequent/consistent rebel pattern | 5 |
low_discipline_politicians | BIGINT | All politicians with rebel pattern (moderate+) | 12 |
power_brokers | BIGINT | Politicians with strong/moderate broker classification | 8 |
highly_connected_politicians | BIGINT | Politicians with highly influential classification | 6 |
crisis_ready_politicians | BIGINT | Politicians with highly resilient classification | 45 |
low_resilience_politicians | BIGINT | Politicians with low resilience classification | 8 |
stability_assessment | TEXT | Overall political stability classification | 'STABLE_POLITICAL_ENVIRONMENT' |
coalition_assessment | TEXT | Coalition landscape assessment | 'STABLE_COALITION_PATTERNS' |
latest_vote_data | DATE | Most recent voting data timestamp | '2024-11-15' |
ballots_last_30_days | BIGINT | Recent voting activity indicator | 42 |
intelligence_report_timestamp | TIMESTAMP | Report generation timestamp | '2026-01-22 15:00:00' |
Intelligence Dimensions Aggregated
1. Party Momentum (from view_riksdagen_party_momentum_analysis)
- Parties gaining/losing momentum
- Volatile parties requiring monitoring
2. Coalition Dynamics (from view_riksdagen_coalition_alignment_matrix)
- High-probability coalitions
- Cross-bloc alliances (potential realignments)
3. Voting Anomalies (from view_riksdagen_voting_anomaly_detection)
- High defection risks (critical rebels)
- Low discipline politicians (all rebel patterns)
4. Influence Networks (from view_riksdagen_politician_influence_metrics)
- Power brokers (coalition facilitators)
- Highly connected politicians (network hubs)
5. Crisis Resilience (from view_riksdagen_crisis_resilience_indicators)
- Crisis-ready politicians (high performers under pressure)
- Low resilience politicians (vulnerability indicators)
Assessment Classifications
Stability Assessment Logic:
CASE
WHEN high_defection_risks >= 5 THEN 'HIGH_POLITICAL_INSTABILITY_RISK'
WHEN volatile_parties >= 3 THEN 'MODERATE_POLITICAL_INSTABILITY_RISK'
ELSE 'STABLE_POLITICAL_ENVIRONMENT'
END
Coalition Assessment Logic:
CASE
WHEN cross_bloc_alliances >= 2 THEN 'POTENTIAL_REALIGNMENT_DETECTED'
WHEN high_probability_coalitions >= 5 THEN 'STABLE_COALITION_PATTERNS'
ELSE 'UNCERTAIN_COALITION_LANDSCAPE'
END
Example Queries
1. Current Intelligence Snapshot
SELECT
stability_assessment,
coalition_assessment,
parties_gaining_momentum,
parties_losing_momentum,
high_defection_risks,
cross_bloc_alliances,
power_brokers,
crisis_ready_politicians,
latest_vote_data,
ballots_last_30_days,
intelligence_report_timestamp
FROM view_riksdagen_intelligence_dashboard;
2. Risk Alert Detection
SELECT
CASE
WHEN stability_assessment = 'HIGH_POLITICAL_INSTABILITY_RISK'
THEN 'CRITICAL: ' || high_defection_risks || ' high defection risks detected'
WHEN stability_assessment = 'MODERATE_POLITICAL_INSTABILITY_RISK'
THEN 'WARNING: ' || volatile_parties || ' volatile parties detected'
ELSE 'STABLE: No immediate concerns'
END AS risk_alert,
stability_assessment,
coalition_assessment
FROM view_riksdagen_intelligence_dashboard;
3. Coalition Realignment Monitor
SELECT
coalition_assessment,
cross_bloc_alliances AS potential_realignments,
high_probability_coalitions AS stable_coalitions,
CASE
WHEN cross_bloc_alliances >= 2 THEN 'Monitor for coalition shifts'
ELSE 'No realignment indicators'
END AS recommendation
FROM view_riksdagen_intelligence_dashboard;
4. Intelligence Brief Summary
SELECT
'Political Stability: ' || stability_assessment || E'\n' ||
'Coalition Landscape: ' || coalition_assessment || E'\n' ||
'High-Risk Politicians: ' || high_defection_risks || E'\n' ||
'Cross-Bloc Alliances: ' || cross_bloc_alliances || E'\n' ||
'Power Brokers: ' || power_brokers || E'\n' ||
'Crisis-Ready: ' || crisis_ready_politicians || E'\n' ||
'Data Currency: ' || (CURRENT_DATE - latest_vote_data) || ' days old' AS intelligence_brief
FROM view_riksdagen_intelligence_dashboard;
Performance Characteristics
- Query Time: 200-500ms (aggregates 5 source views)
- Refresh Frequency: Real-time (recalculates on each query)
- Data Volume: Single row (dashboard summary)
- Optimization: Consider materializing for sub-second response
Dependencies
Critical Dependencies (all must exist):
view_riksdagen_party_momentum_analysis- Party trend analysisview_riksdagen_coalition_alignment_matrix- Coalition probabilitiesview_riksdagen_voting_anomaly_detection- Rebel/discipline patternsview_riksdagen_politician_influence_metrics- Network analysisview_riksdagen_crisis_resilience_indicators- Crisis performancevote_datatable - Recent voting activity metrics
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Predictive Intelligence: Early warning indicators for instability
- Comparative Analysis: Multi-dimensional political assessment
- Network Analysis: Coalition and influence patterns
- Temporal Intelligence: Momentum and trend tracking
- Risk Assessment: Comprehensive threat monitoring
Risk Rules Supported
From RISK_RULES_INTOP_OSINT.md:
- All Risk Categories: Dashboard aggregates indicators from all 50 risk rules
- Executive Summary: High-level roll-up of rule violations
- Priority Alerting: Focuses on critical patterns and anomalies
Use Cases
- Executive Briefings: Single-view intelligence snapshot for leadership
- Situation Room: Real-time political stability monitoring
- Early Warning System: Detect instability before it manifests
- Coalition Formation: Assess viability of potential government coalitions
- Risk Dashboards: Feed executive intelligence dashboards
- API Endpoints: Power real-time intelligence APIs
- Alert Generation: Trigger notifications on threshold violations
Historical Context
Version History:
- v1.29 (2025-03-15): Initial creation as unified dashboard
- v1.33 (2025-06-20): Dropped by CASCADE during crisis_resilience_indicators fix, recreated same changeset
- v1.40 (2025-09-10): Dropped by CASCADE again, recreated with updated column names
- v1.61 (2026-01-19): Indirectly affected by coalition_evolution/electoral_trends issues
- v1.62 (2026-01-22): Final recreation after v1.61 DROP CASCADE bug fix
Notes
- Single Row View: Returns exactly 1 row with aggregated metrics
- No Historical Data: Provides current snapshot only (no time series)
- Real-Time Calculation: Reflects latest data from all source views
- Alert Threshold Tuning: Thresholds (e.g., 5 defection risks) may need adjustment based on Riksdag size
- Materialization Candidate: Consider creating materialized view for faster API responses
view_risk_score_evolution βββββ
Category: Intelligence Views (v1.30)
Type: Standard View
Intelligence Value: VERY HIGH - Risk Tracking & Prediction
Changelog: v1.30 OSINT Risk Evolution Monitoring
Purpose
Temporal risk score tracking combining rule violations, behavioral trends, and predictive indicators. Provides month-over-month risk evolution analysis with automated severity classification and early warning capabilities.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
person_id | VARCHAR(255) | Politician identifier | '0532213467925' |
first_name | VARCHAR(255) | Politician first name | 'Anna' |
last_name | VARCHAR(255) | Politician last name | 'Andersson' |
party | VARCHAR(50) | Party affiliation | 'S' |
year_month | DATE | Month of assessment | '2024-10-01' |
risk_score | INTEGER | Total risk points | 85 |
risk_severity | VARCHAR(50) | Classification | 'MAJOR' |
active_violations | INTEGER | Current rule violations | 3 |
absence_risk | INTEGER | Absence-related points | 30 |
effectiveness_risk | INTEGER | Effectiveness-related points | 25 |
discipline_risk | INTEGER | Discipline-related points | 15 |
productivity_risk | INTEGER | Productivity-related points | 15 |
risk_trend | INTEGER | Month-over-month change | +12 |
risk_velocity | INTEGER | Acceleration of risk growth | +5 |
ma_3month_risk | NUMERIC(10,2) | 3-month moving average | 78.50 |
risk_trajectory | VARCHAR(50) | Trend classification | 'ESCALATING' |
Risk Score Calculation
Total Risk Score = Sum of risk category points:
| Risk Category | Max Points | Calculation Basis |
|---|---|---|
| Absence Risk | 0-100 | Absence rate Γ multiplier + trend weighting |
| Effectiveness Risk | 0-100 | (100 - win_rate) Γ multiplier + trend weighting |
| Discipline Risk | 0-100 | Rebel rate Γ multiplier + party impact factor |
| Productivity Risk | 0-100 | Document deficit Γ multiplier |
Risk Severity Thresholds:
| Severity | Score Range | Description |
|---|---|---|
| MINOR | 10-49 | Early warning, monitor |
| MAJOR | 50-99 | Significant concern, investigate |
| CRITICAL | 100+ | Severe risk, immediate attention |
Risk Trajectory Classifications
- STABLE: Risk score variation < 5 points/month, consistent behavior
- IMPROVING: Risk score declining > 10 points/month, positive trend
- CONCERNING: Risk score increasing 5-15 points/month, monitor closely
- ESCALATING: Risk score increasing > 15 points/month, intervention needed
- VOLATILE: Large month-to-month swings, unpredictable behavior
Example Queries
1. Current High-Risk Politicians (Top 20)
SELECT
first_name,
last_name,
party,
risk_score,
risk_severity,
active_violations,
absence_risk,
effectiveness_risk,
discipline_risk,
risk_trajectory
FROM view_risk_score_evolution
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
AND risk_score >= 50 -- MAJOR or CRITICAL
ORDER BY risk_score DESC
LIMIT 20;
2. Risk Escalation Detection (Rapid Increase)
SELECT
first_name,
last_name,
party,
year_month,
risk_score,
risk_trend AS monthly_change,
risk_velocity AS acceleration,
risk_trajectory,
CASE
WHEN risk_trend > 20 THEN 'CRITICAL_ESCALATION'
WHEN risk_trend > 10 THEN 'MODERATE_ESCALATION'
WHEN risk_trend > 5 THEN 'MILD_ESCALATION'
ELSE 'STABLE_OR_IMPROVING'
END AS escalation_severity
FROM view_risk_score_evolution
WHERE year_month >= CURRENT_DATE - INTERVAL '6 months'
AND risk_trend > 5 -- Increasing risk
ORDER BY risk_trend DESC, year_month DESC
LIMIT 30;
3. Risk Category Breakdown by Party
SELECT
party,
COUNT(*) AS members_assessed,
ROUND(AVG(risk_score), 1) AS avg_party_risk,
COUNT(*) FILTER (WHERE risk_severity = 'CRITICAL') AS critical_count,
COUNT(*) FILTER (WHERE risk_severity = 'MAJOR') AS major_count,
COUNT(*) FILTER (WHERE risk_severity = 'MINOR') AS minor_count,
ROUND(AVG(absence_risk), 1) AS avg_absence_risk,
ROUND(AVG(effectiveness_risk), 1) AS avg_effectiveness_risk,
ROUND(AVG(discipline_risk), 1) AS avg_discipline_risk
FROM view_risk_score_evolution
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
GROUP BY party
ORDER BY avg_party_risk DESC;
4. Risk Evolution Time Series (Individual Politician)
SELECT
year_month,
risk_score,
risk_severity,
risk_trend,
ma_3month_risk,
active_violations,
risk_trajectory
FROM view_risk_score_evolution
WHERE person_id = '0532213467925' -- Specific politician
AND year_month >= CURRENT_DATE - INTERVAL '24 months'
ORDER BY year_month DESC;
5. Early Warning System (Deteriorating Performance)
WITH risk_changes AS (
SELECT
person_id,
first_name,
last_name,
party,
year_month,
risk_score,
LAG(risk_score) OVER (
PARTITION BY person_id
ORDER BY year_month
) AS prev_risk,
risk_score - LAG(risk_score) OVER (
PARTITION BY person_id
ORDER BY year_month
) AS risk_change
FROM view_risk_score_evolution
WHERE year_month >= CURRENT_DATE - INTERVAL '6 months'
)
SELECT
first_name,
last_name,
party,
COUNT(*) AS months_tracked,
ROUND(AVG(risk_change), 1) AS avg_monthly_increase,
MAX(risk_score) AS peak_risk,
MIN(risk_score) AS lowest_risk,
MAX(risk_score) - MIN(risk_score) AS total_increase
FROM risk_changes
WHERE risk_change IS NOT NULL
GROUP BY person_id, first_name, last_name, party
HAVING AVG(risk_change) > 3 -- Consistently increasing
AND COUNT(*) >= 3 -- At least 3 months tracked
ORDER BY avg_monthly_increase DESC
LIMIT 20;
``$
#### \text{Performance} \text{Characteristics}
- **\text{Query} \text{Time}:** 100-150\text{ms} (\text{complex} \text{risk} \text{calculation})
- **\text{Indexes} \text{Used}:** \text{Multiple} \text{indexes} \text{on} \text{violation}, \text{behavioral}, \text{and} \text{temporal} \text{data}
- **\text{Data} \text{Volume}:** ~15{,}000 \text{rows} (350 \text{politicians} \times 36 \text{months} \text{rolling})
- **\text{Refresh} \text{Frequency}:** \text{Real}-\text{time} (\text{recalculated} \text{on} \text{query})
- **\text{Optimization}:** \text{Strong} \text{candidate} \text{for} \text{materialization}
#### \text{Data} \text{Sources}
- **\text{Behavioral} \text{Data}:** $view_politician_behavioral_trends`
- **Violations:** `rule_violation` table
- **Productivity:** Document summary views
- **Party Context:** Party performance benchmarks
#### Dependencies
- Depends on: `view_politician_behavioral_trends`, `rule_violation`, document views
- Used by: `view_riksdagen_intelligence_dashboard`, risk reports
#### Risk Rules Supported
From [RISK_RULES_INTOP_OSINT.md](RISK_RULES_INTOP_OSINT.md):
- **All Politician Risk Rules (P-01 to P-24)**: Unified risk scoring
- **PoliticianCombinedRisk (P-05)**: Primary implementation view
- **Risk Trending Rules**: Temporal risk evolution tracking
---
### view_decision_temporal_trends βββββ
**Category:** Intelligence Views (v1.35)
**Type:** Standard View
**Intelligence Value:** VERY HIGH - Temporal Decision Flow Analysis & Predictive Intelligence
**Changelog:** v1.35 Temporal Decision Trends with Moving Averages
#### Purpose
Temporal trends view for decision flow analysis from DOCUMENT_PROPOSAL_DATA, enabling time-series analysis of decision patterns, seasonal variations, and predictive forecasting of legislative activity. Provides daily aggregations with moving averages (7-day, 30-day, 90-day), year-over-year comparisons, and seasonal decomposition for Swedish parliamentary calendar. Supports anomaly detection through z-score analysis and trend identification via moving average crossovers.
#### Key Columns
| Column | Type | Description | Example |
|--------|------|-------------|---------|
| `decision_day` | DATE | Date of decision(s) | '2024-11-15' |
| `daily_decisions` | BIGINT | Total decisions on this day | 42 |
| `daily_approval_rate` | NUMERIC(5,2) | Percentage of approved decisions (bifall) | 67.50 |
| `approved_decisions` | BIGINT | Count of approved decisions (bifall) | 28 |
| `rejected_decisions` | BIGINT | Count of rejected decisions (avslag) | 8 |
| `referred_back_decisions` | BIGINT | Count of decisions referred back (Γ₯terfΓΆrvisning) | 6 |
| `ma_7day_decisions` | NUMERIC(10,2) | 7-day moving average of daily decisions | 38.71 |
| `ma_30day_decisions` | NUMERIC(10,2) | 30-day moving average of daily decisions | 41.15 |
| `ma_90day_decisions` | NUMERIC(10,2) | 90-day moving average of daily decisions | 39.82 |
| `ma_30day_approval_rate` | NUMERIC(5,2) | 30-day moving average of approval rate | 68.20 |
| `decisions_last_year` | BIGINT | Decisions on same day last year | 45 |
| `yoy_decisions_change` | BIGINT | Year-over-year change in decisions | -3 |
| `yoy_decisions_change_pct` | NUMERIC(5,2) | Year-over-year percentage change | -6.67 |
| `decision_year` | NUMERIC | Year of decision | 2024 |
| `decision_month` | NUMERIC | Month of decision (1-12) | 11 |
| `decision_week` | NUMERIC | Week of year (1-53) | 46 |
| `decision_day_of_week` | NUMERIC | Day of week (0=Sunday, 6=Saturday) | 2 |
| `parliamentary_period` | TEXT | Seasonal period classification | 'Autumn Session' |
| `decision_quarter` | TEXT | Quarter and year | 'Q4 2024' |
#### Seasonal Indicators
**Parliamentary Period Classification:**
- `Summer Recess`: July-August (low activity expected)
- `Winter Recess`: December-January (low activity expected)
- `Spring Session`: February-March
- `Late Spring Session`: April-June
- `Autumn Session`: September-November (typically highest activity)
- `Active Session`: Other periods
#### Example Queries
**1. Seasonal Pattern Analysis**
Identify average decision volumes and approval rates by parliamentary period over the last 3 years.
```sql
SELECT
parliamentary_period,
COUNT(DISTINCT decision_day) AS days_with_decisions,
ROUND(AVG(daily_decisions), 2) AS avg_daily_decisions,
ROUND(AVG(daily_approval_rate), 2) AS avg_approval_rate,
ROUND(MIN(daily_decisions), 2) AS min_daily_decisions,
ROUND(MAX(daily_decisions), 2) AS max_daily_decisions
FROM view_decision_temporal_trends
WHERE decision_day >= CURRENT_DATE - INTERVAL '3 years'
GROUP BY parliamentary_period
ORDER BY avg_daily_decisions DESC;
Sample Output:
parliamentary_period | days_with_decisions | avg_daily_decisions | avg_approval_rate | min_daily_decisions | max_daily_decisions
--------------------------+---------------------+---------------------+-------------------+---------------------+--------------------
Autumn Session | 245 | 42.15 | 68.30 | 15 | 87
Late Spring Session | 198 | 38.72 | 67.80 | 12 | 78
Spring Session | 156 | 35.45 | 66.50 | 8 | 72
Winter Recess | 45 | 8.23 | 71.20 | 1 | 25
Summer Recess | 38 | 5.67 | 69.40 | 1 | 18
Intelligence Application: Identifies seasonal patterns for resource planning and forecasting. Autumn Session shows highest activity (~42 decisions/day), while Summer Recess has minimal activity (~6 decisions/day).
2. Trend Detection (Moving Average Crossover)
Detect uptrends and downtrends in legislative activity using moving average crossovers.
SELECT
decision_day,
daily_decisions,
ma_7day_decisions,
ma_30day_decisions,
CASE
WHEN ma_7day_decisions > ma_30day_decisions THEN 'Uptrend β¬'
WHEN ma_7day_decisions < ma_30day_decisions THEN 'Downtrend β¬'
ELSE 'Neutral β‘'
END AS trend_signal,
ROUND(ma_7day_decisions - ma_30day_decisions, 2) AS ma_divergence
FROM view_decision_temporal_trends
WHERE decision_day >= CURRENT_DATE - INTERVAL '6 months'
ORDER BY decision_day DESC
LIMIT 20;
Sample Output:
decision_day | daily_decisions | ma_7day_decisions | ma_30day_decisions | trend_signal | ma_divergence
-------------+-----------------+-------------------+--------------------+--------------+--------------
2024-11-15 | 42 | 38.71 | 41.15 | Downtrend β¬ | -2.44
2024-11-14 | 45 | 39.86 | 41.22 | Downtrend β¬ | -1.36
2024-11-13 | 48 | 40.29 | 40.95 | Downtrend β¬ | -0.66
2024-11-12 | 52 | 41.14 | 40.75 | Uptrend β¬ | 0.39
2024-11-11 | 47 | 40.71 | 40.35 | Uptrend β¬ | 0.36
Intelligence Application: Moving average crossovers signal trend changes. When 7-day MA crosses above 30-day MA, legislative activity is accelerating. When it crosses below, activity is declining. This helps identify bottlenecks or unusual activity surges.
3. Anomaly Detection (Z-Score Method)
Identify days with abnormally high or low decision volumes using statistical deviation analysis.
WITH stats AS (
SELECT
AVG(daily_decisions) AS mean_decisions,
STDDEV(daily_decisions) AS stddev_decisions
FROM view_decision_temporal_trends
WHERE decision_day >= CURRENT_DATE - INTERVAL '1 year'
)
SELECT
vdt.decision_day,
vdt.daily_decisions,
vdt.parliamentary_period,
ROUND(s.mean_decisions, 2) AS mean_decisions,
ROUND(s.stddev_decisions, 2) AS stddev_decisions,
ROUND((vdt.daily_decisions - s.mean_decisions) / NULLIF(s.stddev_decisions, 0), 2) AS z_score,
CASE
WHEN ABS((vdt.daily_decisions - s.mean_decisions) / NULLIF(s.stddev_decisions, 0)) > 2.5 THEN 'EXTREME ANOMALY π΄'
WHEN ABS((vdt.daily_decisions - s.mean_decisions) / NULLIF(s.stddev_decisions, 0)) > 2.0 THEN 'ANOMALY π‘'
WHEN ABS((vdt.daily_decisions - s.mean_decisions) / NULLIF(s.stddev_decisions, 0)) > 1.5 THEN 'NOTABLE π’'
ELSE 'NORMAL'
END AS anomaly_status
FROM view_decision_temporal_trends vdt
CROSS JOIN stats s
WHERE vdt.decision_day >= CURRENT_DATE - INTERVAL '3 months'
AND ABS((vdt.daily_decisions - s.mean_decisions) / NULLIF(s.stddev_decisions, 0)) > 1.5
ORDER BY ABS((vdt.daily_decisions - s.mean_decisions) / NULLIF(s.stddev_decisions, 0)) DESC
LIMIT 15;
Sample Output:
decision_day | daily_decisions | parliamentary_period | mean_decisions | stddev_decisions | z_score | anomaly_status
-------------+-----------------+----------------------+----------------+------------------+---------+------------------
2024-10-22 | 87 | Autumn Session | 39.45 | 15.23 | 3.12 | EXTREME ANOMALY π΄
2024-09-15 | 78 | Autumn Session | 39.45 | 15.23 | 2.53 | EXTREME ANOMALY π΄
2024-11-03 | 72 | Autumn Session | 39.45 | 15.23 | 2.14 | ANOMALY π‘
2024-08-05 | 1 | Summer Recess | 39.45 | 15.23 | -2.52 | EXTREME ANOMALY π΄
2024-10-08 | 65 | Autumn Session | 39.45 | 15.23 | 1.68 | NOTABLE π’
Intelligence Application: Z-score > 2 indicates statistically significant anomalies. High z-scores may indicate critical legislative pushes, deadline-driven activity, or unusual parliamentary sessions. Low z-scores may indicate bottlenecks, political gridlock, or unexpected recesses.
4. Year-over-Year Comparison
Compare current legislative activity to the same period last year to identify trends.
SELECT
decision_day,
daily_decisions AS current_year_decisions,
decisions_last_year AS prior_year_decisions,
yoy_decisions_change AS decision_change,
yoy_decisions_change_pct AS pct_change,
parliamentary_period,
CASE
WHEN yoy_decisions_change_pct > 20 THEN 'Significant Increase β¬β¬'
WHEN yoy_decisions_change_pct > 10 THEN 'Moderate Increase β¬'
WHEN yoy_decisions_change_pct > -10 THEN 'Stable β‘'
WHEN yoy_decisions_change_pct > -20 THEN 'Moderate Decrease β¬'
ELSE 'Significant Decrease β¬β¬'
END AS yoy_trend
FROM view_decision_temporal_trends
WHERE decision_day >= CURRENT_DATE - INTERVAL '3 months'
AND decisions_last_year IS NOT NULL
ORDER BY decision_day DESC
LIMIT 20;
Sample Output:
decision_day | current_year | prior_year | decision_change | pct_change | parliamentary_period | yoy_trend
-------------+--------------+------------+-----------------+------------+----------------------+-------------------------
2024-11-15 | 42 | 45 | -3 | -6.67 | Autumn Session | Stable β‘
2024-11-14 | 45 | 38 | 7 | 18.42 | Autumn Session | Moderate Increase β¬
2024-11-13 | 48 | 52 | -4 | -7.69 | Autumn Session | Stable β‘
2024-11-12 | 52 | 41 | 11 | 26.83 | Autumn Session | Significant Increase β¬β¬
Intelligence Application: Year-over-year comparisons identify whether current legislative activity is above or below historical baselines. Significant deviations may indicate changing political priorities, coalition dynamics, or procedural changes.
5. Forecast Legislative Activity (Simple Moving Average)
Use 30-day moving average to forecast expected decision volumes for upcoming week.
WITH recent_trend AS (
SELECT
ROUND(AVG(ma_30day_decisions), 2) AS forecast_baseline,
ROUND(STDDEV(daily_decisions), 2) AS forecast_uncertainty
FROM view_decision_temporal_trends
WHERE decision_day >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT
CURRENT_DATE + INTERVAL '1 day' * generate_series(1, 7) AS forecast_date,
rt.forecast_baseline AS expected_decisions,
rt.forecast_baseline - rt.forecast_uncertainty AS lower_bound,
rt.forecast_baseline + rt.forecast_uncertainty AS upper_bound,
CASE
WHEN EXTRACT(DOW FROM CURRENT_DATE + INTERVAL '1 day' * generate_series(1, 7)) IN (0, 6) THEN 'Weekend (Low Activity)'
ELSE 'Weekday (Normal Activity)'
END AS activity_expectation
FROM recent_trend rt;
Sample Output:
forecast_date | expected_decisions | lower_bound | upper_bound | activity_expectation
--------------+--------------------+-------------+-------------+----------------------
2024-11-16 | 41.15 | 26.92 | 55.38 | Weekend (Low Activity)
2024-11-17 | 41.15 | 26.92 | 55.38 | Weekend (Low Activity)
2024-11-18 | 41.15 | 26.92 | 55.38 | Weekday (Normal Activity)
2024-11-19 | 41.15 | 26.92 | 55.38 | Weekday (Normal Activity)
2024-11-20 | 41.15 | 26.92 | 55.38 | Weekday (Normal Activity)
Intelligence Application: Simple forecasting using moving average baseline provides expected decision volumes. Actual volumes significantly outside bounds indicate unusual activity warranting investigation.
6. Parliamentary Session Effectiveness
Compare approval rates across different parliamentary periods to identify procedural patterns.
SELECT
parliamentary_period,
COUNT(*) AS total_days,
ROUND(AVG(daily_decisions), 2) AS avg_decisions_per_day,
ROUND(AVG(daily_approval_rate), 2) AS avg_approval_rate,
ROUND(AVG(ma_30day_approval_rate), 2) AS smoothed_approval_rate,
ROUND(SUM(daily_decisions), 0) AS total_decisions,
ROUND(SUM(approved_decisions), 0) AS total_approved,
ROUND(SUM(rejected_decisions), 0) AS total_rejected
FROM view_decision_temporal_trends
WHERE decision_day >= CURRENT_DATE - INTERVAL '2 years'
GROUP BY parliamentary_period
ORDER BY total_decisions DESC;
Sample Output:
parliamentary_period | total_days | avg_decisions_per_day | avg_approval_rate | smoothed_approval_rate | total_decisions | total_approved | total_rejected
------------------------+------------+-----------------------+-------------------+------------------------+-----------------+----------------+---------------
Autumn Session | 245 | 42.15 | 68.30 | 68.50 | 10327 | 7053 | 2845
Late Spring Session | 198 | 38.72 | 67.80 | 68.10 | 7667 | 5198 | 2134
Spring Session | 156 | 35.45 | 66.50 | 67.20 | 5530 | 3677 | 1623
Winter Recess | 45 | 8.23 | 71.20 | 71.80 | 370 | 263 | 95
Summer Recess | 38 | 5.67 | 69.40 | 70.10 | 215 | 149 | 58
Intelligence Application: Identifies highest productivity periods (Autumn Session) and approval rate variations by season. Recess periods show higher approval rates but much lower volume, suggesting only consensus items are processed during these periods.
Performance Characteristics
- Query Time: 200-500ms (5-year rolling window, daily granularity)
- Refresh Frequency: Real-time (recalculates on each query)
- Data Volume: ~1,825 rows (5 years Γ 365 days, filtered to days with decisions)
- Optimization: Indexed on
document_data.made_public_datefor temporal queries
Data Sources
- Primary Table:
document_proposal_data(proposal decision text) - Join Path:
document_proposal_dataβdocument_proposal_containerβdocument_status_containerβdocument_data(dates) - Time Range: Last 5 years (configurable in view definition)
Intelligence Frameworks Applicable
From DATA_ANALYSIS_INTOP_OSINT.md:
- Temporal Analysis Framework: Primary implementation of time-series decision analysis
- Predictive Intelligence Framework: Forecasting legislative activity using moving averages
- Pattern Recognition Framework: Seasonal decomposition and anomaly detection
- Strategic Assessment: Parliamentary productivity monitoring and baseline comparison
Intelligence Applications
- Forecast Legislative Activity: Predict decision volumes for upcoming months based on moving average trends
- Detect Anomalous Decision Volumes: Identify bottlenecks or unusual activity through z-score analysis
- Compare to Historical Baselines: Year-over-year comparison to assess if current session is above/below normal
- Identify Seasonal Patterns: Resource planning based on parliamentary calendar patterns
- Trend Detection: Moving average crossovers signal acceleration or deceleration in legislative activity
- Crisis Response: Monitor decision volume drops during political crises or government transitions
Dependencies
- Depends on:
document_proposal_data,document_proposal_container,document_status_container,document_data - Used by: Predictive analytics dashboards, legislative planning tools, anomaly detection systems
- Complements:
view_riksdagen_party_decision_flow,view_riksdagen_politician_decision_pattern
Related Views
- view_riksdagen_party_decision_flow: Party-level decision aggregation (v1.35)
- view_riksdagen_politician_decision_pattern: Individual politician decision patterns (v1.35)
- view_politician_behavioral_trends: Behavioral time-series analysis (v1.30)
view_riksdagen_vote_data_ballot_party_summary βββββ
Purpose: Aggregates party-level voting behavior across all ballots (base view for temporal summaries).
Key Metrics: party, ballot_id, total_votes, yes_votes, no_votes, abstain_votes, absent_votes, party_win_rate
Sample Query: SELECT party, SUM(total_votes) as total, AVG(party_win_rate) as avg_win_rate FROM view_riksdagen_vote_data_ballot_party_summary GROUP BY party ORDER BY avg_win_rate DESC;
Applications: Party voting behavior analysis, coalition alignment assessment, party discipline tracking
view_riksdagen_vote_data_ballot_party_summary_annual βββββ
Purpose: Annual aggregation of party voting behavior for long-term trend analysis.
Key Metrics: year, party, ballot_count, total_votes, avg_win_rate, party_cohesion_score
Sample Query: SELECT year, party, ballot_count, ROUND(avg_win_rate, 2) as win_rate FROM view_riksdagen_vote_data_ballot_party_summary_annual WHERE year >= 2020 ORDER BY year DESC, win_rate DESC;
Applications: Long-term party performance tracking, electoral cycle analysis, government effectiveness assessment
view_riksdagen_vote_data_ballot_party_summary_daily βββββ
Purpose: Daily aggregation of party voting behavior for real-time monitoring.
Key Metrics: vote_date, party, ballot_count, yes_votes, no_votes, daily_win_rate, daily_discipline_rate
Sample Query: SELECT vote_date, party, ballot_count, ROUND(daily_win_rate, 2) as win_rate FROM view_riksdagen_vote_data_ballot_party_summary_daily WHERE vote_date >= CURRENT_DATE - 7 ORDER BY vote_date DESC, ballot_count DESC;
Applications: Daily party performance tracking, coalition monitoring, legislative session analysis
view_riksdagen_vote_data_ballot_party_summary_monthly βββββ
Purpose: Monthly aggregation of party voting behavior for medium-term trend analysis.
Key Metrics: month, party, ballot_count, monthly_win_rate, coalition_alignment_score
Sample Query: SELECT DATE_TRUNC('month', month) as month, party, ballot_count, ROUND(monthly_win_rate, 2) FROM view_riksdagen_vote_data_ballot_party_summary_monthly WHERE month >= CURRENT_DATE - INTERVAL '12 months' ORDER BY month DESC;
Applications: Monthly performance reports, coalition stability tracking, trend identification
view_riksdagen_vote_data_ballot_party_summary_weekly βββββ
Purpose: Weekly aggregation of party voting behavior for short-term trend analysis.
Key Metrics: week_start_date, party, ballot_count, weekly_win_rate, weekly_absence_rate
Sample Query: SELECT week_start_date, party, ballot_count, ROUND(weekly_win_rate, 2) as win_rate FROM view_riksdagen_vote_data_ballot_party_summary_weekly WHERE week_start_date >= CURRENT_DATE - 30 ORDER BY week_start_date DESC;
Applications: Weekly performance tracking, short-term trend analysis, legislative activity monitoring
view_riksdagen_vote_data_ballot_politician_summary βββββ
Purpose: Aggregates individual politician voting behavior across all ballots (base view for temporal summaries).
Key Metrics: intressent_id, first_name, last_name, party, total_ballots, total_votes, win_rate, absence_rate, rebel_rate
Sample Query: SELECT first_name, last_name, party, total_ballots, ROUND(win_rate, 2), ROUND(absence_rate, 2) FROM view_riksdagen_vote_data_ballot_politician_summary ORDER BY total_ballots DESC LIMIT 20;
Applications: Individual politician performance scorecards, attendance tracking, party discipline analysis
view_riksdagen_vote_data_ballot_politician_summary_annual βββββ
Purpose: Annual aggregation of individual politician voting behavior for yearly comparisons.
Key Metrics: year, intressent_id, first_name, last_name, party, ballot_count, annual_win_rate, annual_absence_rate
Sample Query: SELECT year, first_name, last_name, party, ballot_count, ROUND(annual_win_rate, 2) as win_rate FROM view_riksdagen_vote_data_ballot_politician_summary_annual WHERE year >= 2020 ORDER BY year DESC, ballot_count DESC;
Applications: Annual performance reviews, electoral term analysis, career trajectory tracking
view_riksdagen_vote_data_ballot_politician_summary_monthly βββββ
Purpose: Monthly aggregation of individual politician voting behavior for medium-term tracking.
Key Metrics: month, intressent_id, first_name, last_name, party, ballot_count, monthly_win_rate, monthly_absence_rate
Sample Query: SELECT DATE_TRUNC('month', month) as month, first_name, last_name, party, ballot_count FROM view_riksdagen_vote_data_ballot_politician_summary_monthly WHERE month >= CURRENT_DATE - INTERVAL '6 months' ORDER BY month DESC;
Applications: Monthly politician scorecards, attendance monitoring, performance trending
view_riksdagen_vote_data_ballot_politician_summary_weekly βββββ
Purpose: Weekly aggregation of individual politician voting behavior for short-term monitoring.
Key Metrics: week_start_date, intressent_id, first_name, last_name, party, ballot_count, weekly_win_rate, weekly_absence_rate
Sample Query: SELECT week_start_date, first_name, last_name, party, ballot_count, ROUND(weekly_absence_rate, 2) FROM view_riksdagen_vote_data_ballot_politician_summary_weekly WHERE week_start_date >= CURRENT_DATE - 30 ORDER BY weekly_absence_rate DESC;
Applications: Weekly performance tracking, attendance alerts, short-term behavior analysis
view_riksdagen_vote_data_ballot_summary βββββ
Purpose: Aggregates overall ballot-level voting statistics (base view for temporal summaries).
Key Metrics: ballot_id, ballot_date, issue, total_voters, yes_count, no_count, abstain_count, absent_count, winning_side
Sample Query: SELECT ballot_id, ballot_date, issue, total_voters, yes_count, no_count FROM view_riksdagen_vote_data_ballot_summary ORDER BY ballot_date DESC LIMIT 20;
Applications: Ballot outcome tracking, voting patterns analysis, chamber activity monitoring
view_riksdagen_vote_data_ballot_summary_annual βββββ
Purpose: Annual aggregation of ballot statistics for yearly legislative activity analysis.
Key Metrics: year, total_ballots, avg_participation_rate, contentious_vote_count, unanimous_vote_count
Sample Query: SELECT year, total_ballots, ROUND(avg_participation_rate, 2) as participation FROM view_riksdagen_vote_data_ballot_summary_annual WHERE year >= 2020 ORDER BY year DESC;
Applications: Annual legislative activity reports, participation trend analysis, chamber effectiveness assessment
view_riksdagen_vote_data_ballot_summary_daily βββββ
Purpose: Daily aggregation of ballot statistics for real-time legislative activity monitoring.
Key Metrics: vote_date, ballot_count, avg_participation_rate, total_votes_cast
Sample Query: SELECT vote_date, ballot_count, ROUND(avg_participation_rate, 2) as participation FROM view_riksdagen_vote_data_ballot_summary_daily WHERE vote_date >= CURRENT_DATE - 7 ORDER BY vote_date DESC;
Applications: Daily legislative activity tracking, session monitoring, participation alerts
view_riksdagen_vote_data_ballot_summary_monthly βββββ
Purpose: Monthly aggregation of ballot statistics for medium-term legislative activity tracking.
Key Metrics: month, total_ballots, avg_participation_rate, legislative_intensity_score
Sample Query: SELECT DATE_TRUNC('month', month) as month, total_ballots, ROUND(avg_participation_rate, 2) FROM view_riksdagen_vote_data_ballot_summary_monthly WHERE month >= CURRENT_DATE - INTERVAL '12 months' ORDER BY month DESC;
Applications: Monthly legislative reports, activity trending, session comparison
view_riksdagen_vote_data_ballot_summary_weekly βββββ
Purpose: Weekly aggregation of ballot statistics for short-term legislative activity analysis.
Key Metrics: week_start_date, ballot_count, avg_participation_rate, weekly_legislative_activity
Sample Query: SELECT week_start_date, ballot_count, ROUND(avg_participation_rate, 2) as participation FROM view_riksdagen_vote_data_ballot_summary_weekly WHERE week_start_date >= CURRENT_DATE - 30 ORDER BY week_start_date DESC;
Applications: Weekly activity tracking, legislative pace monitoring, session planning
Common Usage Patterns
Overview
This section provides the Top 20 analytical queries most frequently used by intelligence analysts, journalists, researchers, and developers. These patterns demonstrate real-world use cases and query optimization techniques.
Category: Politician Performance Analysis
Pattern 1: Comprehensive Politician Scorecard (Last 12 Months)
Use Case: Generate complete performance report for individual MP or party group
WITH performance_12mo AS (
SELECT
person_id,
first_name,
last_name,
party,
AVG(avg_absence_rate) AS avg_absence,
AVG(avg_win_rate) AS avg_win,
AVG(avg_rebel_rate) AS avg_rebel,
COUNT(*) AS months_active
FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months'
AND ballot_count >= 5
GROUP BY person_id, first_name, last_name, party
),
experience AS (
SELECT
person_id,
total_years,
total_weighted_exp,
experience_level,
ministerial_experience,
committee_leadership_exp
FROM view_riksdagen_politician_experience_summary
),
productivity AS (
SELECT
person_id,
COUNT(*) AS total_documents,
COUNT(*) FILTER (WHERE document_type = 'Motion') AS motions,
COUNT(*) FILTER (WHERE document_type = 'Interpellation') AS interpellations
FROM view_riksdagen_politician_document
WHERE made_public_date >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY person_id
),
risk_current AS (
SELECT
person_id,
risk_score,
risk_severity,
risk_trajectory
FROM view_risk_score_evolution
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
)
SELECT
p.first_name,
p.last_name,
p.party,
-- Performance Metrics
ROUND(p.avg_absence, 2) AS absence_rate_12mo,
ROUND(p.avg_win, 2) AS win_rate_12mo,
ROUND(p.avg_rebel, 2) AS rebel_rate_12mo,
-- Experience
ROUND(e.total_years, 1) AS years_experience,
e.experience_level,
e.ministerial_experience AS former_minister,
e.committee_leadership_exp AS former_chair,
-- Productivity
COALESCE(pr.total_documents, 0) AS documents_12mo,
COALESCE(pr.motions, 0) AS motions_12mo,
COALESCE(pr.interpellations, 0) AS interpellations_12mo,
-- Risk Assessment
COALESCE(r.risk_score, 0) AS current_risk_score,
COALESCE(r.risk_severity, 'NONE') AS risk_level,
COALESCE(r.risk_trajectory, 'STABLE') AS risk_trend,
-- Overall Assessment
CASE
WHEN p.avg_absence < 5 AND p.avg_win > 65 AND COALESCE(r.risk_score, 0) < 50 THEN 'EXCELLENT'
WHEN p.avg_absence < 10 AND p.avg_win > 55 AND COALESCE(r.risk_score, 0) < 75 THEN 'GOOD'
WHEN p.avg_absence < 20 AND p.avg_win > 45 THEN 'SATISFACTORY'
ELSE 'CONCERNING'
END AS overall_assessment
FROM performance_12mo p
LEFT JOIN experience e ON e.person_id = p.person_id
LEFT JOIN productivity pr ON pr.person_id = p.person_id
LEFT JOIN risk_current r ON r.person_id = p.person_id
ORDER BY p.party, p.last_name;
Output Format: CSV-ready, suitable for Excel/BI tools
Pattern 2: Party Comparative Dashboard
Use Case: Real-time party comparison for news reporting or research
WITH current_month AS (
SELECT
party,
AVG(avg_party_absence_rate) AS party_absence,
AVG(avg_party_win_rate) AS party_effectiveness,
AVG(avg_party_discipline) AS party_discipline,
SUM(total_documents) AS party_documents
FROM view_party_effectiveness_trends
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
GROUP BY party
),
member_counts AS (
SELECT
party,
member_count
FROM view_riksdagen_party
WHERE member_count > 0
),
risk_summary AS (
SELECT
party,
COUNT(*) AS members_assessed,
AVG(risk_score) AS avg_risk,
COUNT(*) FILTER (WHERE risk_severity = 'CRITICAL') AS critical_members,
COUNT(*) FILTER (WHERE risk_severity = 'MAJOR') AS major_members
FROM view_risk_score_evolution
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
GROUP BY party
)
SELECT
mc.party,
mc.member_count AS seats,
ROUND(cm.party_absence, 2) AS absence_rate,
ROUND(cm.party_effectiveness, 2) AS effectiveness_rate,
ROUND(cm.party_discipline, 2) AS discipline_rate,
cm.party_documents AS monthly_documents,
ROUND(cm.party_documents::NUMERIC / mc.member_count, 1) AS docs_per_member,
COALESCE(rs.members_assessed, 0) AS members_monitored,
ROUND(COALESCE(rs.avg_risk, 0), 1) AS avg_risk_score,
COALESCE(rs.critical_members, 0) AS high_risk_members,
-- Overall Health Score (0-100)
ROUND(
(100 - cm.party_absence) * 0.3 + -- Attendance weight
cm.party_effectiveness * 0.4 + -- Effectiveness weight
cm.party_discipline * 0.2 + -- Discipline weight
LEAST((cm.party_documents::NUMERIC / mc.member_count) * 10, 10) * 0.1 -- Productivity weight
, 1) AS health_score
FROM member_counts mc
LEFT JOIN current_month cm ON cm.party = mc.party
LEFT JOIN risk_summary rs ON rs.party = mc.party
ORDER BY health_score DESC;
Use Case: Dashboard display, party ranking, media briefings
Category: Coalition Analysis
Pattern 3: Government Formation Scenarios (Seat + Alignment Analysis)
Use Case: Post-election coalition modeling
WITH party_seats AS (
SELECT
party,
member_count AS seats
FROM view_riksdagen_party
WHERE member_count > 0
),
coalition_pairs AS (
SELECT
cam.party_1,
cam.party_2,
ps1.seats AS seats_1,
ps2.seats AS seats_2,
ps1.seats + ps2.seats AS combined_seats_2party,
cam.alignment_rate,
cam.coalition_likelihood
FROM view_riksdagen_coalition_alignment_matrix cam
JOIN party_seats ps1 ON ps1.party = cam.party_1
JOIN party_seats ps2 ON ps2.party = cam.party_2
WHERE cam.alignment_rate >= 60 -- Minimum viable alignment
),
three_party_combos AS (
SELECT
cp1.party_1,
cp1.party_2,
ps3.party AS party_3,
cp1.seats_1 + cp1.seats_2 + ps3.seats AS combined_seats_3party,
ROUND((cp1.alignment_rate + cam2.alignment_rate + cam3.alignment_rate) / 3, 2) AS avg_alignment,
cp1.coalition_likelihood AS likelihood_1_2,
cam2.coalition_likelihood AS likelihood_1_3,
cam3.coalition_likelihood AS likelihood_2_3
FROM coalition_pairs cp1
CROSS JOIN party_seats ps3
LEFT JOIN view_riksdagen_coalition_alignment_matrix cam2
ON (cam2.party_1 = cp1.party_1 AND cam2.party_2 = ps3.party)
OR (cam2.party_1 = ps3.party AND cam2.party_2 = cp1.party_1)
LEFT JOIN view_riksdagen_coalition_alignment_matrix cam3
ON (cam3.party_1 = cp1.party_2 AND cam3.party_2 = ps3.party)
OR (cam3.party_1 = ps3.party AND cam3.party_2 = cp1.party_2)
WHERE ps3.party NOT IN (cp1.party_1, cp1.party_2)
AND cp1.combined_seats_2party + ps3.seats >= 175 -- Majority threshold
)
SELECT
party_1 || '+' || party_2 || '+' || party_3 AS coalition,
combined_seats_3party AS seats,
combined_seats_3party - 175 AS majority_margin,
ROUND(avg_alignment, 2) AS avg_alignment,
CASE
WHEN avg_alignment >= 75 THEN 'HIGHLY_VIABLE'
WHEN avg_alignment >= 65 THEN 'VIABLE'
WHEN avg_alignment >= 60 THEN 'CHALLENGING'
ELSE 'DIFFICULT'
END AS viability_assessment
FROM three_party_combos
WHERE avg_alignment IS NOT NULL
ORDER BY combined_seats_3party DESC, avg_alignment DESC
LIMIT 15;
Output: Coalition scenarios ranked by viability
Pattern 4: Bloc Cohesion Analysis
Use Case: Evaluate internal bloc unity vs. cross-bloc cooperation
WITH bloc_definition AS (
SELECT
party,
CASE
WHEN party IN ('S', 'V', 'MP') THEN 'LEFT'
WHEN party IN ('M', 'KD', 'L', 'C') THEN 'RIGHT'
WHEN party = 'SD' THEN 'SD'
ELSE 'OTHER'
END AS bloc
FROM view_riksdagen_party
WHERE member_count > 0
),
alignment_with_bloc AS (
SELECT
bd1.party,
bd1.bloc,
cam.party_2,
bd2.bloc AS party_2_bloc,
cam.alignment_rate,
CASE
WHEN bd1.bloc = bd2.bloc THEN 'INTERNAL'
ELSE 'CROSS_BLOC'
END AS relationship_type
FROM view_riksdagen_coalition_alignment_matrix cam
JOIN bloc_definition bd1 ON bd1.party = cam.party_1
JOIN bloc_definition bd2 ON bd2.party = cam.party_2
)
SELECT
bloc,
party,
ROUND(AVG(alignment_rate) FILTER (WHERE relationship_type = 'INTERNAL'), 2) AS avg_internal_alignment,
ROUND(AVG(alignment_rate) FILTER (WHERE relationship_type = 'CROSS_BLOC'), 2) AS avg_cross_bloc_alignment,
ROUND(AVG(alignment_rate) FILTER (WHERE relationship_type = 'INTERNAL'), 2) -
ROUND(AVG(alignment_rate) FILTER (WHERE relationship_type = 'CROSS_BLOC'), 2) AS cohesion_gap,
CASE
WHEN AVG(alignment_rate) FILTER (WHERE relationship_type = 'INTERNAL') > 80 THEN 'HIGHLY_COHESIVE'
WHEN AVG(alignment_rate) FILTER (WHERE relationship_type = 'INTERNAL') > 70 THEN 'COHESIVE'
WHEN AVG(alignment_rate) FILTER (WHERE relationship_type = 'INTERNAL') > 60 THEN 'MODERATE'
ELSE 'FRACTURED'
END AS bloc_cohesion
FROM alignment_with_bloc
GROUP BY bloc, party
ORDER BY bloc, avg_internal_alignment DESC;
Category: Trend Analysis & Forecasting
Pattern 5: Politician Risk Trajectory Forecasting
Use Case: Predict future risk scores based on trends (simple linear extrapolation)
WITH risk_history AS (
SELECT
person_id,
first_name,
last_name,
party,
year_month,
risk_score,
ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY year_month DESC) AS month_rank
FROM view_risk_score_evolution
WHERE year_month >= CURRENT_DATE - INTERVAL '6 months'
),
trend_calculation AS (
SELECT
person_id,
first_name,
last_name,
party,
AVG(risk_score) AS avg_risk_6mo,
REGR_SLOPE(risk_score, EXTRACT(EPOCH FROM year_month)) AS risk_slope,
REGR_INTERCEPT(risk_score, EXTRACT(EPOCH FROM year_month)) AS risk_intercept,
MAX(risk_score) AS max_risk,
MIN(risk_score) AS min_risk
FROM risk_history
WHERE month_rank <= 6
GROUP BY person_id, first_name, last_name, party
HAVING COUNT(*) >= 4 -- Minimum data points
)
SELECT
first_name,
last_name,
party,
ROUND(avg_risk_6mo, 1) AS current_avg_risk,
max_risk,
min_risk,
ROUND(risk_slope * 2592000, 2) AS monthly_trend, -- Slope Γ seconds in 30 days
ROUND(
risk_intercept + risk_slope * EXTRACT(EPOCH FROM CURRENT_DATE + INTERVAL '3 months'),
1
) AS projected_risk_3mo,
CASE
WHEN risk_slope * 2592000 > 5 THEN 'RAPID_DETERIORATION'
WHEN risk_slope * 2592000 > 2 THEN 'MODERATE_DETERIORATION'
WHEN risk_slope * 2592000 > -2 THEN 'STABLE'
WHEN risk_slope * 2592000 > -5 THEN 'IMPROVING'
ELSE 'RAPID_IMPROVEMENT'
END AS risk_trajectory_forecast
FROM trend_calculation
WHERE ABS(risk_slope * 2592000) > 1 -- Significant trend
ORDER BY risk_slope * 2592000 DESC
LIMIT 20;
Output: Predictive risk forecast for intervention planning
Category: Productivity & Document Intelligence
Pattern 6: Policy Focus Clustering (Topic Analysis)
Use Case: Identify politician specializations and policy priorities
WITH document_activity AS (
SELECT
person_id,
first_name,
last_name,
party,
org_code AS policy_area,
COUNT(*) AS document_count,
STRING_AGG(DISTINCT document_type, ', ') AS document_types,
MAX(made_public_date) AS latest_activity
FROM view_riksdagen_politician_document
WHERE made_public_date >= CURRENT_DATE - INTERVAL '24 months'
GROUP BY person_id, first_name, last_name, party, org_code
),
total_documents AS (
SELECT
person_id,
SUM(document_count) AS total_docs
FROM document_activity
GROUP BY person_id
),
policy_concentration AS (
SELECT
da.person_id,
da.first_name,
da.last_name,
da.party,
da.policy_area,
da.document_count,
ROUND(100.0 * da.document_count / td.total_docs, 1) AS concentration_pct,
da.latest_activity,
ROW_NUMBER() OVER (PARTITION BY da.person_id ORDER BY da.document_count DESC) AS policy_rank
FROM document_activity da
JOIN total_documents td ON td.person_id = da.person_id
WHERE td.total_docs >= 10 -- Minimum activity threshold
)
SELECT
first_name,
last_name,
party,
policy_area AS primary_focus,
document_count AS docs_in_area,
concentration_pct AS focus_concentration,
latest_activity,
CASE
WHEN concentration_pct >= 50 THEN 'SPECIALIST'
WHEN concentration_pct >= 30 THEN 'FOCUSED'
WHEN concentration_pct >= 20 THEN 'DIVERSIFIED'
ELSE 'GENERALIST'
END AS specialization_profile
FROM policy_concentration
WHERE policy_rank = 1 -- Top policy area for each politician
AND document_count >= 5
ORDER BY concentration_pct DESC
LIMIT 30;
Category: Temporal & Seasonal Analysis
Pattern 7: Parliamentary Activity Seasonality
Use Case: Identify seasonal patterns in voting and document submission
WITH monthly_activity AS (
SELECT
DATE_TRUNC('month', vote_date) AS month,
EXTRACT(MONTH FROM vote_date) AS month_number,
EXTRACT(YEAR FROM vote_date) AS year,
COUNT(DISTINCT vote_date) AS sitting_days,
SUM(ballot_count) AS total_ballots,
AVG(ballot_count) AS avg_ballots_per_day,
SUM(absent_votes) AS total_absences,
ROUND(100.0 * SUM(absent_votes) / SUM(ballot_count), 2) AS absence_rate
FROM view_riksdagen_vote_data_ballot_politician_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '36 months'
GROUP BY DATE_TRUNC('month', vote_date), EXTRACT(MONTH FROM vote_date), EXTRACT(YEAR FROM vote_date)
),
seasonal_averages AS (
SELECT
month_number,
TO_CHAR(TO_DATE(month_number::TEXT, 'MM'), 'Month') AS month_name,
COUNT(*) AS years_in_sample,
ROUND(AVG(sitting_days), 1) AS avg_sitting_days,
ROUND(AVG(total_ballots), 0) AS avg_ballots,
ROUND(AVG(absence_rate), 2) AS avg_absence_rate
FROM monthly_activity
GROUP BY month_number
)
SELECT
month_name,
avg_sitting_days,
avg_ballots,
avg_absence_rate,
CASE
WHEN month_number IN (7, 8) THEN 'SUMMER_RECESS'
WHEN month_number IN (12, 1) THEN 'WINTER_RECESS'
WHEN month_number IN (3, 4) THEN 'EASTER_PERIOD'
WHEN month_number IN (9, 10, 11) THEN 'AUTUMN_SESSION'
WHEN month_number IN (2, 5, 6) THEN 'SPRING_SESSION'
END AS parliamentary_period,
CASE
WHEN avg_sitting_days > 15 THEN 'HIGH_ACTIVITY'
WHEN avg_sitting_days > 10 THEN 'MODERATE_ACTIVITY'
WHEN avg_sitting_days > 5 THEN 'LOW_ACTIVITY'
ELSE 'RECESS'
END AS activity_classification
FROM seasonal_averages
ORDER BY month_number;
Category: Anomaly Detection & Outlier Analysis
Pattern 8: Statistical Outlier Detection (Z-Score Method)
Use Case: Identify politicians with statistically abnormal behavior
WITH recent_performance AS (
SELECT
person_id,
first_name,
last_name,
party,
AVG(avg_absence_rate) AS avg_absence,
AVG(avg_win_rate) AS avg_win,
AVG(avg_rebel_rate) AS avg_rebel,
COUNT(*) AS months_tracked
FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months'
AND ballot_count >= 10
GROUP BY person_id, first_name, last_name, party
HAVING COUNT(*) >= 6 -- At least 6 months of data
),
population_stats AS (
SELECT
AVG(avg_absence) AS mean_absence,
STDDEV(avg_absence) AS stddev_absence,
AVG(avg_win) AS mean_win,
STDDEV(avg_win) AS stddev_win,
AVG(avg_rebel) AS mean_rebel,
STDDEV(avg_rebel) AS stddev_rebel
FROM recent_performance
),
z_scores AS (
SELECT
rp.first_name,
rp.last_name,
rp.party,
ROUND(rp.avg_absence, 2) AS absence_rate,
ROUND(rp.avg_win, 2) AS win_rate,
ROUND(rp.avg_rebel, 2) AS rebel_rate,
ROUND((rp.avg_absence - ps.mean_absence) / NULLIF(ps.stddev_absence, 0), 2) AS absence_z_score,
ROUND((rp.avg_win - ps.mean_win) / NULLIF(ps.stddev_win, 0), 2) AS win_z_score,
ROUND((rp.avg_rebel - ps.mean_rebel) / NULLIF(ps.stddev_rebel, 0), 2) AS rebel_z_score
FROM recent_performance rp
CROSS JOIN population_stats ps
)
SELECT
first_name,
last_name,
party,
absence_rate,
absence_z_score,
win_rate,
win_z_score,
rebel_rate,
rebel_z_score,
CASE
WHEN ABS(absence_z_score) > 3 OR ABS(win_z_score) > 3 OR ABS(rebel_z_score) > 3 THEN 'EXTREME_OUTLIER'
WHEN ABS(absence_z_score) > 2 OR ABS(win_z_score) > 2 OR ABS(rebel_z_score) > 2 THEN 'SIGNIFICANT_OUTLIER'
WHEN ABS(absence_z_score) > 1.5 OR ABS(win_z_score) > 1.5 OR ABS(rebel_z_score) > 1.5 THEN 'MODERATE_OUTLIER'
ELSE 'NORMAL'
END AS outlier_classification
FROM z_scores
WHERE ABS(absence_z_score) > 1.5 OR ABS(win_z_score) > 1.5 OR ABS(rebel_z_score) > 1.5
ORDER BY
GREATEST(ABS(absence_z_score), ABS(win_z_score), ABS(rebel_z_score)) DESC
LIMIT 25;
View Dependency Diagram
Data Lineage: From Source Tables to Intelligence Products
graph TB
subgraph "Source Tables (Core Schema)"
T1[person_data]
T2[assignment_data]
T3[vote_data]
T4[document_data]
T5[committee_document_data]
T6[rule_violation]
end
subgraph "Base Views (v1.0-v1.19)"
V1[view_riksdagen_politician]
V2[view_riksdagen_party]
V3[view_riksdagen_committee]
V4[view_riksdagen_ministry]
V5[view_riksdagen_politician_document]
end
subgraph "Vote Aggregation Views (v1.2-v1.25)"
V6[view_riksdagen_vote_data_ballot_summary_daily]
V7[view_riksdagen_vote_data_ballot_party_summary_daily]
V8[view_riksdagen_vote_data_ballot_politician_summary_daily]
end
subgraph "Experience & Productivity (v1.23-v1.28)"
V9[view_riksdagen_politician_experience_summary]
V10[view_riksdagen_party_ballot_support_annual_summary]
V11[view_riksdagen_party_document_summary]
end
subgraph "Intelligence Views (v1.29-v1.30)"
V12[view_politician_behavioral_trends]
V13[view_party_effectiveness_trends]
V14[view_risk_score_evolution]
V15[view_riksdagen_coalition_alignment_matrix]
V16[view_riksdagen_intelligence_dashboard]
end
T1 --> V1
T2 --> V1
T2 --> V9
T3 --> V6
T3 --> V7
T3 --> V8
T4 --> V5
T4 --> V11
V1 --> V12
V1 --> V14
V2 --> V13
V2 --> V15
V8 --> V12
V7 --> V13
V12 --> V14
V13 --> V16
V14 --> V16
V15 --> V16
V6 --> V10
T6 --> V14
style T1 fill:#fdecea,stroke:#333,stroke-width:2px
style T2 fill:#fdecea,stroke:#333,stroke-width:2px
style T3 fill:#fdecea,stroke:#333,stroke-width:2px
style T4 fill:#fdecea,stroke:#333,stroke-width:2px
style V12 fill:#ffeb99,stroke:#333,stroke-width:3px
style V13 fill:#ffeb99,stroke:#333,stroke-width:3px
style V14 fill:#ffcccc,stroke:#333,stroke-width:3px
style V15 fill:#e1f5ff,stroke:#333,stroke-width:3px
style V16 fill:#ccffcc,stroke:#333,stroke-width:3px
View Dependency Levels
| Level | Views | Description |
|---|---|---|
| Level 0 | Source Tables | Raw data (person_data, vote_data, document_data, etc.) |
| Level 1 | Base Views | Direct table aggregations (politician, party, committee) |
| Level 2 | Vote Summaries | Daily/weekly/monthly/annual aggregations (materialized) |
| Level 3 | Experience & Productivity | Complex aggregations with business logic |
| Level 4 | Intelligence Views | Advanced analytics combining multiple sources |
| Level 5 | Dashboard Views | Unified intelligence products |
Performance Optimization Guide
Query Optimization Best Practices
1. Always Filter by Date Range
Problem: Querying entire view history (10+ years) is slow and resource-intensive
Solution: Add date filters to WHERE clause
-- β BAD: Slow (queries all history)
SELECT * FROM view_politician_behavioral_trends;
-- β
GOOD: Fast (filters to recent data)
SELECT * FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months';
Performance Impact: 10-100x improvement
2. Use Minimum Sample Size Filters
Problem: Low-sample politicians/parties skew averages and waste computation
Solution: Filter by ballot_count, document_count, or equivalent
-- β
GOOD: Filter low-activity records
WHERE ballot_count >= 10 -- At least 10 ballots for statistical validity
AND months_tracked >= 3 -- At least 3 months of data
Performance Impact: 2-5x improvement + better data quality
3. Leverage Indexes Effectively
Problem: Full table scans on large views without index usage
Solution: Use indexed columns in WHERE, JOIN, and ORDER BY clauses
Key Indexes:
| View Category | Indexed Columns | Use Case |
|---|---|---|
| Vote Summaries | vote_date, person_id, party | Temporal + entity filtering |
| Behavioral Trends | year_month, person_id, party | Time-series queries |
| Document Views | made_public_date, person_id, org_code | Productivity tracking |
| Risk Evolution | year_month, person_id, risk_severity | Risk monitoring |
-- β
GOOD: Uses indexes
SELECT * FROM view_politician_behavioral_trends
WHERE year_month >= '2024-01-01' -- Indexed
AND party = 'S' -- Indexed
AND ballot_count >= 10;
-- β BAD: Function prevents index usage
WHERE EXTRACT(YEAR FROM year_month) = 2024 -- No index
4. Use Materialized Views for Dashboards
Problem: Complex aggregation views are slow for real-time dashboards
Solution: Use materialized views (refreshed daily) for dashboard queries
Available Materialized Views (v1.25+):
| View | Refresh Schedule | Performance Gain |
|---|---|---|
view_riksdagen_vote_data_ballot_summary_daily | Daily 02:00 UTC | 50-200x |
view_riksdagen_vote_data_ballot_party_summary_daily | Daily 02:00 UTC | 30-100x |
view_riksdagen_vote_data_ballot_politician_summary_daily | Daily 02:00 UTC | 100-500x |
| Committee decision views | Daily 02:00 UTC | 20-80x |
-- β
GOOD: Uses materialized view
SELECT * FROM view_riksdagen_vote_data_ballot_politician_summary_daily
WHERE vote_date >= CURRENT_DATE - INTERVAL '30 days';
-- Query time: <50ms
Planned v1.32 Materializations:
view_politician_behavioral_trends_matview_party_effectiveness_trends_matview_risk_score_evolution_mat
5. Optimize Aggregation Queries
Problem: Nested aggregations and multiple CTEs cause slow query plans
Solution: Use efficient aggregation patterns
-- β BAD: Multiple passes through data
SELECT
party,
(SELECT AVG(absence_rate) FROM view_politician_behavioral_trends WHERE party = p.party) AS avg_absence,
(SELECT AVG(win_rate) FROM view_politician_behavioral_trends WHERE party = p.party) AS avg_win
FROM view_riksdagen_party p;
-- β
GOOD: Single aggregation pass
SELECT
party,
AVG(absence_rate) AS avg_absence,
AVG(win_rate) AS avg_win
FROM view_politician_behavioral_trends
GROUP BY party;
6. Limit Result Sets
Problem: Returning thousands of rows when only top/bottom N needed
Solution: Use LIMIT and ORDER BY effectively
-- β
GOOD: Top 20 only
SELECT * FROM view_politician_behavioral_trends
WHERE year_month = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
ORDER BY avg_absence_rate DESC
LIMIT 20;
Index Usage Reference
| Index Name | Columns | Views Optimized | Performance Gain |
|---|---|---|---|
idx_vote_summary_daily_date_person | vote_date DESC, intressent_id | Politician behavioral trends, daily summaries | 10-100x |
idx_vote_summary_daily_party_date | party, vote_date DESC | Party effectiveness trends | 20-80x |
idx_rule_violation_date_resource | detected_date DESC, reference_id | Risk score evolution | 5-50x |
idx_politician_document_date_org | made_public_date DESC, person_id, org | Document productivity | 10-50x |
idx_document_data_ministry_date | org, made_public_date DESC | Ministry effectiveness | 10-50x |
idx_assignment_data_person_role | person_id, role_code, from_date | Experience summary | 20-100x |
Query Performance Benchmarks
| Query Pattern | Typical Response Time | Optimization Notes |
|---|---|---|
| Single politician lookup | <10ms | Indexed on person_id |
| Party comparison (8 parties) | 50-100ms | Use current month only |
| 12-month trend analysis | 100-200ms | Filter by date range |
| Coalition matrix (all pairs) | 200-400ms | Candidate for materialization |
| Risk score evolution (all politicians) | 150-300ms | Use date filters + LIMIT |
| Full behavioral trends (36 months) | 500ms-2s | Avoid without filters |
Common Performance Anti-Patterns
β Anti-Pattern 1: No Date Filters
-- Takes 5-10 seconds
SELECT * FROM view_politician_behavioral_trends;
β Solution:
-- Takes <200ms
SELECT * FROM view_politician_behavioral_trends
WHERE year_month >= CURRENT_DATE - INTERVAL '12 months';
β Anti-Pattern 2: Function-Based Filtering
-- Prevents index usage
WHERE EXTRACT(YEAR FROM year_month) = 2024
β Solution:
-- Uses index
WHERE year_month >= '2024-01-01'
AND year_month < '2025-01-01'
β Anti-Pattern 3: Cartesian Join Explosion
-- Creates millions of rows
SELECT *
FROM view_riksdagen_politician p1
CROSS JOIN view_riksdagen_politician p2;
β Solution:
-- Controlled cross join
SELECT *
FROM view_riksdagen_politician p1
CROSS JOIN view_riksdagen_politician p2
WHERE p1.person_id < p2.person_id -- Avoid duplicates
AND p1.party != p2.party -- Cross-party only
LIMIT 100;
Cross-Reference to Intelligence Frameworks
Risk Rules Mapping
Views supporting specific risk rules from RISK_RULES_INTOP_OSINT.md:
| Risk Rule | Rule ID | Supported By Views | Metrics Used |
|---|---|---|---|
| PoliticianLazy | P-01 | view_politician_behavioral_trends | avg_absence_rate, attendance_status |
| PoliticianIneffectiveVoting | P-02 | view_politician_behavioral_trends | avg_win_rate, effectiveness_status |
| PoliticianHighRebelRate | P-03 | view_politician_behavioral_trends | avg_rebel_rate, discipline_status |
| PoliticianDecliningEngagement | P-04 | view_politician_behavioral_trends | All trend metrics (absence_trend, etc.) |
| PoliticianCombinedRisk | P-05 | view_risk_score_evolution | risk_score, behavioral_assessment |
| PoliticianLowProductivity | P-06 | view_riksdagen_politician_document | Document counts by type |
| PartyWeakSupport | Y-01 | view_party_effectiveness_trends | avg_party_win_rate, effectiveness metrics |
| PartyCoalitionUnstable | Y-02 | view_riksdagen_coalition_alignment_matrix | alignment_rate, coalition_likelihood |
| PartyLowDiscipline | Y-03 | view_party_effectiveness_trends | avg_party_discipline |
| PartyIsolated | Y-05 | view_riksdagen_coalition_alignment_matrix | Low alignment rates across all parties |
Intelligence Frameworks Mapping
Views implementing frameworks from DATA_ANALYSIS_INTOP_OSINT.md:
| Framework | Description | Implementing Views |
|---|---|---|
| Temporal Analysis | Time-series tracking, trends | view_politician_behavioral_trends, view_party_effectiveness_trends, all vote summaries |
| Comparative Analysis | Entity comparison, benchmarking | view_riksdagen_politician, view_riksdagen_party, all summary views |
| Pattern Recognition | Behavioral classification, clustering | view_politician_behavioral_trends, view_risk_score_evolution |
| Predictive Intelligence | Forecasting, trend extrapolation | view_risk_score_evolution, trend metrics in behavioral views |
| Network Analysis | Relationship mapping | view_riksdagen_coalition_alignment_matrix (partial implementation) |
| Coalition Analysis | Government formation scenarios | view_riksdagen_coalition_alignment_matrix, party alignment views |
Product Feature Mapping
Views supporting features from BUSINESS_PRODUCT_DOCUMENT.md:
| Product Line | Feature | Supporting Views |
|---|---|---|
| Product Line 1: Core Intelligence | Politician Dashboard | view_riksdagen_politician, view_politician_behavioral_trends, view_riksdagen_politician_experience_summary |
| Product Line 1: Core Intelligence | Party Dashboard | view_riksdagen_party, view_party_effectiveness_trends |
| Product Line 2: Advanced Analytics | Performance Trends | All behavioral trend views, vote summary views |
| Product Line 2: Advanced Analytics | Comparative Analysis | All base views (politician, party, committee) |
| Product Line 3: Risk Intelligence | Risk Assessment Feed | view_risk_score_evolution, view_politician_behavioral_trends |
| Product Line 3: Risk Intelligence | Early Warning System | Trend metrics in all intelligence views |
| Product Line 4: Coalition Tools | Coalition Scenarios | view_riksdagen_coalition_alignment_matrix |
| Product Line 4: Coalition Tools | Government Formation | view_riksdagen_party, coalition alignment matrix |
Appendices
Appendix A: View Naming Conventions
Standard Patterns:
view_riksdagen_*: Swedish Parliament (Riksdagen) related viewsview_*_summary: Aggregation views (counts, averages)view_*_daily: Daily granularity materialized viewsview_*_weekly: Weekly granularity materialized viewsview_*_monthly: Monthly granularity materialized viewsview_*_annual: Annual granularity materialized viewsview_*_trends: Time-series trend analysis views (v1.30)view_*_evolution: Temporal change tracking (v1.30)view_*_matrix: Cross-entity relationship views (v1.29)
Appendix B: Swedish Political Terms Glossary
| Swedish Term | English Translation | Context |
|---|---|---|
| Riksdagen | The Swedish Parliament | Legislative body, 349 seats |
| Interpellation | Interpellation | Question to minister requiring debate |
| Motion | Motion | Legislative proposal by MP |
| Utskott | Committee | Specialized parliamentary committee |
| TjΓ€nstgΓΆrande riksdagsledamot | Serving member of parliament | Active MP status |
| FrΓ₯nvarande | Absent | Absent from vote |
| AvstΓ₯r | Abstain | Abstention vote |
| Ja | Yes | Affirmative vote |
| Nej | No | Negative vote |
Appendix C: View-to-Product Mapping
This appendix maps database views to business product features per BUSINESS_PRODUCT_DOCUMENT.md, establishing complete traceability from data sources to commercial products.
Total Addressable Market (TAM): β¬46M across 5 market segments (Political Consulting β¬15M, Media & Journalism β¬8M, Academic Research β¬5M, Corporate Affairs β¬12M, Government Transparency β¬6M)
Annual Revenue Potential: β¬5.1M across cross-product feature categories (see Cross-Product Feature Matrix below)
JSON Specifications: See json-export-specs/schemas/ for complete API schemas
Note on Revenue Models: This appendix presents two complementary revenue perspectives:
- Product Line Revenue (β¬630K + β¬855K + β¬1.77M + β¬525K = β¬3.78M): Individual product line subscription revenues
- Cross-Product Feature Matrix (β¬5.1M total): Feature-category-based revenue model reflecting cross-product feature usage and premium tiers. This is the primary revenue model used for strategic planning.
Product Line 1: Political Intelligence API (β¬630K annual revenue potential)
Revenue Source: BUSINESS_PRODUCT_DOCUMENT.md#product-line-1-political-intelligence-api - β¬630,000 total (β¬450K subscription fees + β¬60K overage + β¬120K custom development)
Target Segments: Political Consulting (β¬15M TAM), Media & Journalism (β¬8M TAM), Academic Research (β¬5M TAM)
| View | Product Feature | JSON Schema | API Endpoint | Market Segment | Revenue Tier |
|---|---|---|---|---|---|
view_riksdagen_politician | Politician Profiles | politician-schema.md | GET /api/v1/politicians | All segments | Pro β¬99/mo |
view_riksdagen_politician_summary | Politician Scorecards | politician-schema.md#intelligence | GET /api/v1/politicians/{id} | Political Consulting | Enterprise β¬330/mo |
view_riksdagen_party | Party Performance Data | party-schema.md | GET /api/v1/parties | Media & Journalism | Pro β¬99/mo |
view_riksdagen_party_summary | Party Analytics | party-schema.md#performance | GET /api/v1/parties/{id} | Political Consulting | Enterprise β¬330/mo |
view_riksdagen_vote_data_ballot_summary | Voting Statistics | politician-schema.md#voting | GET /api/v1/votes/{ballot_id} | Academic Research | Academic β¬50/mo |
view_riksdagen_vote_data_ballot_politician_summary | Individual Voting Records | politician-schema.md#voting | GET /api/v1/politicians/{id}/voting | All segments | Pro β¬99/mo |
view_rule_violation | Risk Assessment Feed | intelligence-schema.md | GET /api/v1/politicians/{id}/risk | Political Consulting | Premium feature |
Business Documentation: BUSINESS_PRODUCT_DOCUMENT.md#product-line-1
Product Line 2: Advanced Analytics Suite (β¬855K annual revenue potential)
Revenue Source: BUSINESS_PRODUCT_DOCUMENT.md#product-line-2-advanced-analytics-suite - β¬855,000 total (β¬720K subscription fees + β¬90K custom dashboards + β¬45K training)
Target Segments: Corporate Government Affairs (β¬12M TAM), NGOs & Advocacy, Political Parties
| View | Dashboard Component | Data Schema | Market Segment | Pricing Tier |
|---|---|---|---|---|
view_riksdagen_politician_ranking | Political Scorecards | politician-schema.md#intelligence | Corporate Affairs | Professional β¬6K/mo |
view_riksdagen_coalition_alignment_matrix | Coalition Stability Monitor | party-schema.md#coalition | Political Parties | Enterprise β¬15K/mo |
view_party_effectiveness_trends | Party Performance Dashboard | party-schema.md#intelligence | NGOs & Advocacy | Professional β¬6K/mo |
view_politician_behavioral_trends | Behavioral Analytics | intelligence-schema.md | Corporate Affairs | Enterprise β¬15K/mo |
view_riksdagen_committee_decisions | Committee Activity Tracker | committee-schema.md | All segments | Professional β¬6K/mo |
view_ministry_effectiveness_trends | Government Performance Monitor | ministry-schema.md | Corporate Affairs | Enterprise β¬15K/mo |
Business Documentation: BUSINESS_PRODUCT_DOCUMENT.md#product-line-2
Product Line 3: Risk Intelligence Feed (β¬1.77M annual revenue potential)
Revenue Source: BUSINESS_PRODUCT_DOCUMENT.md#product-line-3-risk-intelligence-feed - β¬1,770,000 total (β¬900K subscription fees + β¬500K alerting + β¬220K consulting + β¬150K services)
Target Segments: Political Consulting, Corporate Affairs, Media & Journalism
| View | Risk Intelligence Product | Intelligence Value | Market Segment | Premium Tier |
|---|---|---|---|---|
view_rule_violation | Risk Assessment Feed | βββββ | Political Consulting | β¬5,900/mo |
view_politician_risk_summary | Politician Risk Profiles | βββββ | Corporate Affairs | β¬5,900/mo |
view_riksdagen_voting_anomaly_detection | Voting Anomaly Alerts | βββββ | Political Parties | β¬5,900/mo |
view_risk_score_evolution | Risk Trend Analysis | βββββ | Political Consulting | β¬5,900/mo |
view_ministry_risk_evolution | Government Risk Monitor | ββββ | Corporate Affairs | β¬5,900/mo |
Business Documentation: BUSINESS_PRODUCT_DOCUMENT.md#product-line-3
Product Line 4: Custom Report Generator (β¬525K annual revenue potential)
Revenue Note: This is a simplified representation of report generation features that appear across multiple product lines in BUSINESS_PRODUCT_DOCUMENT.md. The β¬525K figure is estimated based on view-to-product mapping: (20 Professional subscriptions at β¬6K/mo Γ 12 = β¬1.44M total, with ~36% allocated to custom reporting = β¬525K). See BUSINESS_PRODUCT_DOCUMENT.md for complete product line breakdown.
Target Segments: All segments, customizable templates
| View | Report Template | Output Format | Market Segment | Feature Tier |
|---|---|---|---|---|
view_riksdagen_politician_experience_summary | Experience Analysis Report | PDF, Excel | Academic Research | Starter β¬2K/mo |
view_riksdagen_party_ballot_support_annual_summary | Coalition Analysis Report | PDF, PPT | Political Consulting | Professional β¬6K/mo |
view_committee_productivity_matrix | Committee Performance Report | Excel, PDF | NGOs & Advocacy | Professional β¬6K/mo |
view_riksdagen_politician_document_summary | Legislative Productivity Report | PDF, Excel | Media & Journalism | Starter β¬2K/mo |
Business Documentation: BUSINESS_PRODUCT_DOCUMENT.md#product-line-4
Cross-Product Feature Matrix
| Feature Category | Views Used (Count) | Product Lines | Annual Revenue | Customer Segments |
|---|---|---|---|---|
| Politician Intelligence | 8 core views | 1, 2, 3, 4 | β¬1.2M | All segments |
| Party & Coalition Analysis | 6 core views | 1, 2, 3, 4 | β¬800K | Political focus |
| Risk Assessment | 5 specialized views | 2, 3 | β¬1.8M | Consulting, Corporate |
| Government Performance | 4 ministry views | 2, 3, 4 | β¬400K | Corporate Affairs |
| Committee & Legislative | 12 committee views | 1, 2, 4 | β¬300K | Academic, NGO |
| Voting & Ballot Analysis | 20 vote views | 1, 2, 3 | β¬600K | All segments |
JSON Schema Integration Reference
All views are exported via JSON API with standardized schemas. See complete specifications:
- Politician Data: politician-schema.md - 8 core views
- Party Data: party-schema.md - 6 core views
- Intelligence Analytics: intelligence-schema.md - 5 risk views
- Committee Data: committee-schema.md - 12 committee views
- Ministry Data: ministry-schema.md - 4 government views
- Voting & Ballot Data: Vote view data exported via politician-schema.md#voting-section - 20 source views
API Documentation: json-export-specs/README.md
Example Responses: json-export-specs/examples/
Appendix D: Party Code Reference
| Code | Full Name (Swedish) | English Name | Ideology | Historic Seats Range |
|---|---|---|---|---|
| S | Socialdemokraterna | Social Democrats | Social democracy | 70-130 |
| M | Moderaterna | Moderate Party | Liberal conservatism | 60-110 |
| SD | Sverigedemokraterna | Sweden Democrats | National conservatism | 20-80 |
| C | Centerpartiet | Centre Party | Agrarian liberalism | 20-35 |
| V | VΓ€nsterpartiet | Left Party | Democratic socialism | 15-30 |
| KD | Kristdemokraterna | Christian Democrats | Christian democracy | 15-30 |
| L | Liberalerna | Liberals | Social liberalism | 15-30 |
| MP | MiljΓΆpartiet | Green Party | Green politics | 15-30 |
Appendix E: Database Maintenance Schedule
| Task | Frequency | Time (UTC) | Purpose |
|---|---|---|---|
| Materialized View Refresh | Daily | 02:00 | Update vote/document aggregations |
| Index Maintenance | Weekly | Sunday 03:00 | REINDEX for performance |
| Statistics Update | Daily | 02:30 | Update query planner statistics (ANALYZE) |
| Liquibase Migrations | On deployment | Varies | Schema evolution |
| Backup | Daily | 04:00 | Full database backup |
Appendix F: Future View Enhancements (v1.31-v1.32 Planning)
Planned for v1.31:
view_committee_productivity_enhanced: Committee efficiency metrics with trend analysisview_ministry_effectiveness_detailed: Ministry performance with budget correlationview_politician_network_centrality: Network analysis metrics (degree, betweenness, closeness)
Planned for v1.32 (Materialization Focus):
view_politician_behavioral_trends_mat: Materialized for sub-100ms dashboard queriesview_party_effectiveness_trends_mat: Materialized party performanceview_risk_score_evolution_mat: Materialized risk trackingview_coalition_alignment_matrix_mat: Daily-refreshed coalition analysis
Research/Future:
- Media Influence Tracking: Integration with news articles, social media mentions
- Disinformation Vulnerability: Behavioral patterns indicating susceptibility
- Crisis Resilience Indicators: Stability metrics under political stress
- International Comparison Views: Nordic/EU parliament benchmarking
Appendix G: Support & Contribution
Documentation Feedback:
- GitHub Issues: https://github.com/Hack23/cia/issues
- Pull Requests: https://github.com/Hack23/cia/pulls
Related Documentation:
- README.md - Project overview
- CONTRIBUTING.md - Contribution guidelines
- service.data.impl/README-SCHEMA-MAINTENANCE.md - Database maintenance
Contact:
- Project: Citizen Intelligence Agency (CIA)
- License: Apache 2.0
- Repository: https://github.com/Hack23/cia
Document Metadata
Version: 3.0
Date: 2026-04-05
Classification: Public Documentation
Status: Active - Comprehensive Documentation with Business Context
Last Updated: 2026-04-05
Last Validated Against Schema: 2026-04-05
Next Review: 2026-05-05 (monthly review recommended)
Authors: Citizen Intelligence Agency Intelligence Operations Team
Reviewers: Stack Specialist, Intelligence Operative
Change Log:
| Version | Date | Changes | Author |
|---|---|---|---|
| 1.0 | 2025-11-17 | Initial comprehensive catalog creation | Intelligence Operative |
| 1.1 | 2025-11-20 | Validation & Corrections - Validated against full_schema.sql; Added Complete View Inventory section listing all 82 views; Updated Executive Summary with accurate statistics (9 detailed, 73 basic coverage); Added validation metadata; Identified 73 undocumented views requiring detailed documentation | Intelligence Operative |
| 2.0 | 2025-11-21 | Complete Documentation Achievement - Added comprehensive structured documentation for all 73 remaining views; Documented all politician views (ballot summary, influence metrics, risk summary, document summaries); Documented all intelligence views (dashboard, crisis resilience, voting anomaly detection); Completed ministry/government views (effectiveness trends, productivity matrix, risk evolution, government structure); Documented all party views (performance metrics, momentum analysis, document summaries, coalition patterns); Completed vote data views (20 ballot/party/politician summaries at daily/weekly/monthly/annual granularities); Documented all committee views (productivity, decisions, roles, membership); Completed document views and application/audit views; Added WorldBank data view documentation; Achievement: 100% documentation coverage (85/85 views documented; later corrected to 84 in v2.1 after schema reverification) | Intelligence Operative (Copilot Agent) |
| 2.1 | 2025-11-25 | Business Context Integration & Statistical Corrections (v1.36) - β Reverified view counts: corrected from 85 to 84 total views (56 regular + 28 materialized); β Updated "Last Validated" date from 2025-11-22 to 2025-11-25; β Added business value context to key views (view_riksdagen_politician, view_riksdagen_party) with TAM metrics, product integration links, and customer segments; β Added comprehensive Appendix C: View-to-Product Mapping linking 22+ key views to commercial products across 4 product lines (β¬5.1M annual revenue potential); β Integrated JSON export specification cross-references for API endpoints; β Added links to BUSINESS_PRODUCT_DOCUMENT.md throughout catalog; β Enhanced Related Documentation section with Business Product Document and JSON Export Specs | Intelligence Operative (Copilot Agent) |
| 2.2 | 2025-12-10 | Validation Report Consolidation - β Added comprehensive "Validation History" section consolidating DATABASE_VIEW_VALIDATION_REPORT.md content; β Documented validation methodology with executable commands; β Added validation schedule and procedures; β Included historical validation timeline showing coverage progression (10.98% β 100%); β Added health metrics and validation tools reference; β Removed DATABASE_VIEW_VALIDATION_REPORT.md reference (content now integrated); β Part of validation documentation consolidation effort (single source of truth) | Intelligence Operative (Copilot Agent) |
| 3.0 | 2026-04-05 | Full Audit & Count Reconciliation (v1.80) - β Corrected total view count from 96 to 110 (77 regular + 33 materialized) after comprehensive audit against full_schema.sql; β Added 5 new-style mv_* materialized views (v1.76) to inventory; β Added 4 politician career/trajectory views to Politician Views category; β Created new Election Cycle Views (6) and Seasonal/Election Year Views (7) categories; β Updated all category counts and summary statistics; β Cross-referenced all views against Liquibase changelogs and full_schema.sql ground truth; β Resolved issue #1181 view count discrepancy | Code Quality Engineer (Copilot Agent) |
Validation & Corrections Log
2025-11-20: Schema Validation
Validation Performed: Comprehensive comparison of documented views against actual database schema in service.data.impl/src/main/resources/full_schema.sql
Key Findings:
- β Total views in database: 80 (confirmed)
- β Views documented but not in DB: 0 (no orphaned documentation)
- β Views in DB but not fully documented: 71 (critical documentation gap)
- β Documentation coverage: 11.25% (9 of 80 views fully documented)
Corrections Applied:
- Executive Summary Updated: Changed "80+ database views" claim to accurate "80 database views" with transparent coverage statistics
- Complete View Inventory Added: New comprehensive section listing all 80 views with basic descriptions, types (standard/materialized), and intelligence value ratings
- Validation Metadata Added: Added "Last Validated Against Schema" date to document metadata
- Validation History Section: Comprehensive validation documentation now in dedicated section (see Validation History)
- Related Documentation Updated: Consolidated validation report content into main documentation
Views Confirmed Present and Documented (9):
- view_party_effectiveness_trends β
- view_politician_behavioral_trends β
- view_riksdagen_coalition_alignment_matrix β
- view_riksdagen_party β
- view_riksdagen_politician β
- view_riksdagen_politician_document β
- view_riksdagen_politician_experience_summary β
- view_riksdagen_vote_data_ballot_politician_summary_daily β
- view_risk_score_evolution β
Views Identified for Documentation (71):
- Priority 1 (Critical Intelligence): 13 views (crisis resilience, voting anomaly, intelligence dashboard, risk summary, influence metrics, ministry views, party momentum)
- Priority 2 (Vote & Party Analysis): 28 views (all ballot summaries, party document/coalition views)
- Priority 3 (Committee & Government): 15 views (committee productivity, decisions, government proposals)
- Priority 4 (Supporting): 15 views (application tracking, audit, worldbank)
See Validation History section for complete validation methodology and historical progression.
Impact: Documentation now accurately reflects database schema state and provides transparency about coverage gaps. Users can reference the Complete View Inventory for all available views while detailed documentation is expanded.
2025-11-21: Complete Documentation Achievement
Documentation Completed: Comprehensive structured documentation added for all 73 remaining database views, achieving 100% documentation coverage.
Key Achievements:
- β Total views documented: 82 of 82 (100% coverage)
- β Detailed documentation (π): 9 views with comprehensive examples
- β Structured documentation (π): 73 views with purpose, key metrics, sample queries, applications
- β
All view categories fully documented:
- Politician Views: 8 views (including ballot summary, influence metrics, risk summary)
- Party Views: 12 views (including performance metrics, momentum analysis, coalition patterns)
- Committee Views: 12 views (productivity, decisions, roles, membership)
- Ministry/Government Views: 8 views (effectiveness trends, productivity matrix, risk evolution, decision impact)
- Intelligence Views: 6 views (dashboard, crisis resilience, voting anomaly detection)
- Vote Data Views: 20 views (ballot/party/politician summaries - daily/weekly/monthly/annual)
- Document Views: 7 views (politician and party document productivity)
- Application/Audit Views: 14 views (user behavior analytics, audit trails)
- WorldBank Views: 1 view (economic indicators)
Documentation Methodology:
- High-Priority Views (Intelligence, Ministry, Risk): Detailed documentation with complex use cases
- Core Analytical Views (Party, Politician, Committee): Structured documentation with sample queries
- Supporting Views (Vote Summaries, Documents, Audit): Concise structured documentation
- Consistent Format: Purpose, key metrics/columns, sample SQL queries, intelligence applications
Quality Standards Met:
- β Purpose statement for each view
- β Key metrics or column descriptions
- β Executable SQL sample queries
- β Intelligence applications and use cases
- β View type classification (standard/materialized)
- β Intelligence value rating (β-βββββ)
Impact:
- Usability: Analysts and developers can now discover and effectively use all 110 database views
- Onboarding: New team members have comprehensive view reference documentation
- Query Efficiency: Sample queries provide starting points for common analytical tasks
- Intelligence Operations: Clear guidance on which views support which analysis types
- Documentation Debt Eliminated: No remaining undocumented views
Next Steps:
- Periodic validation against schema changes (monthly recommended)
- Performance benchmark validation for sample queries
- User feedback collection for documentation improvements
- Potential materialization of additional high-usage views (v1.32 planning)
2025-11-25: Business Context Integration & Statistical Corrections (v1.36)
Validation Performed: Reverification of view counts and integration of business product documentation.
Key Statistical Corrections:
- β Total Views: Corrected from 85 to 84 (accurate count against full_schema.sql)
- β Regular Views: Corrected from 57 to 56 (validated via grep)
- β Materialized Views: Confirmed 28 (unchanged, accurate)
- β Documentation Coverage: Updated from 85 to 84 views (100% coverage maintained)
- β Last Validated Date: Updated from 2025-11-22 to 2025-11-25
Business Context Enhancements Applied:
-
View Documentation Enhanced: Added business context sections to high-value views including:
view_riksdagen_politician: β¬15M TAM (Political Consulting), JSON spec integrationview_riksdagen_party: β¬8M TAM (Media & Journalism), product feature mapping- Market segment identification for each key view
- API endpoint mappings and JSON schema references
- Revenue tier and customer segment classification
-
New Appendix C Created: Comprehensive View-to-Product Mapping
- Product Line 1: Political Intelligence API - 7 core views mapped
- Product Line 2: Advanced Analytics Suite - 6 dashboard components
- Product Line 3: Risk Intelligence Feed - 5 risk assessment views
- Product Line 4: Custom Report Generator - 4 report templates
- Cross-Product Feature Matrix: 6 feature categories with β¬5.1M annual revenue potential (Politician Intelligence β¬1.2M, Party & Coalition β¬800K, Risk Assessment β¬1.8M, Government Performance β¬400K, Committee & Legislative β¬300K, Voting & Ballot β¬600K)
- JSON Schema Integration Reference with 5 schema categories
-
Related Documentation Updated:
- Added BUSINESS_PRODUCT_DOCUMENT.md to Related Documentation table
- Added json-export-specs/ link to Related Documentation
- Cross-referenced business documentation throughout catalog
-
Appendix Reorganization:
- Renamed Appendix C β Appendix D (Party Code Reference)
- Renamed Appendix D β Appendix E (Database Maintenance Schedule)
- Renamed Appendix E β Appendix F (Future View Enhancements)
- Renamed Appendix F β Appendix G (Support & Contribution)
- Inserted new Appendix C (View-to-Product Mapping)
Impact:
- Business Alignment: Complete traceability from database views to commercial products
- Revenue Context: β¬5.1M annual revenue potential mapped across 6 feature categories
- Market Transparency: Customer segments (β¬46M TAM across 5 segments) linked to specific views
- API Integration: JSON export specs cross-referenced for all product features
- Strategic Planning: View-to-revenue mapping enables data-driven prioritization
Quality Validation:
- β All view counts verified against service.data.impl/src/main/resources/full_schema.sql
- β TAM figures sourced from BUSINESS_PRODUCT_DOCUMENT.md (β¬46M across 5 segments)
- β Product Line 1-3 revenue figures sourced from BUSINESS_PRODUCT_DOCUMENT.md (β¬630K, β¬855K, β¬1.77M)
- β Product Line 4 revenue estimated based on view mapping and cross-product allocation (β¬525K)
- β Cross-Product Feature Matrix totals (β¬5.1M) represent primary revenue model
- β JSON schema links validated against json-export-specs/schemas/ directory
- β Product line mappings cross-referenced with product documentation
Next Actions:
- Monitor business metrics against actual usage patterns
- Update product mappings as new features launch
- Maintain alignment between view documentation and business strategy
- Quarterly review of TAM estimates and revenue projections
Election Year Behavioral Pattern Analysis Views (v1.60)
view_riksdagen_election_year_behavioral_patterns ββββ
Category: Temporal Pattern Analysis Views (v1.60)
Type: Complex Aggregation View
Intelligence Value: HIGH - Election Year Pattern Detection
Changelog: v1.60 Election Year Behavioral Pattern Analysis
mv_annual_document_metrics ββββ
Category: Performance Optimization (v1.70)
Type: Materialized View
Intelligence Value: HIGH - Annual Document Aggregation
Purpose
Pre-aggregated annual document metrics materialized view created to optimize election year analysis queries. Eliminates cartesian products by aggregating document_data by year BEFORE joining with voting metrics. Refreshes daily at 2:00 AM via CONCURRENTLY to avoid blocking queries.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
year | INTEGER | Calendar year extracted from made_public_date | 2022 |
documents_produced | BIGINT | Total unique documents published in year | 5,678 |
motions_filed | BIGINT | Total motions filed in year | 2,345 |
proposals_submitted | BIGINT | Total proposals submitted in year | 567 |
first_document_date | DATE | Earliest document publication date | '2022-01-01' |
last_document_date | DATE | Latest document publication date | '2022-12-31' |
Performance Characteristics
- Refresh Time: <10 seconds for 24 rows (2002-2026)
- Data Volume: 24 rows (one per year)
- Refresh Method: CONCURRENTLY (non-blocking)
- Refresh Schedule: Daily at 2:00 AM UTC
- Index: Unique index on
yearcolumn (required for CONCURRENT refresh)
Dependencies
Source Tables:
document_data- Document records with made_public_date, doc_type
Framework Integration:
- Framework 1 (Temporal Analysis): Year-over-year document trends
- Framework 7 (Performance Optimization): Query optimization via pre-aggregation
Use Cases
- Election Year Analysis: Powers view_riksdagen_election_year_behavioral_patterns
- Performance Optimization: Reduces 109K document_data rows to 24 aggregate rows
- Cartesian Product Prevention: Eliminates 3.5M Γ 109K joins (billions of intermediate rows)
- Query Acceleration: 99.99% reduction in temp file usage (>50GB β <1MB)
Refresh Procedure
-- Manual refresh (if needed outside schedule)
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_annual_document_metrics;
-- Check last refresh time
SELECT schemaname, matviewname, last_refresh
FROM pg_matviews
WHERE matviewname = 'mv_annual_document_metrics';
mv_annual_voting_metrics ββββ
Category: Performance Optimization (v1.70)
Type: Materialized View
Intelligence Value: HIGH - Annual Voting Aggregation
Purpose
Pre-aggregated annual voting metrics materialized view created to optimize election year analysis queries. Eliminates cartesian products by aggregating vote_data by year BEFORE joining with document metrics. Refreshes daily at 2:00 AM via CONCURRENTLY to avoid blocking queries.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
year | INTEGER | Calendar year extracted from vote_date | 2022 |
total_ballots | BIGINT | Total unique ballots voted on in year | 1,250 |
total_votes | BIGINT | Total individual votes cast in year | 435,750 |
avg_attendance_rate | NUMERIC | Average attendance percentage | 87.50 |
active_politicians | BIGINT | Unique politicians who voted in year | 349 |
first_vote_date | DATE | Earliest vote date in year | '2022-01-01' |
last_vote_date | DATE | Latest vote date in year | '2022-12-31' |
Performance Characteristics
- Refresh Time: <10 seconds for 24 rows (2002-2026)
- Data Volume: 24 rows (one per year)
- Refresh Method: CONCURRENTLY (non-blocking)
- Refresh Schedule: Daily at 2:00 AM UTC
- Index: Unique index on
yearcolumn (required for CONCURRENT refresh)
Dependencies
Source Tables:
vote_data- Voting records with vote_date, ballot_id, intressent_id
Framework Integration:
- Framework 1 (Temporal Analysis): Year-over-year voting trends
- Framework 7 (Performance Optimization): Query optimization via pre-aggregation
Use Cases
- Election Year Analysis: Powers view_riksdagen_election_year_behavioral_patterns
- Performance Optimization: Reduces 3.5M vote_data rows to 24 aggregate rows
- Cartesian Product Prevention: Eliminates 3.5M Γ 109K joins (billions of intermediate rows)
- Query Acceleration: 99.99% reduction in temp file usage (>50GB β <1MB)
Refresh Procedure
-- Manual refresh (if needed outside schedule)
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_annual_voting_metrics;
-- Check last refresh time
SELECT schemaname, matviewname, last_refresh
FROM pg_matviews
WHERE matviewname = 'mv_annual_voting_metrics';
mv_decision_temporal_trends ββββ
Category: Performance Optimization (v1.76)
Type: Materialized View
Intelligence Value: HIGH - Decision Temporal Pre-aggregation
Purpose
Pre-aggregated daily decision temporal trends materialized view created to optimize the view_election_cycle_decision_intelligence query. Materializes the view_decision_temporal_trends base view which computes daily decision counts, approval/rejection rates, moving averages (7/30/90-day), year-over-year changes, and parliamentary period classification. Eliminates repeated expensive scans of document_proposal_data and document_data joins.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
decision_day | DATE | Calendar date of decisions | '2024-03-15' |
daily_decisions | BIGINT | Total decisions on this day | 42 |
daily_approval_rate | NUMERIC | Approval percentage for the day | 78.50 |
approved_decisions | BIGINT | Approved decisions count | 33 |
rejected_decisions | BIGINT | Rejected decisions count | 7 |
referred_back_decisions | BIGINT | Referred back to committee | 2 |
ma_7day_decisions | NUMERIC | 7-day moving average of decisions | 38.71 |
ma_30day_decisions | NUMERIC | 30-day moving average of decisions | 35.20 |
ma_90day_decisions | NUMERIC | 90-day moving average of decisions | 32.15 |
ma_30day_approval_rate | NUMERIC | 30-day moving avg approval rate | 75.30 |
yoy_decisions_change | BIGINT | Year-over-year decision count delta | +5 |
yoy_decisions_change_pct | NUMERIC | Year-over-year percentage change | 13.51 |
parliamentary_period | TEXT | Session classification | 'Autumn Session' |
decision_quarter | TEXT | Quarter label | 'Q1 2024' |
Performance Characteristics
- Source View:
view_decision_temporal_trends - Data Volume: ~6,000 rows (one per decision day over 25 years)
- Refresh Method: CONCURRENTLY (non-blocking)
- Index: Unique index on
decision_daycolumn
Dependencies
Source Tables (via view_decision_temporal_trends):
document_proposal_data- Proposal chamber decisionsdocument_proposal_container- Proposal containersdocument_status_container- Document status linkagedocument_data- Document dates and metadata
Consumed By:
view_election_cycle_decision_intelligence- Election cycle decision analysis
Refresh Procedure
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_decision_temporal_trends;
mv_ministry_decision_impact ββββ
Category: Performance Optimization (v1.76)
Type: Materialized View
Intelligence Value: HIGH - Ministry Decision Pre-aggregation
Purpose
Pre-aggregated ministry-level decision impact materialized view created to optimize the view_election_cycle_decision_intelligence query. Materializes the view_ministry_decision_impact base view which computes proposal outcomes (approved, rejected, referred back, committee referral) grouped by ministry, committee, decision type, and quarter. Provides approval and rejection rates per ministry-committee combination.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
ministry_code | TEXT | Government ministry identifier | 'Fi' |
committee | TEXT | Parliamentary committee | 'FiU' |
decision_type | TEXT | Type of decision | 'prop' |
decision_quarter | TIMESTAMP | Quarter start date | '2024-01-01' |
decision_year | NUMERIC | Calendar year | 2024 |
quarter_num | NUMERIC | Quarter number (1-4) | 1 |
total_proposals | BIGINT | Total proposals in group | 15 |
approved_proposals | BIGINT | Approved proposal count | 12 |
rejected_proposals | BIGINT | Rejected proposal count | 2 |
referred_back_proposals | BIGINT | Referred back count | 1 |
approval_rate | NUMERIC | Approval percentage | 80.00 |
rejection_rate | NUMERIC | Rejection percentage | 13.33 |
committee_referral_rate | NUMERIC | Committee referral percentage | 0.00 |
Performance Characteristics
- Source View: `view_ministry_decision_impact$
- \text{Data} \text{Volume}: ~2{,}000 \text{rows} (\text{ministry} \times \text{committee} \times \text{quarter} \text{combinations})
- \text{Refresh} \text{Method}: \text{CONCURRENTLY} (\text{non}-\text{blocking})
- \text{Index}: \text{Unique} \text{index} \text{on} $ministry_code, committee, decision_type, decision_quarter`
Dependencies
Source Tables (via view_ministry_decision_impact):
document_data- Government proposals (document_type = 'prop')document_status_container- Document status linkagedocument_proposal_container- Proposal containersdocument_proposal_data- Committee decisions and chamber outcomes
Consumed By:
view_election_cycle_decision_intelligence- Election cycle decision analysis
Refresh Procedure
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_ministry_decision_impact;
mv_party_decision_flow ββββ
Category: Performance Optimization (v1.76)
Type: Materialized View
Intelligence Value: HIGH - Party Decision Flow Pre-aggregation
Purpose
Pre-aggregated party-level decision flow materialized view created to optimize the view_election_cycle_decision_intelligence query. Materializes the view_riksdagen_party_decision_flow base view which computes proposal outcomes grouped by party, committee, decision type, and month. Tracks which parties drive proposals through which committees and their success rates.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
party | TEXT | Political party short code | 'S' |
committee | TEXT | Parliamentary committee | 'FiU' |
decision_type | TEXT | Type of decision | 'mot' |
committee_org | TEXT | Originating organization | 'Fi' |
decision_month | TIMESTAMP | Month start date | '2024-03-01' |
decision_year | NUMERIC | Calendar year | 2024 |
decision_month_num | NUMERIC | Month number (1-12) | 3 |
total_proposals | BIGINT | Total proposals in group | 8 |
approved_proposals | BIGINT | Approved proposal count | 5 |
rejected_proposals | BIGINT | Rejected proposal count | 2 |
referred_back_proposals | BIGINT | Referred back count | 1 |
approval_rate | NUMERIC | Approval percentage | 62.50 |
rejection_rate | NUMERIC | Rejection percentage | 25.00 |
Performance Characteristics
- Source View: `view_riksdagen_party_decision_flow$
- \text{Data} \text{Volume}: ~5{,}000 \text{rows} (\text{party} \times \text{committee} \times \text{month} \text{combinations})
- \text{Refresh} \text{Method}: \text{CONCURRENTLY} (\text{non}-\text{blocking})
- \text{Index}: \text{Unique} \text{index} \text{on} $party, committee, decision_type, decision_month`
Dependencies
Source Tables (via view_riksdagen_party_decision_flow):
document_proposal_data- Proposal decisionsdocument_proposal_container- Proposal containersdocument_status_container- Document status linkagedocument_data- Document datesdocument_person_reference_co_0- Person referencesdocument_person_reference_da_0- Party short codes
Consumed By:
view_election_cycle_decision_intelligence- Election cycle decision analysis
Refresh Procedure
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_party_decision_flow;
Purpose
Systematic analysis of election year behavioral patterns across 7 Swedish election cycles (2002-2026) compared to midterm years. Enables detection of election-driven behavioral shifts through statistical baseline calculations and z-score analysis. Provides annual aggregation with 37 metrics including ballots, documents, motions, proposals, and attendance rates.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
year | INTEGER | Calendar year | 2022 |
is_election_year | BOOLEAN | Election year flag | true |
total_ballots | BIGINT | Total ballots cast | 1,234 |
active_politicians | BIGINT | Active politicians | 349 |
attendance_rate | NUMERIC | Attendance percentage | 87.50 |
documents_produced | BIGINT | Total documents | 5,678 |
motions_filed | BIGINT | Motions filed | 2,345 |
proposals_filed | BIGINT | Proposals filed | 567 |
election_median_ballots | NUMERIC | Election year median | 1,200.00 |
election_avg_ballots | NUMERIC | Election year average | 1,250.00 |
midterm_avg_ballots | NUMERIC | Midterm year average | 1,100.00 |
ballot_ratio_vs_midterm | NUMERIC | Election/midterm ratio | 1.12 |
ballot_z_score_vs_election_avg | NUMERIC | Z-score vs election avg | 0.85 |
year_classification | TEXT | Activity classification | 'NORMAL_ELECTION_ACTIVITY' |
Statistical Methodology
Baseline Calculations:
- Election year baseline: Median via PERCENTILE_CONT(0.5) across 7 election years
- Midterm baseline: Average across 17 midterm years
- Standard deviation: For z-score calculations
Z-Score Formula:
z_score = (actual_value - election_avg) / election_stddev
Year Classifications:
- `HIGH_ELECTION_ACTIVITY$: \text{Documents} > \text{election_avg} + 2 \times \text{stddev}
- $NORMAL_ELECTION_ACTIVITY`: Within Β±2 stddev of election_avg
- `LOW_ELECTION_ACTIVITY$: \text{Documents} < \text{election_avg} - 2 \times \text{stddev}
- $MIDTERM_YEAR`: Non-election year
Example Queries
Query 1: Compare 2022 election year vs 2021 midterm year
SELECT
year,
is_election_year,
total_ballots,
documents_produced,
ballot_ratio_vs_midterm,
year_classification
FROM view_riksdagen_election_year_behavioral_patterns
WHERE year IN (2021, 2022)
ORDER BY year;
Query 2: Identify high-activity election years
SELECT
year,
ballot_z_score_vs_election_avg,
doc_z_score_vs_election_avg,
year_classification,
yoy_ballot_change_pct
FROM view_riksdagen_election_year_behavioral_patterns
WHERE is_election_year = true
AND year_classification = 'HIGH_ELECTION_ACTIVITY'
ORDER BY ballot_z_score_vs_election_avg DESC;
Query 3: Track document productivity trends across election cycles
SELECT
year,
documents_produced,
election_avg_docs,
midterm_avg_docs,
doc_ratio_vs_midterm,
CASE
WHEN is_election_year THEN 'Election Year'
ELSE 'Midterm Year'
END AS year_type
FROM view_riksdagen_election_year_behavioral_patterns
WHERE year BETWEEN 2014 AND 2022
ORDER BY year;
Performance Characteristics
- Query Time: < 500ms (empty database), < 2s (with full data)
- Index Usage: idx_vote_data_date, idx_doc_data_made_public_date
- Data Volume: 24 rows (one per year 2002-2026)
- Aggregation: Annual metrics with statistical calculations
- Refresh: Static view, updates with new data inserts
Dependencies
Source Tables:
vote_data- Voting records with ballot_datedocument_data- Document records with made_public_date
Framework Integration:
- Framework 1 (Temporal Analysis): Year-over-year trends
- Framework 3 (Pattern Recognition): Anomaly detection
- Framework 6 (Decision Intelligence): Operational warnings
Use Cases
- Election Forecasting: Predict behavioral patterns based on historical election years
- Anomaly Detection: Identify unusual activity levels in election years
- Comparative Analysis: Contrast election year vs midterm year behavior
- Trend Analysis: Track 24-year evolution of parliamentary activity
- Academic Research: Analyze election-driven behavioral shifts
Purpose
Three-row aggregate summary comparing election years (7 years) vs midterm years (17 years) with comprehensive statistical measures. Provides direct comparison ratios, min/max values, standard deviations, and year arrays for reference. Enables quick assessment of election year vs midterm year differences.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
period_type | TEXT | Period classification | 'ELECTION_YEARS' |
avg_ballots | NUMERIC | Average ballots | 1,250.50 |
avg_documents | NUMERIC | Average documents | 5,678.00 |
avg_motions | NUMERIC | Average motions | 2,345.00 |
avg_proposals | NUMERIC | Average proposals | 567.00 |
avg_attendance | NUMERIC | Average attendance rate | 87.50 |
avg_active_politicians | NUMERIC | Avg active politicians | 349.00 |
year_count | BIGINT | Number of years | 7 |
years | TEXT | Year array (as string) | '{2002,2006,2010,2014,2018,2022,2026}' |
min_ballots | NUMERIC | Minimum ballots | 1,100.00 |
max_ballots | NUMERIC | Maximum ballots | 1,400.00 |
stddev_ballots | NUMERIC | Standard deviation | 95.50 |
Row Structure
The view returns exactly 3 rows:
- ELECTION_YEARS: Aggregate statistics for 7 election years (2002, 2006, 2010, 2014, 2018, 2022, 2026)
- MIDTERM_YEARS: Aggregate statistics for 17 midterm years (all other years 2002-2026)
- COMPARISON_RATIO: Direct election/midterm ratios for all metrics
Example Queries
Query 1: Compare election vs midterm baseline
SELECT
period_type,
ROUND(avg_ballots, 2) AS avg_ballots,
ROUND(avg_documents, 2) AS avg_documents,
ROUND(avg_motions, 2) AS avg_motions,
year_count
FROM view_riksdagen_election_year_vs_midterm
WHERE period_type IN ('ELECTION_YEARS', 'MIDTERM_YEARS')
ORDER BY period_type;
Query 2: Calculate election year activity boost
SELECT
avg_ballots AS election_vs_midterm_ballot_ratio,
avg_documents AS election_vs_midterm_doc_ratio,
avg_motions AS election_vs_midterm_motion_ratio,
CASE
WHEN avg_ballots > 1.1 THEN 'Significant Increase (>10%)'
WHEN avg_ballots > 1.0 THEN 'Moderate Increase'
WHEN avg_ballots < 0.9 THEN 'Decrease'
ELSE 'Stable'
END AS activity_assessment
FROM view_riksdagen_election_year_vs_midterm
WHERE period_type = 'COMPARISON_RATIO';
Query 3: Analyze election year variability
SELECT
period_type,
ROUND(stddev_ballots, 2) AS ballot_variability,
ROUND(stddev_documents, 2) AS document_variability,
ROUND((max_ballots - min_ballots), 2) AS ballot_range
FROM view_riksdagen_election_year_vs_midterm
WHERE period_type = 'ELECTION_YEARS';
Performance Characteristics
- Query Time: < 100ms (empty database), < 500ms (with full data)
- Data Volume: 3 rows (fixed)
- Aggregation: Aggregate of view_riksdagen_election_year_behavioral_patterns
- Refresh: Static view, updates with source view
Dependencies
Source Views:
view_riksdagen_election_year_behavioral_patterns- Annual behavioral patterns
Framework Integration:
- Framework 1 (Temporal Analysis): Period comparison
- Framework 3 (Pattern Recognition): Baseline establishment
Use Cases
- Quick Reference: Single-query comparison of election vs midterm years
- Baseline Establishment: Reference values for anomaly detection
- Reporting: Executive summary statistics for presentations
- API Integration: Simplified endpoint for dashboards
Purpose
Identifies statistically unusual patterns in election years using z-score thresholds (|z| > 1.5). Multi-dimensional anomaly detection across ballots, documents, and motions with severity classification (CRITICAL, HIGH, MODERATE) and directional indicators (ELEVATED, REDUCED, MIXED). Provides early warning of abnormal election year behavior.
Key Columns
| Column | Type | Description | Example |
|---|---|---|---|
year | INTEGER | Election year | 2022 |
total_ballots | BIGINT | Total ballots cast | 1,400 |
documents_produced | BIGINT | Documents produced | 6,500 |
motions_filed | BIGINT | Motions filed | 2,800 |
ballot_z_score_vs_election_avg | NUMERIC | Ballot z-score | 2.35 |
doc_z_score_vs_election_avg | NUMERIC | Document z-score | 1.85 |
motion_z_score | NUMERIC | Motion z-score | 1.65 |
has_ballot_anomaly | BOOLEAN | Ballot anomaly flag | true |
has_doc_anomaly | BOOLEAN | Document anomaly flag | true |
anomaly_count | INTEGER | Total anomalies | 2 |
anomaly_types | TEXT | Anomaly dimensions | 'BALLOT,DOCUMENT' |
anomaly_severity | TEXT | Severity level | 'HIGH' |
max_z_score | NUMERIC | Maximum z-score | 2.35 |
anomaly_direction | TEXT | Activity direction | 'ELEVATED_ACTIVITY' |
year_classification | TEXT | Activity classification | 'HIGH_ELECTION_ACTIVITY' |
Anomaly Detection Methodology
Z-Score Threshold: |z| > 1.5 (1.5 standard deviations from election year mean)
Severity Classification:
CRITICAL: max |z| > 2.5 (extreme outlier)HIGH: max |z| > 2.0 (significant anomaly)MODERATE: max |z| > 1.5 (notable deviation)NORMAL: |z| β€ 1.5 (within normal range)
Direction Classification:
ELEVATED_ACTIVITY: Majority of z-scores > 1.5 (increased activity)REDUCED_ACTIVITY: Majority of z-scores < -1.5 (decreased activity)MIXED_PATTERN: Mix of positive and negative z-scoresNORMAL: No anomalies detected
Example Queries
Query 1: Identify critical anomalies
SELECT
year,
anomaly_types,
anomaly_severity,
max_z_score,
anomaly_direction,
total_ballots,
documents_produced
FROM view_riksdagen_election_year_anomalies
WHERE anomaly_severity IN ('CRITICAL', 'HIGH')
ORDER BY max_z_score DESC;
Query 2: Track election year anomaly history
SELECT
year,
anomaly_count,
ballot_z_score_vs_election_avg,
doc_z_score_vs_election_avg,
motion_z_score,
anomaly_direction
FROM view_riksdagen_election_year_anomalies
WHERE anomaly_count > 0
ORDER BY year;
Query 3: Compare anomalous vs normal election years
SELECT
CASE
WHEN anomaly_severity IN ('CRITICAL', 'HIGH') THEN 'Anomalous'
ELSE 'Normal'
END AS election_type,
COUNT(*) AS year_count,
ROUND(AVG(total_ballots), 2) AS avg_ballots,
ROUND(AVG(documents_produced), 2) AS avg_documents
FROM view_riksdagen_election_year_anomalies
GROUP BY election_type
ORDER BY election_type;
Performance Characteristics
- Query Time: < 200ms (empty database), < 1s (with full data)
- Data Volume: 0-7 rows (election years with |z| > 1.5 only)
- Filtering: Pre-filtered to election years with anomalies
- Index Usage: Same as behavioral patterns view
- Refresh: Static view, updates with source data
Dependencies
Source Views:
view_riksdagen_election_year_behavioral_patterns- Annual behavioral patterns
Framework Integration:
- Framework 3 (Pattern Recognition): Anomaly detection algorithms
- Framework 6 (Decision Intelligence): Severity-based alerts
Use Cases
- Early Warning System: Detect unusual election year patterns
- Risk Assessment: Identify elections requiring investigation
- Predictive Analytics: Forecast potential anomalies based on z-score trends
- Quality Assurance: Validate data quality in election years
- Academic Research: Study factors driving election year anomalies
Interpretation Guide
Z-Score Interpretation:
|z| < 1.0: Within 1 standard deviation (68% of data)1.0 < |z| < 2.0: Notable deviation (95% confidence)|z| > 2.0: Significant outlier (99% confidence)|z| > 3.0: Extreme outlier (99.7% confidence)
Example Anomaly Scenarios:
- 2022 HIGH BALLOT: Z-score = 2.35 β 35% more ballots than typical election year
- 2014 REDUCED DOCS: Z-score = -1.85 β 15% fewer documents than typical election year
- 2018 MIXED: Z-score ballots +1.6, documents -1.7 β Contradictory patterns
π Working with Sample Data
All views documented in this catalog have corresponding sample data files for testing, development, and documentation validation.
Sample Data Location
Sample CSV files are located in: service.data.impl/sample-data/
| File Pattern | Count | Description |
|---|---|---|
view_*_sample.csv | 84 | View sample data - All 84 documented views |
table_*_sample.csv | 54 | Table sample data |
distribution_*.csv | 43 | Statistical distributions |
distinct_*_values.csv | 9 | Distinct value sets |
| Metadata files (*.csv) | 11 | Manifests, statistics, mappings |
| Total | 200 | Complete sample data coverage |
Important Data Value Notes
When working with sample data, be aware of these Swedish language values:
Gender Values:
'KVINNA'- Woman'MAN'- Man
Status Values:
'TjΓ€nstgΓΆrande riksdagsledamot'- Active member of parliament'TjΓ€nstgΓΆrande ersΓ€ttare'- Active substitute'Tidigare riksdagsledamot'- Former member of parliament'TillgΓ€nglig ersΓ€ttare'- Available substitute'Inga uppdrag'- No assignments
Views Without Sample Data
Some documented views do not have sample CSV files:
| View Name | Reason | Status |
|---|---|---|
view_riksdagen_coalition_alignment_matrix | Empty or very large - no rows returned | Schema exists, no sample CSV |
view_riksdagen_voting_anomaly_detection | Empty due to status value mismatch | Schema exists, no sample CSV |
view_riksdagen_intelligence_dashboard | Single-row dashboard (v1.62 recreated) | Schema exists, no sample CSV needed |
Note: 81 of 84 documented views have sample CSV files. The 3 views without samples either return 0 rows with current filter criteria or are single-row dashboards that don't need sample data.
See sample-data/README.md for data quality issues and extraction details.
Sample Data Documentation
- Usage Guide: sample-data/README.md
- Extraction Statistics: extraction_statistics.csv
- Data Manifest: sample_data_manifest.csv
Example: Using Sample Data
# View sample data for politician view
head -5 service.data.impl/sample-data/view_riksdagen_politician_sample.csv
# Count rows in sample
wc -l service.data.impl/sample-data/view_riksdagen_politician_sample.csv
# Check distinct values
cut -d',' -f6 service.data.impl/sample-data/view_riksdagen_politician_sample.csv | sort | uniq -c
All example queries in this catalog have been verified against current sample data as of 2026-01-01.
V1.55 Seasonal Analysis Views
view_riksdagen_seasonal_quarterly_activity
ββββ High Intelligence Value
π Purpose: Quarterly pattern analysis (Q1-Q4) across election cycles (2002-2026) with z-score anomaly detection and seasonal clustering.
π Key Columns:
| Column | Type | Description | Example |
|---|---|---|---|
year | integer | Calendar year | 2022 |
quarter | integer | Quarter (1-4) | 4 |
is_election_year | boolean | Election year flag | true |
total_ballots | bigint | Ballot count | 450 |
total_documents | bigint | Document count | 1200 |
attendance_rate | numeric | Average attendance % | 92.5 |
ballot_z_score | numeric | Z-score vs baseline | 1.8 |
π‘ Example Queries:
-- Q4 activity in election years
SELECT year, quarter, total_ballots, ballot_z_score
FROM view_riksdagen_seasonal_quarterly_activity
WHERE quarter = 4 AND is_election_year = true
ORDER BY year DESC;
-- Anomalous quarters (|z| > 2)
SELECT year, quarter, total_ballots, ballot_z_score
FROM view_riksdagen_seasonal_quarterly_activity
WHERE ABS(ballot_z_score) > 2.0
ORDER BY ABS(ballot_z_score) DESC;
β‘ Performance: Aggregates quarterly, minimal overhead. Indexed on year/quarter.
π Dependencies: vote_data, document_data
π― Framework Integration: Framework 3 (Pattern Recognition) - Seasonal clustering
π― Use Cases: Seasonal trend analysis, Q4 pre-election surge detection, baseline establishment
view_riksdagen_q4_election_year_comparison
ββββ High Intelligence Value
π Purpose: Q4 (October-December) activity comparison between election years and non-election years to detect pre-election surge patterns.
π Key Columns:
| Column | Type | Description | Example |
|---|---|---|---|
year | integer | Calendar year | 2022 |
is_election_year | boolean | Election year flag | true |
q4_ballots | bigint | Q4 ballot count | 180 |
q4_documents | bigint | Q4 document count | 520 |
baseline_ballots | numeric | Non-election Q4 average | 120 |
surge_ratio | numeric | Activity ratio vs baseline | 1.50 |
π‘ Example Queries:
-- Detect Q4 pre-election surges (>150% baseline)
SELECT year, q4_ballots, baseline_ballots, surge_ratio
FROM view_riksdagen_q4_election_year_comparison
WHERE is_election_year = true AND surge_ratio > 1.5
ORDER BY surge_ratio DESC;
-- Compare 2022 election Q4 vs non-election years
SELECT year, is_election_year, q4_ballots, q4_documents
FROM view_riksdagen_q4_election_year_comparison
WHERE year BETWEEN 2020 AND 2022
ORDER BY year;
β‘ Performance: Pre-aggregated from quarterly view, fast queries
π Dependencies: view_riksdagen_seasonal_quarterly_activity
π― Framework Integration: Framework 3 (Pattern Recognition) + Framework 4 (Predictive Intelligence)
π― Use Cases: Pre-election activity prediction, electoral behavior forecasting, Q4 surge detection
view_riksdagen_seasonal_anomaly_detection
βββββ Critical Intelligence Value
π Purpose: Identifies quarterly activity anomalies >2 standard deviations from baseline with severity classification and anomaly type categorization.
π Key Columns:
| Column | Type | Description | Example |
|---|---|---|---|
year | integer | Calendar year | 2022 |
quarter | integer | Quarter (1-4) | 4 |
anomaly_type | text | Type of anomaly | BALLOT_SURGE |
z_score | numeric | Statistical deviation | 2.3 |
severity | text | Severity level | HIGH |
direction | text | Activity direction | ELEVATED |
π‘ Example Queries:
-- Critical anomalies (z-score > 2.5)
SELECT year, quarter, anomaly_type, z_score, severity
FROM view_riksdagen_seasonal_anomaly_detection
WHERE severity = 'CRITICAL'
ORDER BY ABS(z_score) DESC;
-- Recent anomalies (last 5 years)
SELECT year, quarter, anomaly_type, direction
FROM view_riksdagen_seasonal_anomaly_detection
WHERE year >= EXTRACT(YEAR FROM CURRENT_DATE) - 5
ORDER BY year DESC, quarter DESC;
β‘ Performance: Filters for |z| > 1.5, indexes on year/quarter/severity
π Dependencies: view_riksdagen_seasonal_quarterly_activity
π― Framework Integration: Framework 3 (Pattern Recognition) + Framework 6 (Decision Intelligence)
π― Use Cases: Crisis detection, operational warnings, electoral behavior anomalies, statistical outlier identification
V1.59 Election Proximity & Seasonal Analysis Views
view_riksdagen_election_proximity_trends
ββββ High Intelligence Value
π Purpose: Tracks politician activity trends approaching election dates across multiple behavioral dimensions to detect election-driven behavioral shifts.
π Key Columns:
| Column | Type | Description | Example |
|---|---|---|---|
person_id | text | Politician identifier | p123456 |
election_year | integer | Upcoming election year | 2022 |
months_to_election | integer | Months until election | 6 |
ballot_participation | numeric | Voting participation rate | 95.2 |
document_production | bigint | Document count | 45 |
activity_trend | text | Trend classification | INCREASING |
π‘ Example Queries:
-- Politicians increasing activity 6 months before election
SELECT person_id, ballot_participation, document_production
FROM view_riksdagen_election_proximity_trends
WHERE months_to_election = 6
AND activity_trend = 'INCREASING'
ORDER BY document_production DESC
LIMIT 20;
-- Pre-election behavioral patterns
SELECT election_year, months_to_election,
AVG(ballot_participation) as avg_participation
FROM view_riksdagen_election_proximity_trends
WHERE months_to_election BETWEEN 1 AND 12
GROUP BY election_year, months_to_election
ORDER BY election_year DESC, months_to_election;
β‘ Performance: Indexed on person_id, election_year, months_to_election
π Dependencies: vote_data, document_data, politician metadata
π― Framework Integration: Framework 1 (Temporal Analysis) + Framework 4 (Predictive Intelligence)
π― Use Cases: Pre-election behavior tracking, candidate visibility analysis, electoral strategy assessment
view_riksdagen_pre_election_quarterly_activity
βββββ Critical Intelligence Value
π Purpose: Comprehensive Q4 (October-December) multi-dimensional activity analysis comparing election vs non-election years with z-score calculation and party-level context.
π Key Columns:
| Column | Type | Description | Example |
|---|---|---|---|
year | integer | Calendar year | 2022 |
is_election_year | boolean | Election year flag | true |
q4_ballots | bigint | Q4 ballot count | 180 |
q4_documents | bigint | Q4 document count | 520 |
party_effectiveness | numeric | Party performance score | 87.5 |
committee_productivity | numeric | Committee output metric | 92.0 |
activity_z_score | numeric | Multi-dimensional z-score | 1.9 |
classification | text | Activity classification | ELEVATED |
π‘ Example Queries:
-- High-activity pre-election Q4 periods
SELECT year, q4_ballots, q4_documents, activity_z_score
FROM view_riksdagen_pre_election_quarterly_activity
WHERE is_election_year = true
AND activity_z_score > 1.5
ORDER BY activity_z_score DESC;
-- Party-level Q4 election analysis
SELECT year, party, q4_documents, party_effectiveness
FROM view_riksdagen_pre_election_quarterly_activity
WHERE is_election_year = true
ORDER BY year DESC, party_effectiveness DESC;
-- YoY Q4 comparison across election cycles
SELECT year, is_election_year, q4_ballots, committee_productivity
FROM view_riksdagen_pre_election_quarterly_activity
WHERE year BETWEEN 2018 AND 2023
ORDER BY year DESC;
β‘ Performance: META/META level view aggregating from multiple behavioral views, efficient for analytical queries
π Dependencies: view_politician_behavioral_trends, view_riksdagen_politician_document, view_riksdagen_politician_role_evolution, view_party_effectiveness_trends, view_committee_productivity
π― Framework Integration: Framework 1 (Temporal Analysis) + Framework 3 (Pattern Recognition)
π― Use Cases: Comprehensive system-wide pre-election activity detection, cross-election cycle comparison, party and committee context analysis
view_riksdagen_seasonal_activity_patterns
βββββ Critical Intelligence Value
π Purpose: Enhanced comprehensive Q1-Q4 seasonal pattern analysis across all election cycles (2002-2026) with advanced temporal trends, QoQ analysis, and NTILE clustering.
π Key Columns:
| Column | Type | Description | Example |
|---|---|---|---|
year | integer | Calendar year | 2022 |
quarter | integer | Quarter (1-4) | 4 |
is_election_year | boolean | Election year flag | true |
quarterly_ballots | bigint | Quarter ballot count | 180 |
qoq_ballot_change | numeric | Quarter-over-quarter % change | 15.5 |
pattern_type | text | Seasonal pattern | Q4_SURGE |
activity_cluster | integer | NTILE cluster (1-4) | 4 |
z_score | numeric | Cross-year deviation | 1.8 |
π‘ Example Queries:
-- Q4 surge patterns in election years
SELECT year, quarterly_ballots, qoq_ballot_change, pattern_type
FROM view_riksdagen_seasonal_activity_patterns
WHERE quarter = 4
AND is_election_year = true
AND pattern_type = 'Q4_SURGE'
ORDER BY year DESC;
-- High-activity quarters (top cluster)
SELECT year, quarter, quarterly_ballots, activity_cluster
FROM view_riksdagen_seasonal_activity_patterns
WHERE activity_cluster = 4
ORDER BY year DESC, quarter;
-- QoQ trends for last 3 years
SELECT year, quarter, quarterly_ballots, qoq_ballot_change
FROM view_riksdagen_seasonal_activity_patterns
WHERE year >= EXTRACT(YEAR FROM CURRENT_DATE) - 3
ORDER BY year DESC, quarter DESC;
β‘ Performance: META/META level with pre-computed z-scores from base view, LAG/LEAD for temporal trends, efficient NTILE clustering
π Dependencies: view_riksdagen_seasonal_quarterly_activity (foundation view with z-scores and baselines)
π― Framework Integration: Framework 3 (Pattern Recognition) + Framework 4 (Predictive Intelligence)
π― Use Cases: Long-term seasonal trend analysis, electoral cycle predictions, quarterly behavior clustering, pattern classification
V1.58 Career Path Analysis Views
view_riksdagen_politician_career_path_10level
ββββ High Intelligence Value
π Purpose: 10-level hierarchical career path progression tracking for politicians with role evolution, seniority analysis, and advancement patterns.
π Key Columns:
| Column | Type | Description | Example |
|---|---|---|---|
person_id | text | Politician identifier | p123456 |
career_level | integer | Career progression level (1-10) | 7 |
current_role | text | Current position | Committee Chair |
years_in_parliament | numeric | Total parliamentary years | 12.5 |
role_transitions | integer | Number of role changes | 5 |
advancement_rate | numeric | Career velocity metric | 0.56 |
seniority_rank | integer | Ranking within cohort | 15 |
π‘ Example Queries:
-- Senior politicians (level 8+)
SELECT person_id, career_level, current_role, years_in_parliament
FROM view_riksdagen_politician_career_path_10level
WHERE career_level >= 8
ORDER BY career_level DESC, years_in_parliament DESC;
-- Fast-track careers (high advancement rate)
SELECT person_id, years_in_parliament, role_transitions, advancement_rate
FROM view_riksdagen_politician_career_path_10level
WHERE years_in_parliament < 10
AND advancement_rate > 0.5
ORDER BY advancement_rate DESC;
-- Career level distribution
SELECT career_level, COUNT(*) as politician_count
FROM view_riksdagen_politician_career_path_10level
GROUP BY career_level
ORDER BY career_level;
β‘ Performance: Indexed on person_id, career_level, seniority_rank for efficient queries
π Dependencies: politician role data, committee assignments, parliamentary records
π― Framework Integration: Framework 1 (Temporal Analysis) - Career progression tracking
π― Use Cases: Leadership pipeline analysis, career progression patterns, seniority tracking, promotion velocity assessment
END OF DOCUMENT