SQLite - обновить из вида - PullRequest
0 голосов
/ 05 мая 2018

У меня есть вид:


    CREATE VIEW UsersCounts AS SELECT
        users.id,
        users.username,
        users.email,
        SUM(CASE WHEN orders.id > 0 THEN 1 ELSE 0 END) as orders_all,
        SUM(CASE WHEN orders.status='ACTIVE' THEN 1 ELSE 0 END) as orders_active,
        SUM(CASE WHEN orders.status='RETURNED' THEN 1 ELSE 0 END) as orders_returned
    FROM users
        INNER JOIN orders ON
            users.email = orders.email
    GROUP BY users.id

Результат:

id | username | email | orders_all | orders_active | orders_returned

Как я могу установить Users.customer_status = "VIP"', где orders_active > 5?

Ответы [ 3 ]

0 голосов
/ 05 мая 2018

Вы бы сделали:

CREATE VIEW UsersCounts AS
    SELECT u.id, u.username, u.email,
           SUM(CASE WHEN o.id > 0 THEN 1 ELSE 0 END) as orders_all,
           SUM(CASE WHEN o.status = 'ACTIVE' THEN 1 ELSE 0 END) as orders_active,
           SUM(CASE WHEN o.status = 'RETURNED' THEN 1 ELSE 0 END) as orders_returned,
           (CASE WHEN SUM(CASE WHEN o.status = 'ACTIVE' THEN 1 ELSE 0 END) > 5
                 THEN 'VIP'
                 ELSE MAX(u.customer_status)
            END) as customer_status
    FROM users u INNER JOIN
         orders o
         ON u.email = o.email
    GROUP BY u.id
0 голосов
/ 06 мая 2018

пример:

обновить таблицу из идентификатора вида установить возраст <18 лет не может курить </p>

create table TestTable (id int,age int,smokable NVARCHAR(8));
CREATE VIEW TestView AS SELECT
id,
case when age < 18 then 'young' 
else 'old'
end status
from TestTable;
insert into TestTable (id,age,smokable) values (1,25,null),(2,17,null),(3,12,null),(4,9,null);
select * from TestView;
id | status
:- | :-----
1  | old   
2  | young 
3  | young 
4  | young 
select * from TestTable;
id | age | smokable
:- | :-- | :-------
1  | 25  | <em>null</em>    
2  | 17  | <em>null</em>    
3  | 12  | <em>null</em>    
4  | 9   | <em>null</em>    
update TestTable
set smokable = 'Unable'
where id in (select id from TestView where status = 'young');
select * from TestTable;
id | age | smokable
:- | :-- | :-------
1  | 25  | <em>null</em>    
2  | 17  | Unable  
3  | 12  | Unable  
4  | 9   | Unable  
0 голосов
/ 05 мая 2018

Для обновления вы можете использовать

    UPDATE users 
    SET customer_status = 'VIP'
    where EXISTS ( SELECT orders_active
                   FROM orders_active
                   WHERE  users.email = email
                   AND  orders_active > 5
    )
...