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

  1. Executive Summary
  2. View Categories Overview
  3. Complete View Inventory
  4. Politician Views
  5. Party Views
  6. Committee Views
  7. Ministry/Government Views
  8. Vote Data Views
  9. Document Views
  10. Intelligence Views
  11. Application & Audit Views
  12. Common Usage Patterns
  13. View Dependency Diagram
  14. Performance Optimization Guide
  15. Cross-Reference to Intelligence Frameworks
  16. 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)

MetricCountDescription
Total Views110βœ… UPDATED v1.80: 77 regular + 33 materialized (verified against full_schema.sql)
Regular Views77βœ… UPDATED: 77 regular views (CREATE VIEW / CREATE OR REPLACE VIEW)
Materialized Views33βœ… UPDATED: 28 legacy view_* materialized + 5 new mv_* materialized
Views Documented (Detailed)15βœ… Views with comprehensive examples and performance characteristics
Views Documented (Structured)95Purpose, metrics, queries, product mappings
Documentation Coverage100%All 110 views documented
Intelligence Views8Advanced analytical views (risk, anomaly, influence, crisis, momentum, dashboard, temporal trends)
Election Cycle Views6v1.51: META/META-level election cycle analysis across 6 frameworks
Party Analysis Views (v1.61)4Recreated views with 59-70 columns, advanced window functions, forecasting
Career Trajectory Views4v1.56/v1.58: Politician career pattern detection, role evolution, longevity analysis, career path
Party Transition Views3v1.57: Party switcher tracking with defection analysis and career outcomes
Seasonal/Election Year Views7v1.55/v1.59/v1.60: Temporal pattern analysis with seasonal decomposition and election year comparison
Decision Flow Views4Party, politician, ministry, temporal trends for decision analysis
New-Style Materialized Views5v1.76: mv_* prefix views for annual metrics, decision trends, ministry impact, party flow
Vote Data Views16Daily, weekly, monthly, annual ballot and voting data summaries (ballot, party, politician)
Application Event Views12User behavior tracking (daily, weekly, monthly, annual)
Document Views9Politician and party document productivity
Committee Views12Committee productivity, decisions, membership
Government/Ministry Views9Government and ministry performance tracking (includes mv_ministry_decision_impact)
Party Views19Party performance, decision flow, effectiveness, transitions, longitudinal analysis
Politician Views12Politician performance, experience, career trajectory, behavioral trends
Application/Audit Views14Platform usage tracking and audit trails
Database Size20 GBTotal database size (validated 2025-11-21)
Total Rows5.6MTotal rows across all tables
Base Tables93Core data tables
Indexes178Database 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

  1. Political Scorecards: Individual politician performance metrics (attendance, effectiveness, productivity)
  2. Coalition Analysis: Party alignment matrices, government formation forecasting
  3. Risk Assessment: Behavioral anomaly detection, defection risk, democratic accountability
  4. Trend Analysis: Temporal pattern recognition, momentum tracking, predictive analytics
  5. Network Analysis: Influence mapping, power structure visualization, broker identification
  6. Document Intelligence: Legislative productivity, policy focus analysis
  7. Performance Monitoring: Committee effectiveness, ministry performance, party strength
DocumentLinkDescription
Business Product DocumentBUSINESS_PRODUCT_DOCUMENT.mdCommercial product strategy and market analysis
JSON Export Specificationsjson-export-specs/API schemas and data format specifications
Intelligence Data Flow MapINTELLIGENCE_DATA_FLOW.mdCentral cross-reference hub showing data pipeline
Intelligence Evolution ChangelogCHANGELOG_INTELLIGENCE.mdUnified intelligence capability tracking
Sample Data Directoryservice.data.impl/sample-data/Actual sample CSV files for all 110 views and 54 tables
Intelligence FrameworksDATA_ANALYSIS_INTOP_OSINT.mdAnalysis methodologies and OSINT techniques
Risk RulesRISK_RULES_INTOP_OSINT.md45 behavioral detection rules
Changelog AnalysisLIQUIBASE_CHANGELOG_INTELLIGENCE_ANALYSIS.mdSchema evolution analysis
Data ModelDATA_MODEL.mdDatabase schema and relationships
Schema Maintenanceservice.data.impl/README-SCHEMA-MAINTENANCE.mdDatabase 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:

  1. 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
    
  2. 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
    
  3. 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
    
  4. Calculate Coverage: Compute percentage of documented views

    COVERAGE=$((100 * DOCUMENTED / TOTAL))
    
  5. 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:

  1. 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
    
  2. Validate view documentation coverage:

    ./validate-view-documentation.sh
    # Reviews full_schema.sql vs DATABASE_VIEW_INTELLIGENCE_CATALOG.md
    
  3. Review findings: Check for missing or extra documented views

  4. Update documentation: Add missing views or remove obsolete ones

  5. Re-run validation: Confirm fixes achieve 100% coverage

Historical Validations

DateCoverageTotal ViewsMissingStatusKey Changes
2025-11-2010.98%8273⚠️ InitialIdentified major documentation gap
2025-11-21100%820βœ… CompleteAdded all 73 missing views
2025-11-25100%840βœ… UpdatedCorrected count, validated integrity
2026-04-05100%1100βœ… CurrentFull 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):

MetricScoreStatusNotes
Overall Health82/100βœ… GoodAbove 80/100 threshold
Schema Integrity90/100βœ… ExcellentAll views valid
Data Quality80/100βœ… GoodMeets standards
Performance75/100⚠️ AcceptableSome optimization opportunities
Security85/100βœ… GoodNo 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 analysisTemporal Analysis Views
See which views support comparative analysisComparative Analysis Views
See which views support pattern recognitionPattern Recognition Views
See which views support predictive intelligencePredictive Intelligence Views
See which views support network analysisNetwork Analysis Views
See complete data flow pipelineIntelligence Data Flow Map
Understand how risk rules use viewsRisk Rule β†’ View Mapping
Browse politician viewsPolitician Views
Browse party viewsParty Views
Browse committee viewsCommittee Views
Browse vote data viewsVote 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

CategoryCountPrimary PurposeIntelligence Value
Politician Views12Individual performance, experience, behavior, career trajectory⭐⭐⭐⭐⭐ VERY HIGH
Party Views19Organizational effectiveness, coalition analysis, transitions⭐⭐⭐⭐⭐ VERY HIGH
Committee Views12Legislative body productivity, decision tracking⭐⭐⭐⭐ HIGH
Ministry Views9Government executive performance monitoring⭐⭐⭐⭐ HIGH
Vote Data Views15+Ballot summaries (daily/weekly/monthly/annual)⭐⭐⭐⭐ HIGH
Document Views7+Legislative productivity, document tracking⭐⭐⭐ MEDIUM
Intelligence Views7+Advanced analytics, risk assessment, trends⭐⭐⭐⭐⭐ VERY HIGH
Election Cycle Views6META-level election cycle analysis⭐⭐⭐⭐⭐ VERY HIGH
Seasonal/Election Year Views7Temporal patterns, election proximity trends⭐⭐⭐⭐ HIGH
Application Views14Audit trails, user activity, session tracking⭐⭐ LOW
New-Style Materialized Views5Pre-aggregated metrics for performance⭐⭐⭐⭐ HIGH
WorldBank Views1Economic indicator data⭐⭐⭐ MEDIUM

View Evolution Timeline

VersionDateKey Views IntroducedIntelligence Impact
v1.0-v1.12014-11Base politician, party, committee viewsFoundation
v1.2-v1.32015Vote summary views (daily/weekly/monthly/annual)Temporal analysis enabled
v1.23-v1.242023Party coalition views, document summariesCoalition analysis
v1.25-v1.262024Committee decision views, materialized viewsPerformance optimization
v1.27-v1.282024Politician experience scoringExpertise tracking
v1.292024-11Intelligence dashboard, coalition alignment, anomaly detectionAdvanced intelligence
v1.302024-11Behavioral trends, risk evolution, effectiveness trendsPredictive 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 NameTypeIntelligence ValueDescription
view_application_action_event_page_annual_summaryStandard⭐⭐Annual summary of user interactions by page
view_application_action_event_page_daily_summaryStandard⭐⭐Daily summary of user interactions by page
view_application_action_event_page_element_annual_summaryStandard⭐⭐Annual summary of UI element interactions
view_application_action_event_page_element_daily_summaryStandard⭐⭐Daily summary of UI element interactions
view_application_action_event_page_element_hourly_summaryStandard⭐⭐Hourly summary of UI element interactions
view_application_action_event_page_element_weekly_summaryStandard⭐⭐Weekly summary of UI element interactions
view_application_action_event_page_hourly_summaryStandard⭐⭐Hourly summary of user interactions by page
view_application_action_event_page_modes_annual_summaryStandard⭐⭐Annual summary of page access modes
view_application_action_event_page_modes_daily_summaryStandard⭐⭐Daily summary of page access modes
view_application_action_event_page_modes_hourly_summaryStandard⭐⭐Hourly summary of page access modes
view_application_action_event_page_modes_weekly_summaryStandard⭐⭐Weekly summary of page access modes
view_application_action_event_page_weekly_summaryStandard⭐⭐Weekly summary of user interactions by page
view_audit_author_summaryStandard⭐⭐Summary of data changes by author
view_audit_data_summaryStandard⭐⭐Summary of audit trail data changes

Committee Views (12 views)

View NameTypeIntelligence ValueDescription
view_committee_productivityStandard⭐⭐⭐⭐Committee productivity metrics and efficiency indicators
view_committee_productivity_matrixStandard⭐⭐⭐⭐Matrix comparison of committee productivity
view_riksdagen_committeeStandard⭐⭐⭐⭐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_proposalStandard⭐⭐⭐Parliamentary member proposals to committees
view_riksdagen_committee_role_memberStandard⭐⭐⭐Committee role assignments and members
view_riksdagen_committee_rolesStandard⭐⭐⭐Committee role definitions and structure

Document Views (9 views)

View NameTypeIntelligence ValueDescription
view_document_data_committee_report_urlStandard⭐⭐⭐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_summaryStandard⭐⭐⭐⭐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_proposalsStandard⭐⭐⭐Parliamentary member legislative proposals
mv_annual_document_metricsπŸ”„ Materialized⭐⭐⭐⭐Pre-aggregated annual document metrics (v1.76)

Government/Ministry Views (9 views)

View NameTypeIntelligence ValueDescription
view_ministry_effectiveness_trendsStandard⭐⭐⭐⭐⭐Ministry performance trends over time
view_ministry_productivity_matrixStandard⭐⭐⭐⭐⭐Comparative ministry productivity analysis
view_ministry_risk_evolutionStandard⭐⭐⭐⭐⭐Evolution of ministry risk indicators
view_ministry_decision_impactStandard⭐⭐⭐⭐⭐Ministry proposal success rates and effectiveness (v1.35)
mv_ministry_decision_impactπŸ”„ Materialized⭐⭐⭐⭐⭐Materialized ministry decision impact for performance (v1.76)
view_riksdagen_govermentStandard⭐⭐⭐⭐Government structure and composition
view_riksdagen_goverment_proposalsStandard⭐⭐⭐⭐Government legislative proposals
view_riksdagen_goverment_role_memberStandard⭐⭐⭐⭐Government role assignments
view_riksdagen_goverment_rolesStandard⭐⭐⭐⭐Government role definitions

Intelligence & Risk Views (8 views)

View NameTypeIntelligence ValueDescription
view_decision_temporal_trendsStandard⭐⭐⭐⭐⭐Decision temporal trends and pattern analysis
mv_decision_temporal_trendsπŸ”„ Materialized⭐⭐⭐⭐⭐Materialized decision temporal trends for performance (v1.76)
πŸ“– view_party_effectiveness_trendsStandard⭐⭐⭐⭐⭐Party effectiveness metrics over time
πŸ“– view_politician_behavioral_trendsStandard⭐⭐⭐⭐⭐Politician behavioral pattern analysis
view_politician_risk_summaryStandard⭐⭐⭐⭐⭐Aggregated politician risk indicators
view_riksdagen_crisis_resilience_indicatorsStandard⭐⭐⭐⭐⭐Crisis period performance and resilience metrics
view_riksdagen_intelligence_dashboardStandard⭐⭐⭐⭐⭐Unified intelligence dashboard with key metrics
πŸ“– view_riksdagen_voting_anomaly_detectionStandard⭐⭐⭐⭐⭐Voting anomaly and defection risk detection
πŸ“– view_risk_score_evolutionStandard⭐⭐⭐⭐⭐Evolution of risk scores over time

Party Views (19 views)

View NameTypeIntelligence ValueDescription
πŸ“– view_riksdagen_coalition_alignment_matrixStandard⭐⭐⭐⭐⭐Party coalition alignment and probability matrix
πŸ“– view_riksdagen_partyStandard⭐⭐⭐⭐⭐Core party information and metrics
view_party_performance_metricsStandard⭐⭐⭐⭐⭐Comprehensive party performance indicators
view_riksdagen_party_summaryStandardβ­β­β­β­πŸ“˜ Party assignment & document aggregation (v1.61 recreated)
view_riksdagen_party_ballot_support_annual_summaryStandard⭐⭐⭐⭐Annual party ballot support patterns
view_riksdagen_party_coalation_against_annual_summaryStandard⭐⭐⭐⭐Annual party opposition coalition patterns
πŸ“– view_riksdagen_party_decision_flowStandard⭐⭐⭐⭐⭐Party-level proposal decision analysis (v1.35)
mv_party_decision_flowπŸ”„ Materialized⭐⭐⭐⭐⭐Materialized party decision flow for performance (v1.76)
view_riksdagen_party_longitudinal_performanceStandardβ­β­β­β­β­πŸ“˜ Semester performance trackingβ€”70 KPIs (v1.61 recreated)
view_riksdagen_party_coalition_evolutionStandardβ­β­β­β­β­πŸ“˜ Party-pair alliance trackingβ€”35 metrics (v1.61 recreated)
view_riksdagen_party_electoral_trendsStandardβ­β­β­β­β­πŸ“˜ Electoral performanceβ€”49 indicators (v1.61 recreated)
view_riksdagen_party_memberStandard⭐⭐⭐⭐Party membership roster
view_riksdagen_party_momentum_analysisStandard⭐⭐⭐⭐⭐Party momentum and trend analysis
view_riksdagen_party_role_memberStandard⭐⭐⭐Party role assignments
view_riksdagen_party_signatures_document_summaryStandard⭐⭐⭐Party document signature patterns
view_riksdagen_party_transition_historyStandard⭐⭐⭐⭐⭐Party switcher tracking with historical transitions (v1.55)
view_riksdagen_party_defector_analysisStandard⭐⭐⭐⭐⭐Defector behavioral analysis and early warning signals (v1.55)
view_riksdagen_party_switcher_outcomesStandard⭐⭐⭐⭐⭐Post-transition career success metrics (v1.55)
view_riksdagen_person_signed_document_summaryStandard⭐⭐⭐Individual document signature summary

Politician Views (12 views)

View NameTypeIntelligence ValueDescription
πŸ“– view_riksdagen_politicianStandard⭐⭐⭐⭐⭐Core politician information and demographics
πŸ“– view_riksdagen_politician_documentπŸ”„ Materialized⭐⭐⭐⭐⭐Politician document authorship and productivity
πŸ“– view_riksdagen_politician_experience_summaryStandard⭐⭐⭐⭐⭐Politician experience scoring and classification
view_riksdagen_politician_ballot_summaryStandard⭐⭐⭐⭐⭐Politician voting record summary
view_riksdagen_politician_influence_metricsStandard⭐⭐⭐⭐⭐Politician influence and network analysis
πŸ“– view_riksdagen_politician_decision_patternStandard⭐⭐⭐⭐⭐Politician decision effectiveness and committee specialization (v1.35)
view_riksdagen_politician_career_path_10levelStandard⭐⭐⭐⭐⭐10-level politician career path classification (v1.58)
view_riksdagen_politician_career_trajectoryStandard⭐⭐⭐⭐⭐Politician career trajectory and pattern detection (v1.56)
view_riksdagen_politician_longevity_analysisStandard⭐⭐⭐⭐⭐Politician longevity and survival analysis (v1.56)
view_riksdagen_politician_role_evolutionStandard⭐⭐⭐⭐⭐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 NameTypeIntelligence ValueDescription
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 NameTypeIntelligence ValueDescription
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 NameTypeIntelligence ValueDescription
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 NameTypeIntelligence ValueDescription
mv_annual_voting_metricsπŸ”„ Materialized⭐⭐⭐⭐Pre-aggregated annual voting metrics (v1.76)

Election Cycle Views (6 views)

View NameTypeIntelligence ValueDescription
view_election_cycle_anomaly_patternStandard⭐⭐⭐⭐⭐Election cycle anomaly pattern detection (v1.51)
view_election_cycle_comparative_analysisStandard⭐⭐⭐⭐⭐Cross-election cycle comparative analysis (v1.51)
view_election_cycle_decision_intelligenceStandard⭐⭐⭐⭐⭐Election cycle decision intelligence metrics (v1.51)
view_election_cycle_network_analysisStandard⭐⭐⭐⭐⭐Election cycle network and coalition analysis (v1.51)
view_election_cycle_predictive_intelligenceStandard⭐⭐⭐⭐⭐Election cycle predictive intelligence (v1.51)
view_election_cycle_temporal_trendsStandard⭐⭐⭐⭐⭐Election cycle temporal trend analysis (v1.51)

Seasonal & Election Year Views (7 views)

View NameTypeIntelligence ValueDescription
view_riksdagen_election_proximity_trendsStandard⭐⭐⭐⭐Behavioral trends by proximity to elections (v1.59)
view_riksdagen_election_year_behavioral_patternsStandard⭐⭐⭐⭐Election year vs non-election year behavioral patterns (v1.60)
view_riksdagen_pre_election_quarterly_activityStandard⭐⭐⭐⭐Pre-election quarterly activity patterns (v1.59)
view_riksdagen_q4_election_year_comparisonStandard⭐⭐⭐⭐Q4 election year vs non-election year comparison (v1.55)
view_riksdagen_seasonal_activity_patternsStandard⭐⭐⭐⭐Seasonal parliamentary activity patterns (v1.59)
view_riksdagen_seasonal_anomaly_detectionStandard⭐⭐⭐⭐⭐Seasonal anomaly detection in parliamentary activity (v1.55)
view_riksdagen_seasonal_quarterly_activityStandard⭐⭐⭐⭐Quarterly seasonal activity metrics (v1.55)

WorldBank Data (1 view)

View NameTypeIntelligence ValueDescription
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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier (Riksdagen ID)'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
genderVARCHAR(10)Gender'woman', 'man'
born_yearINTEGERBirth year1972
partyVARCHAR(50)Current party affiliation (short code)'S' (Social Democrats)
statusVARCHAR(50)Current assignment status'TjΓ€nstgΓΆrande riksdagsledamot'
electoral_regionVARCHAR(100)Electoral constituency'Stockholms kommun'
total_assignmentsINTEGERTotal career assignments15
total_days_servedINTEGERTotal days in parliament2847
first_assignment_dateDATECareer start date'2014-09-29'
last_assignment_dateDATEMost 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 FrameworkUse CaseExample ApplicationLink
Temporal AnalysisTrack career duration and entry cohortsMonitor politician career trajectories over timeFramework Docs
Comparative AnalysisParty composition and experience levelsCompare experience distribution across partiesFramework Docs
Pattern RecognitionDemographic clustering analysisIdentify patterns in gender, age, regional representationFramework Docs
Predictive IntelligenceCareer trajectory modelingPredict re-election likelihood based on profileFramework Docs
Network AnalysisPolitician identification for network constructionBase layer for building collaboration and voting networksFramework 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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Current party affiliation'S'
total_assignmentsINTEGERTotal number of assignments15
total_daysINTEGERTotal days in active assignments2847
total_yearsNUMERIC(10,2)Total years experience7.79
ministerial_daysINTEGERDays in government positions1095
committee_chair_daysINTEGERDays as committee chair547
committee_member_daysINTEGERDays as committee member1825
parliamentary_member_daysINTEGERDays as MP without other roles380
total_weighted_expNUMERIC(15,2)Weighted experience score4783.50
experience_levelVARCHAR(50)Classification'EXPERIENCED', 'VETERAN', 'NOVICE'
ministerial_experienceBOOLEANHas held government positionTRUE
committee_leadership_expBOOLEANHas been committee chairTRUE
avg_assignment_durationNUMERIC(10,2)Average assignment length (days)189.80

Weighting System

Experience is weighted by assignment importance:

Assignment TypeWeight MultiplierRationale
Ministerial2.0xGovernment executive responsibility
Committee Chair1.5xLeadership and organizational authority
Committee Member1.2xSpecialized legislative work
Parliamentary Member1.0xBase 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

LevelCriteriaDescription
NOVICE< 365 daysFirst year, learning parliamentary procedures
DEVELOPING365-1095 days (1-3 years)Building expertise, establishing networks
EXPERIENCED1095-2190 days (3-6 years)Established politician, strong influence
VETERAN2190-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

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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier'Q123456'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Current party affiliation'S'
year_monthDATEMonth of aggregation (first day)'2024-10-01'
ballot_countINTEGERNumber of ballots in period45
avg_absence_rateNUMERIC(5,2)Percentage absent12.50
avg_win_rateNUMERIC(5,2)Percentage on winning side67.80
avg_rebel_rateNUMERIC(5,2)Percentage against party8.30
absence_trendNUMERIC(5,2)Change from previous month+2.50
effectiveness_trendNUMERIC(5,2)Win rate change-3.20
rebellion_trendNUMERIC(5,2)Rebel rate change+1.10
ma_3month_absenceNUMERIC(5,2)3-month moving average absence11.20
ma_3month_winNUMERIC(5,2)3-month moving average win rate69.00
ma_3month_rebelNUMERIC(5,2)3-month moving average rebel rate7.50
attendance_statusVARCHAR(50)Classification'MODERATE_ABSENTEEISM'
effectiveness_statusVARCHAR(50)Classification'EFFECTIVE'
discipline_statusVARCHAR(50)Classification'LOW_INDEPENDENCE'
behavioral_assessmentVARCHAR(50)Overall assessment'STANDARD_BEHAVIOR'

Classification Thresholds

Attendance Status:

  • EXCELLENT_ATTENDANCE: < 5% absence
  • GOOD_ATTENDANCE: 5-10% absence
  • MODERATE_ABSENTEEISM: 10-20% absence
  • HIGH_ABSENTEEISM: 20-30% absence
  • CRITICAL_ABSENTEEISM: > 30% absence

Effectiveness Status:

  • HIGHLY_EFFECTIVE: > 70% win rate
  • EFFECTIVE: 55-70% win rate
  • MODERATE_EFFECTIVENESS: 45-55% win rate
  • INEFFECTIVE: < 45% win rate

Discipline Status:

  • HIGH_INDEPENDENCE: > 15% rebellion (frequent dissent)
  • MODERATE_INDEPENDENCE: 10-15% rebellion
  • LOW_INDEPENDENCE: 5-10% rebellion
  • PARTY_LINE: < 5% rebellion (high discipline)

Behavioral Assessment (Combined):

  • EXCELLENT_BEHAVIOR: Excellent attendance + high effectiveness + low rebellion
  • STANDARD_BEHAVIOR: Normal patterns across all metrics
  • MODERATE_RISK: One metric concerning, others normal
  • ELEVATED_RISK: Multiple concerning metrics
  • CRITICAL_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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Party at document submission'S'
document_idVARCHAR(255)Document identifier'H801234'
document_typeVARCHAR(50)Type of document'Interpellation', 'Motion'
titleTEXTDocument title'Svar pΓ₯ frΓ₯ga om...'
sub_titleTEXTDocument subtitleAdditional context
made_public_dateDATEPublication date'2024-10-15'
document_statusVARCHAR(50)Current status'Besvarad', 'Bordlagd'
org_codeVARCHAR(20)Originating organization'au' (Labor committee)
labelVARCHAR(100)Document category/label'Arbetsmarknad'

Document Types

TypeSwedish TermDescriptionFrequency
MotionMotionLegislative proposal by MPCommon
InterpellationInterpellationQuestion to minister requiring debateModerate
Written QuestionSkriftlig frΓ₯gaWritten question to ministerCommon
Simple QuestionFrΓ₯gaSimple parliamentary questionVery Common
EU DocumentEU-dokumentEU-related documentRare
Committee ProposalUtskottsfΓΆrslagCommittee recommendationCommon

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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Party affiliation at decision time'S'
committeeVARCHAR(255)Committee handling decision'UU' (Foreign Affairs)
committee_orgVARCHAR(20)Committee organization code'uu'
decision_monthDATEMonth of aggregation (first day)'2024-10-01'
decision_yearINTEGERYear of decision2024
decision_month_numINTEGERMonth number (1-12)10
total_decisionsBIGINTTotal decisions in period45
approved_decisionsBIGINTDecisions approved (bifall)32
rejected_decisionsBIGINTDecisions rejected (avslag)8
referred_back_decisionsBIGINTDecisions referred back3
other_decisionsBIGINTOther decision outcomes2
approval_rateNUMERIC(5,2)Percentage approved71.11
rejection_rateNUMERIC(5,2)Percentage rejected17.78
earliest_decision_dateDATEFirst decision in period'2024-10-01'
latest_decision_dateDATELast 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 FrameworkUse CaseExample ApplicationLink
Temporal AnalysisTrack decision effectiveness over timeMonitor politician approval rate trends monthlyFramework Docs
Comparative AnalysisPolitician vs. party/committee benchmarksCompare individual approval rates to committee averagesFramework Docs
Pattern RecognitionCommittee specialization clusteringIdentify specialists vs. generalistsFramework Docs
Predictive IntelligenceForecast decision success probabilityPredict proposal outcomes based on politician historyFramework 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 date
  • person_id: Politician identifier
  • party: Party affiliation at time of submission
  • document_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 NameTypeIntelligence ValueDescription
view_riksdagen_party_decision_flowStandard⭐⭐⭐⭐⭐Party-level decision approval rates and patterns
view_riksdagen_politician_decision_patternStandard⭐⭐⭐⭐⭐Individual politician proposal success tracking
view_ministry_decision_impactStandard⭐⭐⭐⭐⭐Ministry legislative effectiveness analysis
view_decision_temporal_trendsStandard⭐⭐⭐⭐⭐Time-series decision patterns with moving averages
view_decision_outcome_kpi_dashboardStandard⭐⭐⭐⭐⭐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 NameTypeDescriptionExample
partyVARCHAR(50)Political party code'S' (Social Democrats)
committeeVARCHAR(255)Committee handling decisions'UU' (Foreign Affairs)
decision_monthDATEMonth of aggregation (first day)'2024-10-01'
decision_yearINTEGERYear of decision2024
decision_month_numINTEGERMonth number (1-12)10
total_decisionsBIGINTTotal decisions in period45
approved_decisionsBIGINTDecisions approved (bifall)32
rejected_decisionsBIGINTDecisions rejected (avslag)8
other_decisionsBIGINTOther decision outcomes5
approval_rateNUMERICApproval percentage71.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

  1. Coalition Formation Analysis: Identify party combinations with highest joint approval rates
  2. Opposition Effectiveness: Measure which opposition parties achieve legislative success
  3. Government Strength: Track ruling coalition proposal success over time
  4. Committee Specialization: Determine which parties dominate specific policy areas
  5. Trend Detection: Early warning for declining party legislative effectiveness
  • 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


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 NameTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier'0279865129018'
first_nameVARCHAR(255)Politician first name'Magdalena'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Party affiliation at decision time'S'
committeeVARCHAR(255)Committee handling decision'UU' (Foreign Affairs)
decision_monthDATEMonth of aggregation (first day)'2024-10-01'
decision_yearINTEGERYear of decision2024
decision_month_numINTEGERMonth number (1-12)10
total_decisionsBIGINTTotal decisions in period45
approved_decisionsBIGINTDecisions approved (bifall)32
rejected_decisionsBIGINTDecisions rejected (avslag)8
other_decisionsBIGINTOther decision outcomes5
approval_rateNUMERICApproval percentage71.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

  1. Rising Political Stars: Identify high-performing politicians for advancement
  2. Committee Chair Effectiveness: Assess committee leadership performance
  3. Shadow Cabinet Analysis: Evaluate opposition leadership proposal success
  4. Legislative Mentorship: Target low-performing members for support
  5. Resignation Prediction: Detect declining effectiveness patterns (early warning)
  • D-02: Politician Proposal Ineffectiveness - Triggers when approval rate <20% with 10+ proposals

Cross-References


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 NameTypeDescriptionExample
ministry_codeVARCHAR(10)Ministry abbreviation'FI' (Finance)
ministry_nameVARCHAR(255)Full ministry name'Finance Ministry'
decision_yearINTEGERYear of decision2024
decision_quarterINTEGERQuarter (1-4)3
total_proposalsBIGINTTotal ministry proposals78
approved_proposalsBIGINTApproved proposals65
rejected_proposalsBIGINTRejected proposals8
other_outcomesBIGINTOther decision outcomes5
approval_rateNUMERICApproval percentage83.33
avg_processing_daysNUMERICAverage days to decision45.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

  1. Minister Performance Evaluation: Objective assessment of minister effectiveness
  2. Coalition Friction Detection: Low approval rates indicate coalition disagreement
  3. Budget Effectiveness: Track which ministries deliver on policy promises
  4. Government Reshuffle: Identify underperforming ministries for cabinet changes
  5. Policy Priority Tracking: Monitor success of government's top policy areas
  • D-03: Ministry Declining Success Rate - Triggers when approval rate declines >20% QoQ

Cross-References


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 NameTypeDescriptionExample
decision_dayDATEDate of decisions'2024-10-15'
daily_decisionsBIGINTTotal decisions on date127
moving_avg_7dNUMERIC7-day moving average98.43
moving_avg_30dNUMERIC30-day moving average85.67
day_of_weekINTEGERDay of week (0=Sunday)2 (Tuesday)
week_of_yearINTEGERWeek number42
monthINTEGERMonth number10

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

  1. Crisis Response Monitoring: Detect emergency legislative activity spikes
  2. Process Bottleneck Detection: Identify unusual decision processing delays
  3. Seasonal Planning: Resource allocation based on historical patterns
  4. Media Monitoring: Validate claims of legislative "gridlock" or "rush"
  5. Pre-Recess Activity: Track decision surge before parliamentary breaks
  • D-04: Decision Volume Anomaly - Triggers when z-score > 2 or < -2

Cross-References


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)

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 identifier
  • formed_date: Government formation date
  • dissolved_date: End date (NULL if current)
  • prime_minister: PM name
  • coalition_parties: Parties in government (array)
  • cabinet_size: Number of ministers
  • majority_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 identifier
  • role_code: Ministry/position code
  • role_title: Minister title (e.g., "Utbildningsminister")
  • from_date: Appointment date
  • to_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 identifier
  • role_title: Official role name
  • ministry_category: Ministry grouping
  • role_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

ColumnTypeDescriptionExample
ministry_idVARCHAR(50)Ministry organization code'U', 'Ju', 'Fi', 'FΓΆ'
ministry_nameVARCHAR(255)Official ministry department name'Utrikesdepartementet'
role_codeVARCHAR(50)Government role code filter'MINISTER', 'STATSSEKRETERARE'
total_assignmentsINTEGERTotal role assignments to ministry47
total_membersINTEGERUnique individuals assigned (COUNT DISTINCT)23
first_assignment_dateDATEEarliest assignment date'1995-01-01'
last_assignment_dateDATEMost recent assignment date'2024-12-31'
is_activeBOOLEANMinistry currently operational (to_date >= CURRENT_DATE or NULL)TRUE

Swedish Government Ministries

CodeMinistry Name (Swedish)English NameTypical Cabinet Size
JuJustitiedepartementetMinistry of Justice1-2 ministers
UUtrikesdepartementetMinistry of Foreign Affairs1-2 ministers
FΓΆFΓΆrsvarsdepartementetMinistry of Defence1 minister
FiFinansdepartementetMinistry of Finance1-2 ministers
UUtbildningsdepartementetMinistry of Education1-2 ministers
SSocialdepartementetMinistry of Health and Social Affairs1-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 definitions
  • view_riksdagen_goverment_role_member - Person-to-ministry mappings
  • view_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_code contains 'MINISTER' (e.g., MINISTER, UTRIKESMINISTER)
  • detail contains 'departementet' (Swedish for "department")
  • detail equals '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;
-- 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. Policy Domain Success Patterns:

    • Compare success rates across different policy domains (ministries)
    • Identify high-performing vs. struggling ministries
    • Resource allocation and capacity assessment
  • 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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Kinberg Batra'
partyVARCHAR(50)Current party affiliation'M'
election_yearINTEGERElection cycle year (2002-2026)2018
career_cycle_numberINTEGERSequential cycle in career3
total_cyclesBIGINTTotal election cycles active5
career_start_yearINTEGERFirst election cycle2006
career_end_yearINTEGERLatest election cycle2022
ballot_countBIGINTVotes cast in this cycle847
attendance_rateNUMERICAttendance % (vs absences)94.3
win_rateNUMERICWin % on party alignment votes87.2
leadership_rolesBIGINTLeadership positions held3
documents_authoredBIGINTDocuments authored42
avg_career_attendanceNUMERICCareer average attendance91.5
performance_vs_baselineNUMERICCurrent vs career average+2.8
career_stageVARCHAR(50)'EARLY_CAREER', 'MID_CAREER', 'LATE_CAREER''MID_CAREER'
performance_trendVARCHAR(50)'IMPROVING', 'DECLINING', 'STABLE', 'NEW_ENTRY''IMPROVING'
career_patternVARCHAR(50)Overall pattern classification'RISING_STAR'

Career Pattern Classification

PatternCriteriaIntelligence Value
PEAK_PERFORMANCEHigh attendance (>90%), stable trend, mid-late careerRetention target, mentorship candidate
RISING_STARImproving trend, early-mid career, above baselinePromotion candidate, future leader
LATE_CAREER_DECLINEDeclining trend, late career, below baselineRetirement risk, succession planning
STRUGGLING_NEWCOMERLow attendance (<70%), new entry, first cycleSupport needed, attrition risk
CONSISTENTStable trend, near baseline, multiple cyclesReliable 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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Ebba'
last_nameVARCHAR(255)Politician last name'Busch'
partyVARCHAR(50)Party affiliation'KD'
role_codeVARCHAR(255)Role identifier'Partiledare'
role_tierVARCHAR(50)Role classification'PARTY_LEADER'
role_weightINTEGERRole importance score (50-1000)900
role_startDATERole start date2015-04-25
role_endDATERole end date2022-09-19
role_start_yearINTEGERStart year2015
role_end_yearINTEGEREnd year2022
role_instancesBIGINTTimes held this role1
total_days_in_roleINTEGERTotal days in role2704
years_in_roleINTEGERTotal years7
is_current_roleBOOLEANCurrently activeFALSE
role_sequenceBIGINTRole order in career3
peak_role_weightINTEGERHighest role achieved900
career_first_yearINTEGERCareer start2002
career_last_yearINTEGERCareer end/current2022
progression_patternVARCHAR(50)Career trajectory'CAREER_PEAK'
career_levelVARCHAR(50)Overall achievement level'TOP_LEADERSHIP'
advancement_velocityNUMERICRole weight increase per year42.50

Role Tier Hierarchy & Weights

TierWeightRolesExample
MINISTER1000Government ministers, Prime Minister'Statsminister', 'Finansminister'
SPEAKER800Parliament Speaker, Vice Speakers'Talman', 'FΓΆrste vice talman'
PARTY_LEADER900Party leaders'Partiledare'
COMMITTEE_CHAIR600Committee chairs'OrdfΓΆrande'
COMMITTEE_VICE_CHAIR500Committee vice chairs'Vice ordfΓΆrande'
COMMITTEE_MEMBER400Committee members'Ledamot'
MP300Parliament members'Riksdagsledamot'
SUBSTITUTE100Substitute members'Suppleant'

Progression Patterns

PatternDescriptionCareer Implication
ASCENDINGSteady upward progressionSuccessful career, increasing responsibility
CAREER_PEAKReached peak role weightAt highest achievement level
DESCENDINGMoving to lower tier rolesCareer wind-down or party loss
LATERALSame tier, different rolesSpecialization, no advancement
PEAK_ROLEHighest weighted role achievedCareer 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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Unique politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Margot'
last_nameVARCHAR(255)Politician last name'WallstrΓΆm'
partyVARCHAR(50)Party affiliation'S'
statusVARCHAR(50)Current status'active', 'retired'
born_yearINTEGERBirth year1953
career_start_dateDATEFirst activity date1988-10-03
career_end_dateDATELast activity date2022-09-15
first_activity_yearINTEGERFirst election cycle1988
last_activity_yearINTEGERLast election cycle2022
total_career_daysINTEGERTotal career days12396
total_career_yearsNUMERICTotal years active33.95
age_at_career_startINTEGERAge when started35
age_at_career_endINTEGERCurrent age or age at exit69
election_cycles_activeBIGINTNumber of cycles participated8
total_votes_castBIGINTLifetime votes cast6842
total_assignmentsBIGINTTotal assignments held18
is_currently_activeBOOLEANCurrently servingTRUE
avg_votes_per_yearNUMERICVoting activity rate201.5
avg_assignments_per_yearNUMERICAssignment turnover0.53
career_continuity_scoreNUMERIC% of possible cycles active88.9
longevity_categoryVARCHAR(50)Duration classification'VETERAN_20_PLUS'
activity_levelVARCHAR(50)Engagement classification'VERY_ACTIVE'
continuity_patternVARCHAR(50)Career consistency'CONTINUOUS'
career_life_stageVARCHAR(50)Age-based classification'SENIOR_ACTIVE'
retention_riskVARCHAR(50)Risk assessment for active'HIGH_RETIREMENT_RISK'

Longevity Categories

CategoryCriteriaTypical Profile
VETERAN_20_PLUS20+ yearsElder statesmen, institutional memory
LONG_SERVICE_15_2015-20 yearsSenior experienced politicians
ESTABLISHED_10_1510-15 yearsEstablished, experienced members
MID_CAREER_5_105-10 yearsMid-career, proven track record
JUNIOR_2_52-5 yearsJunior members, building experience
NEWCOMER_UNDER_2<2 yearsNew entrants, learning phase

Activity Levels

LevelVotes/YearDescription
VERY_ACTIVE300+Highly engaged, consistent participation
ACTIVE200-299Regular participation, good attendance
MODERATE100-199Moderate engagement, average attendance
LOW_ACTIVITY50-99Below average participation
MINIMAL<50Very low engagement, risk indicator

Retention Risk Assessment

Risk LevelCriteriaAction Required
HIGH_RETIREMENT_RISK15+ years, age 60+, veteranSuccession planning critical
MODERATE_ATTRITION_RISK10+ years, <150 votes/yearEngagement support needed
EARLY_EXIT_RISK<3 years, <200 votes/yearOnboarding and support
ENGAGEMENT_RISKContinuity <60%, any durationRe-engagement strategies
LOW_RISKActive, high engagement, stableRetention 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 FrameworkUse CaseSupported GranularitiesLink
Temporal AnalysisTrack voting behavior changes over timeDaily, Weekly, Monthly, AnnualFramework Docs
Comparative AnalysisBenchmark politicians against peersAnnual, MonthlyFramework Docs
Pattern RecognitionDetect behavioral anomalies and clustersAll granularitiesFramework Docs
Predictive IntelligenceForecast future voting behavior and risksMonthly, AnnualFramework Docs

Risk Rules Supported: These views power most politician risk rules including:

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 functions
  • view_riksdagen_party_coalition_evolution - Party-pair alliance tracking with 35 coalition metrics
  • view_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

ColumnTypeDescriptionExample
partyVARCHAR(50)Party short code (primary key)'S', 'M', 'SD', 'C', 'V', 'KD', 'L', 'MP'
party_nameVARCHAR(255)Full party name'Socialdemokraterna'
party_english_nameVARCHAR(255)English translation'Social Democrats'
member_countINTEGERCurrent active members70
websiteVARCHAR(255)Official party website'https://www.socialdemokraterna.se'
registered_dateDATERegistration date'1889-04-23'
party_size_categoryVARCHAR(50)Classification'MAJOR', 'MEDIUM', 'SMALL'
bloc_alignmentVARCHAR(50)Political bloc'LEFT_BLOC', 'RIGHT_BLOC', 'INDEPENDENT'

Swedish Political Parties

CodeParty Name (Swedish)English NameBlocHistorical Seats
SSocialdemokraternaSocial DemocratsLEFT70-110
MModeraternaModerate PartyRIGHT68-107
SDSverigedemokraternaSweden DemocratsRIGHT*62-73
CCenterpartietCentre PartyRIGHT22-31
VVΓ€nsterpartietLeft PartyLEFT21-28
KDKristdemokraternaChristian DemocratsRIGHT19-25
LLiberalernaLiberalsRIGHT16-24
MPMiljΓΆpartietGreen PartyLEFT16-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_data and assignment_data
  • Party Registry: sweden_political_party for 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

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

ColumnTypeDescriptionExample
partyVARCHAR(50)Party code'S'
year_monthDATEMonth of analysis'2024-10-01'
active_membersINTEGERMembers active in voting68
avg_party_absence_rateNUMERIC(5,2)Average absence across members8.50
avg_party_win_rateNUMERIC(5,2)Average effectiveness72.30
avg_party_disciplineNUMERIC(5,2)Party cohesion (100 - rebel rate)94.20
total_documentsINTEGERDocuments produced this month145
interpellations_filedINTEGERQuestions to government23
motions_submittedINTEGERLegislative proposals67
committee_participationNUMERIC(5,2)Committee activity level88.50
absence_trendNUMERIC(5,2)Month-over-month change-1.20
effectiveness_trendNUMERIC(5,2)Win rate change+2.50
discipline_trendNUMERIC(5,2)Cohesion change+0.80
productivity_trendINTEGERDocument count change+12
ma_3month_effectivenessNUMERIC(5,2)3-month moving average71.80
party_performance_statusVARCHAR(50)Classification'STRONG_PERFORMANCE'
coalition_potential_scoreNUMERIC(5,2)Reliability metric (0-100)87.50

Performance Classifications

Party Performance Status:

  • EXCELLENT_PERFORMANCE: High effectiveness, low absence, high discipline
  • STRONG_PERFORMANCE: Above average across all metrics
  • MODERATE_PERFORMANCE: Average performance, some weaknesses
  • CONCERNING_PERFORMANCE: Multiple problematic indicators
  • POOR_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 decisions
  • document_proposal_container - Linkage structure
  • document_status_container - Status information
  • document_data - Document metadata and dates
  • document_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:

FrameworkApplicationExample Analysis
Temporal AnalysisTrack party effectiveness trends over timeMonthly approval rate trajectories
Comparative AnalysisParty-to-party effectiveness comparisonGovernment vs opposition success rates
Pattern RecognitionIdentify committee specializationsWhich parties succeed in which committees
Predictive IntelligenceForecast proposal outcomesBased on party sponsorship and committee
Coalition AnalysisAssess coalition alignment on decisionsDo 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_data has 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

ColumnTypeDescriptionExample
partyVARCHAR(50)Party short code (PK)'S', 'M', 'SD'
first_assignment_dateDATEFirst party assignment'2002-10-01'
last_assignment_dateDATEMost recent assignment'2024-12-15'
total_assignmentsBIGINTAll assignments across members2847
current_assignmentsBIGINTActive assignments156
total_days_servedBIGINTTotal service days (all roles)890456
total_days_served_parliamentBIGINTParliamentary service days456789
total_days_served_committeeBIGINTCommittee service days234567
total_days_served_governmentBIGINTGovernment service days123456
total_days_served_euBIGINTEU representative days12345
total_days_served_speakerBIGINTSpeaker role days5678
total_days_served_partyBIGINTParty leadership days45678
activeBOOLEANHas any active memberstrue
active_parliamentBOOLEANHas parliamentary memberstrue
active_governmentBOOLEANHas government membersfalse
active_committeeBOOLEANHas committee memberstrue
total_activeBIGINTCount of active members68
total_active_parliamentBIGINTActive parliamentarians68
total_active_governmentBIGINTActive government members0
total_active_committeeBIGINTActive committee members102
total_documentsBIGINTDocuments produced8542
avg_documents_per_memberNUMERICAvg docs per member125.62
total_party_motionsBIGINTParty-wide motions234
total_individual_motionsBIGINTIndividual member motions5678
very_high_activity_membersBIGINTMembers with >100 docs12
high_activity_membersBIGINTMembers with 50-100 docs23
medium_activity_membersBIGINTMembers with 10-49 docs28
low_activity_membersBIGINTMembers with <10 docs5
currently_active_membersBIGINTActive in last year64
total_documents_last_yearBIGINTDocs last 12 months1245
avg_documents_last_yearNUMERICAvg docs/member last year19.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_politician and document_data

πŸ”— Dependencies

Upstream:

  • view_riksdagen_politician - Individual politician aggregations
  • document_data - Document production metrics
  • document_status_container - Document linkage
  • document_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

  1. Party Scorecard Generation - Comprehensive party profiles with assignments, activity, and productivity
  2. Experience Assessment - Track party expertise in government, committees, parliament
  3. Member Activity Analysis - Identify high-performing and low-performing member distributions
  4. 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):

ColumnTypeDescriptionExample
partyVARCHAR(50)Party code'S'
election_cycle_idTEXTElection cycle'2018-2021'
semesterTEXTSemester'autumn', 'spring'

Core Metrics (14 columns):

ColumnTypeDescriptionExample
cycle_yearINTEGERYear in 4-year cycle (1-4)3
calendar_yearINTEGERActual year2024
total_ballotsBIGINTBallots in semester847
participation_rateNUMERICAttendance %92.5
win_rateNUMERICWin % on ballots67.8
approval_rateNUMERICDecision approval %71.2
active_membersBIGINTMember count68
documents_last_yearBIGINTDocuments produced1245
avg_rebel_rateNUMERICParty dissent rate3.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_discipline
  • percentile_win_rate, percentile_participation, percentile_approval, percentile_productivity
  • quartile_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_approval
  • next_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_absolute
  • membership_change, approval_rate_change, documents_change, discipline_change

Trajectory Classifications (2 columns):

  • trajectory_win_rate: ASCENDING, RECOVERING, STABLE, DECLINING, DESCENDING, BASELINE
  • trajectory_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_party
  • volatility_classification: HIGH_VOLATILITY, MODERATE_VOLATILITY, LOW_VOLATILITY
  • stability_classification: UNSTABLE, MODERATELY_STABLE, STABLE

Predictive Indicators (4 columns):

  • forecast_trend: EXPECTED_IMPROVEMENT, EXPECTED_DECLINE, EXPECTED_STABLE, NO_FORECAST
  • trend_deviation_from_ma (vs 3-semester moving average)
  • trend_position: UNDERPERFORMING_VS_TREND, ON_TREND, OVERPERFORMING_VS_TREND
  • trajectory_confidence_score (0-100)

Performance Tiers (2 columns):

  • performance_tier: ELITE_PERFORMER, STRONG_PERFORMER, MODERATE_PERFORMER, WEAK_PERFORMER
  • productivity_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 performance
  • view_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

  1. Election Forecasting - Project seat counts based on historical trends and moving averages
  2. Electoral Risk Assessment - Identify parties with high volatility and seat loss warnings
  3. Pre-Election Analysis - Measure party readiness and campaign momentum
  4. Post-Election Evaluation - Compare predicted vs actual electoral outcomes
  5. Coalition Viability - Assess party sizes for government formation scenarios
  6. Trend Analysis - Track long-term growth/decline patterns across cycles
  7. 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 CategoryGranularityMaterializedRefreshUse Case
Ballot SummariesDaily/Weekly/Monthly/Annualβœ“Daily 02:00Overall chamber statistics
Party SummariesDaily/Weekly/Monthly/Annualβœ“Daily 02:00Party performance tracking
Politician SummariesDaily/Weekly/Monthly/Annualβœ“Daily 02:00Individual MP monitoring

Common Metrics Across All Vote Views

MetricDescriptionCalculation
ballot_countNumber of votesCOUNT(DISTINCT ballot_id)
yes_votesTotal "Ja" votesSUM(CASE vote = 'Ja')
no_votesTotal "Nej" votesSUM(CASE vote = 'Nej')
abstain_votesTotal "AvstΓ₯r" votesSUM(CASE vote = 'AvstΓ₯r')
absent_votesTotal absencesSUM(CASE vote = 'FrΓ₯nvarande')
absence_ratePercentage absent100.0 * absent / total
win_ratePercentage on winning side100.0 * wins / participated
rebel_ratePercentage against party100.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

ColumnTypeDescriptionExample
vote_dateDATEVoting date'2024-10-15'
intressent_idVARCHAR(255)Politician ID'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Party affiliation'S'
ballot_countINTEGERBallots this day12
yes_votesINTEGER"Ja" votes7
no_votesINTEGER"Nej" votes4
abstain_votesINTEGERAbstentions0
absent_votesINTEGERTimes absent1
total_votesINTEGERTotal voting opportunities12
absence_rateNUMERIC(5,2)Daily absence percentage8.33
win_rateNUMERIC(5,2)Percentage on winning side75.00
rebel_rateNUMERIC(5,2)Percentage against party5.00
party_consensus_agreeINTEGERVotes with party consensus10
party_consensus_disagreeINTEGERVotes against party consensus1

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:

FrameworkViewSupporting ViewsRisk RulesOperational
Temporal Analysisview_election_cycle_temporal_trends35 views20+ rules100%
Comparative Analysisview_election_cycle_comparative_analysis26 views15+ rules100%
Predictive Intelligenceview_election_cycle_predictive_intelligence14 views8/8 rules100%
Network Analysisview_election_cycle_network_analysis11 views3/4 rules75%
Decision Intelligenceview_election_cycle_decision_intelligence5 views5/5 rules100%
Pattern Recognitionview_election_cycle_anomaly_pattern23 views12/13 rules92%

View Inventory

View NameFrameworkIntelligence ValueDescription
view_election_cycle_temporal_trendsTemporal Analysis⭐⭐⭐⭐⭐Attendance, ballots, violations by cycle/semester
view_election_cycle_comparative_analysisComparative Analysis⭐⭐⭐⭐⭐Party-level metrics comparison by cycle/semester
view_election_cycle_predictive_intelligencePredictive Intelligence⭐⭐⭐⭐⭐Risk forecasts and trajectory analysis by cycle
view_election_cycle_network_analysisNetwork Analysis⭐⭐⭐⭐⭐Coalition alignment structure by election cycle
view_election_cycle_decision_intelligenceDecision Intelligence⭐⭐⭐⭐⭐Proposal success rates and effectiveness by cycle
view_election_cycle_anomaly_patternPattern Recognition⭐⭐⭐⭐⭐Anomaly detection and risk pattern aggregation by cycle

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

ColumnTypeDescriptionExample
election_cycle_idTEXTElection cycle identifier'2018-2022', '2022-2026'
cycle_yearINTEGERYear within 4-year cycle (1-4)3
calendar_yearINTEGERActual calendar year2024
semesterTEXTSemester (autumn/spring)'spring'
is_pre_election_semesterBOOLEANTRUE for final spring before electiontrue
months_until_electionINTEGERCountdown to next election6
active_politiciansBIGINTCount of active politicians349
avg_attendance_rateNUMERIC(5,2)Average attendance percentage87.50
total_ballotsBIGINTTotal ballots in period1250
total_votesBIGINTTotal votes cast425000
avg_win_rateNUMERIC(5,2)Average win rate percentage45.80
avg_rebel_rateNUMERIC(5,2)Average rebel rate percentage12.30
violation_countBIGINTTotal violations detected45
distinct_ballotsBIGINTCount of unique ballots1200

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

ColumnTypeDescription
election_cycle_idTEXTElection cycle identifier
cycle_yearINTEGERYear within cycle (1-4)
semesterTEXTSemester (autumn/spring)
partyTEXTPolitical party abbreviation
total_votes_partyBIGINTTotal party votes
avg_yes_percentageNUMERIC(5,2)Average yes vote percentage
avg_absence_percentageNUMERIC(5,2)Average absence rate
avg_rebel_percentageNUMERIC(5,2)Average rebellion rate
party_member_countBIGINTActive 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

ColumnTypeDescription
risk_forecast_categoryTEXTPredicted risk level
politicians_at_riskBIGINTCount with escalating risk
avg_risk_score_changeNUMERIC(5,2)Average risk delta
predicted_high_absenteeismBIGINTForecast attendance issues
predicted_coalition_volatilityBIGINTHigh 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

ColumnTypeDescription
party_aTEXTFirst party in pair
party_bTEXTSecond party in pair
alignment_scoreNUMERIC(5,2)Voting alignment percentage
coalition_strengthTEXTStrength 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

ColumnTypeDescription
partyTEXTPolitical party
total_proposalsBIGINTTotal proposals submitted
approved_proposalsBIGINTSuccessfully approved proposals
avg_approval_rateNUMERIC(5,2)Approval success percentage
decision_effectivenessTEXTEffectiveness 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

ColumnTypeDescription
election_cycle_idTEXTElection cycle identifier (e.g., '2018-2022')
anomaly_typeTEXTPattern classification type
politician_count_with_riskBIGINTPoliticians with HIGH/CRITICAL risk severity
avg_risk_scoreNUMERIC(5,2)Average risk score across cycle
risk_escalationsBIGINTCount of risk severity escalations
high_anomaly_countBIGINTFrequent/consistent rebel count
avg_total_rebellionsNUMERIC(5,2)Average rebellion count
strong_consensus_rebelsBIGINTPoliticians with 5+ strong consensus rebellions
avg_risk_score_prsNUMERIC(5,2)Average risk score from politician risk summary
high_risk_politiciansBIGINTHIGH/CRITICAL risk level politicians
risk_trendTEXTRisk trajectory (escalating/improving/stable)
anomaly_accelerationBIGINTChange 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 TypeExamplesPurpose
Behavioral Trendspolitician_behavioral_trends, party_effectiveness_trendsTime-series performance tracking
Risk Assessmentrisk_score_evolution, politician_risk_summaryAutomated risk scoring
Coalition Analysiscoalition_alignment_matrixGovernment formation forecasting
Network Intelligencepolitician_influence_metricsPower structure mapping
Dashboard Aggregationriksdagen_intelligence_dashboardUnified intelligence products
Crisis Analysiscrisis_resilience_indicatorsCrisis period performance assessment
Anomaly Detectionvoting_anomaly_detectionBehavioral 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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Party affiliation'S'
statusVARCHAR(100)Current status'TjΓ€nstgΓΆrande riksdagsledamot'
crisis_period_votesBIGINTVotes during crisis periods145
crisis_definitive_votesBIGINTDefinitive votes (Ja/Nej) in crisis132
crisis_absencesBIGINTAbsences during crisis13
crisis_absence_rateDOUBLE PRECISIONCrisis absence rate (0.0-1.0)0.090 (9%)
normal_votesBIGINTVotes during normal periods320
normal_absencesBIGINTAbsences during normal periods28
normal_absence_rateDOUBLE PRECISIONNormal absence rate (0.0-1.0)0.088 (8.8%)
absence_deltaDOUBLE PRECISIONCrisis - Normal absence rate0.002 (0.2%)
aligned_crisis_votesBIGINTVotes aligned with party in crisis125
crisis_party_alignment_rateDOUBLE PRECISIONParty discipline in crisis (0.0-1.0)0.947 (94.7%)
resilience_scoreNUMERIC(10,2)Overall resilience score (0-100)87.5
resilience_classificationTEXTResilience level'HIGHLY_RESILIENT'
attendance_resilienceTEXTAttendance-specific resilience'RESILIENT'
discipline_resilienceTEXTDiscipline-specific resilience'HIGHLY_RESILIENT'

Crisis Period Detection

Algorithm:

  1. Calculate average monthly ballot count (last 2 years)
  2. Identify months with ballot count >150% of average as "crisis periods"
  3. Remaining months classified as "normal periods"
  4. 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 RangeClassificationDescription
90-100HIGHLY_RESILIENTExcellent crisis performance
75-89RESILIENTGood crisis performance
60-74MODERATE_RESILIENCEAdequate crisis performance
45-59VULNERABLEBelow average crisis performance
0-44LOW_RESILIENCEPoor 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

  1. Government Formation: Assess coalition partner reliability under pressure
  2. Ministry Appointments: Identify crisis-capable ministers
  3. Early Warning: Detect politicians who crack under pressure
  4. Party Strength: Evaluate party discipline during crises
  5. 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

ColumnTypeDescriptionExample
parties_gaining_momentumBIGINTParties with positive trend direction3
parties_losing_momentumBIGINTParties with negative trend direction2
volatile_partiesBIGINTParties with volatile/highly volatile classification1
high_probability_coalitionsBIGINTCoalition pairs with strong likelihood4
cross_bloc_alliancesBIGINTStrong/moderate cross-bloc coalitions2
high_defection_risksBIGINTPoliticians with frequent/consistent rebel pattern5
low_discipline_politiciansBIGINTAll politicians with rebel pattern (moderate+)12
power_brokersBIGINTPoliticians with strong/moderate broker classification8
highly_connected_politiciansBIGINTPoliticians with highly influential classification6
crisis_ready_politiciansBIGINTPoliticians with highly resilient classification45
low_resilience_politiciansBIGINTPoliticians with low resilience classification8
stability_assessmentTEXTOverall political stability classification'STABLE_POLITICAL_ENVIRONMENT'
coalition_assessmentTEXTCoalition landscape assessment'STABLE_COALITION_PATTERNS'
latest_vote_dataDATEMost recent voting data timestamp'2024-11-15'
ballots_last_30_daysBIGINTRecent voting activity indicator42
intelligence_report_timestampTIMESTAMPReport 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):

  1. view_riksdagen_party_momentum_analysis - Party trend analysis
  2. view_riksdagen_coalition_alignment_matrix - Coalition probabilities
  3. view_riksdagen_voting_anomaly_detection - Rebel/discipline patterns
  4. view_riksdagen_politician_influence_metrics - Network analysis
  5. view_riksdagen_crisis_resilience_indicators - Crisis performance
  6. vote_data table - 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

  1. Executive Briefings: Single-view intelligence snapshot for leadership
  2. Situation Room: Real-time political stability monitoring
  3. Early Warning System: Detect instability before it manifests
  4. Coalition Formation: Assess viability of potential government coalitions
  5. Risk Dashboards: Feed executive intelligence dashboards
  6. API Endpoints: Power real-time intelligence APIs
  7. 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

ColumnTypeDescriptionExample
person_idVARCHAR(255)Politician identifier'0532213467925'
first_nameVARCHAR(255)Politician first name'Anna'
last_nameVARCHAR(255)Politician last name'Andersson'
partyVARCHAR(50)Party affiliation'S'
year_monthDATEMonth of assessment'2024-10-01'
risk_scoreINTEGERTotal risk points85
risk_severityVARCHAR(50)Classification'MAJOR'
active_violationsINTEGERCurrent rule violations3
absence_riskINTEGERAbsence-related points30
effectiveness_riskINTEGEREffectiveness-related points25
discipline_riskINTEGERDiscipline-related points15
productivity_riskINTEGERProductivity-related points15
risk_trendINTEGERMonth-over-month change+12
risk_velocityINTEGERAcceleration of risk growth+5
ma_3month_riskNUMERIC(10,2)3-month moving average78.50
risk_trajectoryVARCHAR(50)Trend classification'ESCALATING'

Risk Score Calculation

Total Risk Score = Sum of risk category points:

Risk CategoryMax PointsCalculation Basis
Absence Risk0-100Absence rate Γ— multiplier + trend weighting
Effectiveness Risk0-100(100 - win_rate) Γ— multiplier + trend weighting
Discipline Risk0-100Rebel rate Γ— multiplier + party impact factor
Productivity Risk0-100Document deficit Γ— multiplier

Risk Severity Thresholds:

SeverityScore RangeDescription
MINOR10-49Early warning, monitor
MAJOR50-99Significant concern, investigate
CRITICAL100+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_date for 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

  1. Forecast Legislative Activity: Predict decision volumes for upcoming months based on moving average trends
  2. Detect Anomalous Decision Volumes: Identify bottlenecks or unusual activity through z-score analysis
  3. Compare to Historical Baselines: Year-over-year comparison to assess if current session is above/below normal
  4. Identify Seasonal Patterns: Resource planning based on parliamentary calendar patterns
  5. Trend Detection: Moving average crossovers signal acceleration or deceleration in legislative activity
  6. 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
  • 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

LevelViewsDescription
Level 0Source TablesRaw data (person_data, vote_data, document_data, etc.)
Level 1Base ViewsDirect table aggregations (politician, party, committee)
Level 2Vote SummariesDaily/weekly/monthly/annual aggregations (materialized)
Level 3Experience & ProductivityComplex aggregations with business logic
Level 4Intelligence ViewsAdvanced analytics combining multiple sources
Level 5Dashboard ViewsUnified 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 CategoryIndexed ColumnsUse Case
Vote Summariesvote_date, person_id, partyTemporal + entity filtering
Behavioral Trendsyear_month, person_id, partyTime-series queries
Document Viewsmade_public_date, person_id, org_codeProductivity tracking
Risk Evolutionyear_month, person_id, risk_severityRisk 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+):

ViewRefresh SchedulePerformance Gain
view_riksdagen_vote_data_ballot_summary_dailyDaily 02:00 UTC50-200x
view_riksdagen_vote_data_ballot_party_summary_dailyDaily 02:00 UTC30-100x
view_riksdagen_vote_data_ballot_politician_summary_dailyDaily 02:00 UTC100-500x
Committee decision viewsDaily 02:00 UTC20-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_mat
  • view_party_effectiveness_trends_mat
  • view_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 NameColumnsViews OptimizedPerformance Gain
idx_vote_summary_daily_date_personvote_date DESC, intressent_idPolitician behavioral trends, daily summaries10-100x
idx_vote_summary_daily_party_dateparty, vote_date DESCParty effectiveness trends20-80x
idx_rule_violation_date_resourcedetected_date DESC, reference_idRisk score evolution5-50x
idx_politician_document_date_orgmade_public_date DESC, person_id, orgDocument productivity10-50x
idx_document_data_ministry_dateorg, made_public_date DESCMinistry effectiveness10-50x
idx_assignment_data_person_roleperson_id, role_code, from_dateExperience summary20-100x

Query Performance Benchmarks

Query PatternTypical Response TimeOptimization Notes
Single politician lookup<10msIndexed on person_id
Party comparison (8 parties)50-100msUse current month only
12-month trend analysis100-200msFilter by date range
Coalition matrix (all pairs)200-400msCandidate for materialization
Risk score evolution (all politicians)150-300msUse date filters + LIMIT
Full behavioral trends (36 months)500ms-2sAvoid 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 RuleRule IDSupported By ViewsMetrics Used
PoliticianLazyP-01view_politician_behavioral_trendsavg_absence_rate, attendance_status
PoliticianIneffectiveVotingP-02view_politician_behavioral_trendsavg_win_rate, effectiveness_status
PoliticianHighRebelRateP-03view_politician_behavioral_trendsavg_rebel_rate, discipline_status
PoliticianDecliningEngagementP-04view_politician_behavioral_trendsAll trend metrics (absence_trend, etc.)
PoliticianCombinedRiskP-05view_risk_score_evolutionrisk_score, behavioral_assessment
PoliticianLowProductivityP-06view_riksdagen_politician_documentDocument counts by type
PartyWeakSupportY-01view_party_effectiveness_trendsavg_party_win_rate, effectiveness metrics
PartyCoalitionUnstableY-02view_riksdagen_coalition_alignment_matrixalignment_rate, coalition_likelihood
PartyLowDisciplineY-03view_party_effectiveness_trendsavg_party_discipline
PartyIsolatedY-05view_riksdagen_coalition_alignment_matrixLow alignment rates across all parties

Intelligence Frameworks Mapping

Views implementing frameworks from DATA_ANALYSIS_INTOP_OSINT.md:

FrameworkDescriptionImplementing Views
Temporal AnalysisTime-series tracking, trendsview_politician_behavioral_trends, view_party_effectiveness_trends, all vote summaries
Comparative AnalysisEntity comparison, benchmarkingview_riksdagen_politician, view_riksdagen_party, all summary views
Pattern RecognitionBehavioral classification, clusteringview_politician_behavioral_trends, view_risk_score_evolution
Predictive IntelligenceForecasting, trend extrapolationview_risk_score_evolution, trend metrics in behavioral views
Network AnalysisRelationship mappingview_riksdagen_coalition_alignment_matrix (partial implementation)
Coalition AnalysisGovernment formation scenariosview_riksdagen_coalition_alignment_matrix, party alignment views

Product Feature Mapping

Views supporting features from BUSINESS_PRODUCT_DOCUMENT.md:

Product LineFeatureSupporting Views
Product Line 1: Core IntelligencePolitician Dashboardview_riksdagen_politician, view_politician_behavioral_trends, view_riksdagen_politician_experience_summary
Product Line 1: Core IntelligenceParty Dashboardview_riksdagen_party, view_party_effectiveness_trends
Product Line 2: Advanced AnalyticsPerformance TrendsAll behavioral trend views, vote summary views
Product Line 2: Advanced AnalyticsComparative AnalysisAll base views (politician, party, committee)
Product Line 3: Risk IntelligenceRisk Assessment Feedview_risk_score_evolution, view_politician_behavioral_trends
Product Line 3: Risk IntelligenceEarly Warning SystemTrend metrics in all intelligence views
Product Line 4: Coalition ToolsCoalition Scenariosview_riksdagen_coalition_alignment_matrix
Product Line 4: Coalition ToolsGovernment Formationview_riksdagen_party, coalition alignment matrix

Appendices

Appendix A: View Naming Conventions

Standard Patterns:

  • view_riksdagen_*: Swedish Parliament (Riksdagen) related views
  • view_*_summary: Aggregation views (counts, averages)
  • view_*_daily: Daily granularity materialized views
  • view_*_weekly: Weekly granularity materialized views
  • view_*_monthly: Monthly granularity materialized views
  • view_*_annual: Annual granularity materialized views
  • view_*_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 TermEnglish TranslationContext
RiksdagenThe Swedish ParliamentLegislative body, 349 seats
InterpellationInterpellationQuestion to minister requiring debate
MotionMotionLegislative proposal by MP
UtskottCommitteeSpecialized parliamentary committee
TjΓ€nstgΓΆrande riksdagsledamotServing member of parliamentActive MP status
FrΓ₯nvarandeAbsentAbsent from vote
AvstΓ₯rAbstainAbstention vote
JaYesAffirmative vote
NejNoNegative 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:

  1. Product Line Revenue (€630K + €855K + €1.77M + €525K = €3.78M): Individual product line subscription revenues
  2. 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)

ViewProduct FeatureJSON SchemaAPI EndpointMarket SegmentRevenue Tier
view_riksdagen_politicianPolitician Profilespolitician-schema.mdGET /api/v1/politiciansAll segmentsPro €99/mo
view_riksdagen_politician_summaryPolitician Scorecardspolitician-schema.md#intelligenceGET /api/v1/politicians/{id}Political ConsultingEnterprise €330/mo
view_riksdagen_partyParty Performance Dataparty-schema.mdGET /api/v1/partiesMedia & JournalismPro €99/mo
view_riksdagen_party_summaryParty Analyticsparty-schema.md#performanceGET /api/v1/parties/{id}Political ConsultingEnterprise €330/mo
view_riksdagen_vote_data_ballot_summaryVoting Statisticspolitician-schema.md#votingGET /api/v1/votes/{ballot_id}Academic ResearchAcademic €50/mo
view_riksdagen_vote_data_ballot_politician_summaryIndividual Voting Recordspolitician-schema.md#votingGET /api/v1/politicians/{id}/votingAll segmentsPro €99/mo
view_rule_violationRisk Assessment Feedintelligence-schema.mdGET /api/v1/politicians/{id}/riskPolitical ConsultingPremium 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

ViewDashboard ComponentData SchemaMarket SegmentPricing Tier
view_riksdagen_politician_rankingPolitical Scorecardspolitician-schema.md#intelligenceCorporate AffairsProfessional €6K/mo
view_riksdagen_coalition_alignment_matrixCoalition Stability Monitorparty-schema.md#coalitionPolitical PartiesEnterprise €15K/mo
view_party_effectiveness_trendsParty Performance Dashboardparty-schema.md#intelligenceNGOs & AdvocacyProfessional €6K/mo
view_politician_behavioral_trendsBehavioral Analyticsintelligence-schema.mdCorporate AffairsEnterprise €15K/mo
view_riksdagen_committee_decisionsCommittee Activity Trackercommittee-schema.mdAll segmentsProfessional €6K/mo
view_ministry_effectiveness_trendsGovernment Performance Monitorministry-schema.mdCorporate AffairsEnterprise €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

ViewRisk Intelligence ProductIntelligence ValueMarket SegmentPremium Tier
view_rule_violationRisk Assessment Feed⭐⭐⭐⭐⭐Political Consulting€5,900/mo
view_politician_risk_summaryPolitician Risk Profiles⭐⭐⭐⭐⭐Corporate Affairs€5,900/mo
view_riksdagen_voting_anomaly_detectionVoting Anomaly Alerts⭐⭐⭐⭐⭐Political Parties€5,900/mo
view_risk_score_evolutionRisk Trend Analysis⭐⭐⭐⭐⭐Political Consulting€5,900/mo
view_ministry_risk_evolutionGovernment 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

ViewReport TemplateOutput FormatMarket SegmentFeature Tier
view_riksdagen_politician_experience_summaryExperience Analysis ReportPDF, ExcelAcademic ResearchStarter €2K/mo
view_riksdagen_party_ballot_support_annual_summaryCoalition Analysis ReportPDF, PPTPolitical ConsultingProfessional €6K/mo
view_committee_productivity_matrixCommittee Performance ReportExcel, PDFNGOs & AdvocacyProfessional €6K/mo
view_riksdagen_politician_document_summaryLegislative Productivity ReportPDF, ExcelMedia & JournalismStarter €2K/mo

Business Documentation: BUSINESS_PRODUCT_DOCUMENT.md#product-line-4


Cross-Product Feature Matrix

Feature CategoryViews Used (Count)Product LinesAnnual RevenueCustomer Segments
Politician Intelligence8 core views1, 2, 3, 4€1.2MAll segments
Party & Coalition Analysis6 core views1, 2, 3, 4€800KPolitical focus
Risk Assessment5 specialized views2, 3€1.8MConsulting, Corporate
Government Performance4 ministry views2, 3, 4€400KCorporate Affairs
Committee & Legislative12 committee views1, 2, 4€300KAcademic, NGO
Voting & Ballot Analysis20 vote views1, 2, 3€600KAll segments

JSON Schema Integration Reference

All views are exported via JSON API with standardized schemas. See complete specifications:

API Documentation: json-export-specs/README.md
Example Responses: json-export-specs/examples/


Appendix D: Party Code Reference

CodeFull Name (Swedish)English NameIdeologyHistoric Seats Range
SSocialdemokraternaSocial DemocratsSocial democracy70-130
MModeraternaModerate PartyLiberal conservatism60-110
SDSverigedemokraternaSweden DemocratsNational conservatism20-80
CCenterpartietCentre PartyAgrarian liberalism20-35
VVΓ€nsterpartietLeft PartyDemocratic socialism15-30
KDKristdemokraternaChristian DemocratsChristian democracy15-30
LLiberalernaLiberalsSocial liberalism15-30
MPMiljΓΆpartietGreen PartyGreen politics15-30

Appendix E: Database Maintenance Schedule

TaskFrequencyTime (UTC)Purpose
Materialized View RefreshDaily02:00Update vote/document aggregations
Index MaintenanceWeeklySunday 03:00REINDEX for performance
Statistics UpdateDaily02:30Update query planner statistics (ANALYZE)
Liquibase MigrationsOn deploymentVariesSchema evolution
BackupDaily04:00Full 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 analysis
  • view_ministry_effectiveness_detailed: Ministry performance with budget correlation
  • view_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 queries
  • view_party_effectiveness_trends_mat: Materialized party performance
  • view_risk_score_evolution_mat: Materialized risk tracking
  • view_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:

Related Documentation:

Contact:


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:

VersionDateChangesAuthor
1.02025-11-17Initial comprehensive catalog creationIntelligence Operative
1.12025-11-20Validation & 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 documentationIntelligence Operative
2.02025-11-21Complete 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.12025-11-25Business 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 SpecsIntelligence Operative (Copilot Agent)
2.22025-12-10Validation 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.02026-04-05Full 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 discrepancyCode 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:

  1. Executive Summary Updated: Changed "80+ database views" claim to accurate "80 database views" with transparent coverage statistics
  2. Complete View Inventory Added: New comprehensive section listing all 80 views with basic descriptions, types (standard/materialized), and intelligence value ratings
  3. Validation Metadata Added: Added "Last Validated Against Schema" date to document metadata
  4. Validation History Section: Comprehensive validation documentation now in dedicated section (see Validation History)
  5. 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:

  1. High-Priority Views (Intelligence, Ministry, Risk): Detailed documentation with complex use cases
  2. Core Analytical Views (Party, Politician, Committee): Structured documentation with sample queries
  3. Supporting Views (Vote Summaries, Documents, Audit): Concise structured documentation
  4. 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:

  1. View Documentation Enhanced: Added business context sections to high-value views including:

    • view_riksdagen_politician: €15M TAM (Political Consulting), JSON spec integration
    • view_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
  2. 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
  3. Related Documentation Updated:

  4. 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

ColumnTypeDescriptionExample
yearINTEGERCalendar year extracted from made_public_date2022
documents_producedBIGINTTotal unique documents published in year5,678
motions_filedBIGINTTotal motions filed in year2,345
proposals_submittedBIGINTTotal proposals submitted in year567
first_document_dateDATEEarliest document publication date'2022-01-01'
last_document_dateDATELatest 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 year column (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

ColumnTypeDescriptionExample
yearINTEGERCalendar year extracted from vote_date2022
total_ballotsBIGINTTotal unique ballots voted on in year1,250
total_votesBIGINTTotal individual votes cast in year435,750
avg_attendance_rateNUMERICAverage attendance percentage87.50
active_politiciansBIGINTUnique politicians who voted in year349
first_vote_dateDATEEarliest vote date in year'2022-01-01'
last_vote_dateDATELatest 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 year column (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';

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

ColumnTypeDescriptionExample
decision_dayDATECalendar date of decisions'2024-03-15'
daily_decisionsBIGINTTotal decisions on this day42
daily_approval_rateNUMERICApproval percentage for the day78.50
approved_decisionsBIGINTApproved decisions count33
rejected_decisionsBIGINTRejected decisions count7
referred_back_decisionsBIGINTReferred back to committee2
ma_7day_decisionsNUMERIC7-day moving average of decisions38.71
ma_30day_decisionsNUMERIC30-day moving average of decisions35.20
ma_90day_decisionsNUMERIC90-day moving average of decisions32.15
ma_30day_approval_rateNUMERIC30-day moving avg approval rate75.30
yoy_decisions_changeBIGINTYear-over-year decision count delta+5
yoy_decisions_change_pctNUMERICYear-over-year percentage change13.51
parliamentary_periodTEXTSession classification'Autumn Session'
decision_quarterTEXTQuarter 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_day column

Dependencies

Source Tables (via view_decision_temporal_trends):

  • document_proposal_data - Proposal chamber decisions
  • document_proposal_container - Proposal containers
  • document_status_container - Document status linkage
  • document_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

ColumnTypeDescriptionExample
ministry_codeTEXTGovernment ministry identifier'Fi'
committeeTEXTParliamentary committee'FiU'
decision_typeTEXTType of decision'prop'
decision_quarterTIMESTAMPQuarter start date'2024-01-01'
decision_yearNUMERICCalendar year2024
quarter_numNUMERICQuarter number (1-4)1
total_proposalsBIGINTTotal proposals in group15
approved_proposalsBIGINTApproved proposal count12
rejected_proposalsBIGINTRejected proposal count2
referred_back_proposalsBIGINTReferred back count1
approval_rateNUMERICApproval percentage80.00
rejection_rateNUMERICRejection percentage13.33
committee_referral_rateNUMERICCommittee referral percentage0.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 linkage
  • document_proposal_container - Proposal containers
  • document_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

ColumnTypeDescriptionExample
partyTEXTPolitical party short code'S'
committeeTEXTParliamentary committee'FiU'
decision_typeTEXTType of decision'mot'
committee_orgTEXTOriginating organization'Fi'
decision_monthTIMESTAMPMonth start date'2024-03-01'
decision_yearNUMERICCalendar year2024
decision_month_numNUMERICMonth number (1-12)3
total_proposalsBIGINTTotal proposals in group8
approved_proposalsBIGINTApproved proposal count5
rejected_proposalsBIGINTRejected proposal count2
referred_back_proposalsBIGINTReferred back count1
approval_rateNUMERICApproval percentage62.50
rejection_rateNUMERICRejection percentage25.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 decisions
  • document_proposal_container - Proposal containers
  • document_status_container - Document status linkage
  • document_data - Document dates
  • document_person_reference_co_0 - Person references
  • document_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

ColumnTypeDescriptionExample
yearINTEGERCalendar year2022
is_election_yearBOOLEANElection year flagtrue
total_ballotsBIGINTTotal ballots cast1,234
active_politiciansBIGINTActive politicians349
attendance_rateNUMERICAttendance percentage87.50
documents_producedBIGINTTotal documents5,678
motions_filedBIGINTMotions filed2,345
proposals_filedBIGINTProposals filed567
election_median_ballotsNUMERICElection year median1,200.00
election_avg_ballotsNUMERICElection year average1,250.00
midterm_avg_ballotsNUMERICMidterm year average1,100.00
ballot_ratio_vs_midtermNUMERICElection/midterm ratio1.12
ballot_z_score_vs_election_avgNUMERICZ-score vs election avg0.85
year_classificationTEXTActivity 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_date
  • document_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

ColumnTypeDescriptionExample
period_typeTEXTPeriod classification'ELECTION_YEARS'
avg_ballotsNUMERICAverage ballots1,250.50
avg_documentsNUMERICAverage documents5,678.00
avg_motionsNUMERICAverage motions2,345.00
avg_proposalsNUMERICAverage proposals567.00
avg_attendanceNUMERICAverage attendance rate87.50
avg_active_politiciansNUMERICAvg active politicians349.00
year_countBIGINTNumber of years7
yearsTEXTYear array (as string)'{2002,2006,2010,2014,2018,2022,2026}'
min_ballotsNUMERICMinimum ballots1,100.00
max_ballotsNUMERICMaximum ballots1,400.00
stddev_ballotsNUMERICStandard deviation95.50

Row Structure

The view returns exactly 3 rows:

  1. ELECTION_YEARS: Aggregate statistics for 7 election years (2002, 2006, 2010, 2014, 2018, 2022, 2026)
  2. MIDTERM_YEARS: Aggregate statistics for 17 midterm years (all other years 2002-2026)
  3. 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

ColumnTypeDescriptionExample
yearINTEGERElection year2022
total_ballotsBIGINTTotal ballots cast1,400
documents_producedBIGINTDocuments produced6,500
motions_filedBIGINTMotions filed2,800
ballot_z_score_vs_election_avgNUMERICBallot z-score2.35
doc_z_score_vs_election_avgNUMERICDocument z-score1.85
motion_z_scoreNUMERICMotion z-score1.65
has_ballot_anomalyBOOLEANBallot anomaly flagtrue
has_doc_anomalyBOOLEANDocument anomaly flagtrue
anomaly_countINTEGERTotal anomalies2
anomaly_typesTEXTAnomaly dimensions'BALLOT,DOCUMENT'
anomaly_severityTEXTSeverity level'HIGH'
max_z_scoreNUMERICMaximum z-score2.35
anomaly_directionTEXTActivity direction'ELEVATED_ACTIVITY'
year_classificationTEXTActivity 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-scores
  • NORMAL: 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 PatternCountDescription
view_*_sample.csv84View sample data - All 84 documented views
table_*_sample.csv54Table sample data
distribution_*.csv43Statistical distributions
distinct_*_values.csv9Distinct value sets
Metadata files (*.csv)11Manifests, statistics, mappings
Total200Complete 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 NameReasonStatus
view_riksdagen_coalition_alignment_matrixEmpty or very large - no rows returnedSchema exists, no sample CSV
view_riksdagen_voting_anomaly_detectionEmpty due to status value mismatchSchema exists, no sample CSV
view_riksdagen_intelligence_dashboardSingle-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

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:

ColumnTypeDescriptionExample
yearintegerCalendar year2022
quarterintegerQuarter (1-4)4
is_election_yearbooleanElection year flagtrue
total_ballotsbigintBallot count450
total_documentsbigintDocument count1200
attendance_ratenumericAverage attendance %92.5
ballot_z_scorenumericZ-score vs baseline1.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:

ColumnTypeDescriptionExample
yearintegerCalendar year2022
is_election_yearbooleanElection year flagtrue
q4_ballotsbigintQ4 ballot count180
q4_documentsbigintQ4 document count520
baseline_ballotsnumericNon-election Q4 average120
surge_rationumericActivity ratio vs baseline1.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:

ColumnTypeDescriptionExample
yearintegerCalendar year2022
quarterintegerQuarter (1-4)4
anomaly_typetextType of anomalyBALLOT_SURGE
z_scorenumericStatistical deviation2.3
severitytextSeverity levelHIGH
directiontextActivity directionELEVATED

πŸ’‘ 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

⭐⭐⭐⭐ High Intelligence Value

πŸ“‹ Purpose: Tracks politician activity trends approaching election dates across multiple behavioral dimensions to detect election-driven behavioral shifts.

πŸ“Š Key Columns:

ColumnTypeDescriptionExample
person_idtextPolitician identifierp123456
election_yearintegerUpcoming election year2022
months_to_electionintegerMonths until election6
ballot_participationnumericVoting participation rate95.2
document_productionbigintDocument count45
activity_trendtextTrend classificationINCREASING

πŸ’‘ 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:

ColumnTypeDescriptionExample
yearintegerCalendar year2022
is_election_yearbooleanElection year flagtrue
q4_ballotsbigintQ4 ballot count180
q4_documentsbigintQ4 document count520
party_effectivenessnumericParty performance score87.5
committee_productivitynumericCommittee output metric92.0
activity_z_scorenumericMulti-dimensional z-score1.9
classificationtextActivity classificationELEVATED

πŸ’‘ 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:

ColumnTypeDescriptionExample
yearintegerCalendar year2022
quarterintegerQuarter (1-4)4
is_election_yearbooleanElection year flagtrue
quarterly_ballotsbigintQuarter ballot count180
qoq_ballot_changenumericQuarter-over-quarter % change15.5
pattern_typetextSeasonal patternQ4_SURGE
activity_clusterintegerNTILE cluster (1-4)4
z_scorenumericCross-year deviation1.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:

ColumnTypeDescriptionExample
person_idtextPolitician identifierp123456
career_levelintegerCareer progression level (1-10)7
current_roletextCurrent positionCommittee Chair
years_in_parliamentnumericTotal parliamentary years12.5
role_transitionsintegerNumber of role changes5
advancement_ratenumericCareer velocity metric0.56
seniority_rankintegerRanking within cohort15

πŸ’‘ 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