How to build “Star Rating” report in BigQuery (or sparklines, or color gradients)

后端 未结 5 1170
忘了有多久
忘了有多久 2021-02-03 14:44

Suppose I have the followng sample input:

WITH Ratings AS (
    (SELECT \'A\' name, 2 score) UNION ALL
    (SELECT \'B\' name, 0 score) UNION ALL
    (SELECT \'C         


        
5条回答
  •  春和景丽
    2021-02-03 15:09

    We can build star rating as a string using two Unicode characters:

    ★ - Unicode code point 9733 
    ☆ - Unicode code point 9734
    

    We can use CODE_POINTS_TO_STRING function to build the stars, and REPEAT function to produce the right number of stars

    Combined together the solution for sample input will be:

    WITH Ratings AS (
    (SELECT 'A' name, 2 score) UNION ALL
    (SELECT 'B' name, 0 score) UNION ALL
    (SELECT 'C' name, 5 score) UNION ALL
    (SELECT 'D' name, 1 score))
    
    SELECT 
      name, 
      CONCAT(
        REPEAT(CODE_POINTS_TO_STRING([9733]), score),
        REPEAT(CODE_POINTS_TO_STRING([9734]), 5-score)) score
    FROM Ratings
    

    It will produce the following result:

    name    score
    A       ★★☆☆☆
    B       ☆☆☆☆☆
    C       ★★★★★
    D       ★☆☆☆☆
    

提交回复
热议问题