-1

Sorry for an unclear topic but i am not sure how to better describe my situation here

I have a table similar to this:

Test Table

And i was asked to create a view based on the table with some requirements, and the out come should be something like:

enter image description here

(I hard code this table to show my expected result for the View)

I am quite new to Create View Function and i've tried to look for solution online but i can't find much useful information.

K.Leung
  • 11
  • 3

1 Answers1

0

The syntax for creating a view is really simple:

create view <view name> as
    <select query here>;

The question that you have asked is for a view that returns exactly five columns. You can handle this with an aggregation query:

create view v_name as
    select device_id,
           sum(case when device_type = 'A' then count else 0 end) as a,
           sum(case when device_type = 'B' then count else 0 end) as b,
           sum(case when device_type = 'C' then count else 0 end) as c,
           sum(case when device_type = 'D' then count else 0 end) as d
    from t  -- your table name here
    group by device_id;

The caveat is that this returns exactly the types that are in the SELECT -- no others if they are in the table. If you need flexible columns, then you have a problem. It is not hard to construct a dynamic query to return the values at any given time. However, you cannot put dynamic SQL in a view. If this is something you need, then some alternative mechanism -- such as JSON -- might be needed.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786