postgres aggregate join matches to multiple array fields while creating views - sql

I have the following schema + data:
create table org_users (
id character varying (255),
settings_id character varying (255) -- fk: settings.id
);
create table settings (
id character varying (255), -- primary key settings_id
perdiem_settings character varying (255), -- jsonised fk to perdiems.id
floor_settings character varying (255) -- jsonised fk to floors.id
);
create table perdiems (
id integer, -- primary key
name character varying(255)
);
create table floors (
id integer, -- primary key
name character varying (255)
);
insert into perdiems (id, name) values (1, 'perdiem 1');
insert into perdiems (id, name) values (2, 'perdiem 2');
insert into perdiems (id, name) values (3, 'perdiem 3');
insert into floors (id, name) values (1, 'floor 1');
insert into floors (id, name) values (2, 'floor 2');
insert into floors (id, name) values (3, 'floor 3');
insert into settings (id, perdiem_settings, floor_settings) values ('setting1', '{"allowed_per_diem_ids":[1, 2]}', '{"allowed_floor_ids":[1]}');
insert into settings (id, perdiem_settings, floor_settings) values ('setting2', '{"allowed_per_diem_ids":[2, 3]}', '{"allowed_floor_ids":[1, 2]}');
insert into settings (id, perdiem_settings, floor_settings) values ('setting3', '{"allowed_per_diem_ids":[3, 1]}', '{"allowed_floor_ids":[1, 2, 3]}');
insert into org_users (id, settings_id) values ('user1', 'setting1');
insert into org_users (id, settings_id) values ('user2', 'setting2');
insert into org_users (id, settings_id) values ('user3', 'setting3');
Now I want to create a view which will have aggregates from each of the other table, into an array field of its own. To explain with an example, the view that I want should be like:
org_user_id | settings_id | perdiems | floors
--------------------------------------------------------------------------------------------
user1 | setting1 | ['perdiem 1', 'perdiem 2'] | ['floor 1']
user2 | setting2 | ['perdiem 2', 'perdiem 3'] | ['floor 1', 'floor 2']
user3 | setting3 | ['perdiem 3', 'perdiem 1'] | ['floor 1', 'floor 2', 'floor 3']
This question is somewhat related to postgres aggregate join matches to an array field which deals with creating array fields out of join matches. However, here I want to create multiple array fields in a single view and so using a GROUP BY clause will not be feasible iiuc.
The query that I tried is:
CREATE OR REPLACE VIEW users_settings_view AS
SELECT ou.id AS org_user_id, <other fields...>
FROM org_users ou
LEFT JOIN settings pdr_s ON pdr_s.id = ou.settings_id
LEFT JOIN perdiems pdr ON pdr.id = ANY (SELECT json_array_elements(perdiem_settings::JSON->'allowed_per_diem_ids')::text::int FROM settings)
which creates duplicate records for each of the matching perdiem because of the join and not creating an array. Even if I crate an array as mentioned in the other stackoverflow question, it won't work if I have multiple string arrays as part of the view for different columns. Any way I can get multiple join matches to multiple array fields in a single view ?

This will give you the result.
select ou.id, array_agg( DISTINCT pd.name ),
array_agg( DISTINCT f.name )
from org_users ou join settings s on ou.settings_id = s.id
cross join lateral
json_array_elements_text(((s.perdiem_settings)::json->'allowed_per_diem_ids')::json)
as jp(perdiem) join
perdiems pd
on pd.id = jp.perdiem::int
cross join lateral
json_array_elements_text(((s.floor_settings)::json->'allowed_floor_ids')::json)
as js(floor) join
floors f
on f.id = js.floor::int
GROUP BY ou.id;
Demo
Edit
For cases of NULL settings, you may use a separate UNION ALL
select id , ARRAY[NULL] as perdiems ,ARRAY[NULL] as floors FROM org_users
WHERE settings_id IS NULL
UNION ALL
(
-- The above query --
) ORDER BY id;
Demo2

Related

Passing a parameter value for like

create table ter (
ID number,
category varchar2(250 byte),
name varchar2(250 byte)
);
insert into ter values (1, 'amd-visual theraphy','john');
insert into ter values (1, 'amd-visual theraphy','mike');
insert into ter values (2, 'amd-autmatic theraphy','mike');
insert into ter values (3, 'amd-autmatic theraphy','drane');
insert into ter values (3, 'cmd autmatic theraphy', 'traverse');
insert into ter values (3, 'amd-dramatic theraphy','drane');
insert into ter values (3, 'cmd-dropertic theraphy', 'traverse');
insert into ter values (5,'qwd-dropertic visual-theraphy','drones');
insert into ter values (5,'qwd-aromatic-theraphy','drones');
insert into ter values (3, 'other', 'traverse');
insert into ter values (3, 'other', 'traverse');
1: &category is null display all records
2: &category is not null and if i enter category =visual,autmatic then display respectively
3 &category is not null and if i enter category =dramatic it should display dramtic and dropertic ignoring other results;
as dramatic and dropertic is the requirement where the user want to see and ignoring the if partial value matches with visual and autmatic contains
how to obtain this result
this is what one gave the solution to me but still i want to ignore the visual containing dropetic
select *
from ter t cross join (select '&category' as my_categ from dual) m
where m.my_categ is null
or m.my_categ in ('visual', 'autmatic', 'dramtic') and t.category like '%'
|| m.my_categ || '%'
or m.my_categ = 'dramtic' and t.category like '%dropertic%' ;
I'd change your data model a bit.
Instead of saving categories as a space separated string, i'd better move them to separate table.
create table category(
ter_id number,
name varchar(250 bytes)
);
where ter_id is the same as ID in your ter column.
This table should contain records like:
insert into category values (1, 'amd-visual');
insert into category values (1, 'therapy');
-- etc.
Implying above your query will be something like:
select t.*, c.*
from ter t, category c
where t.id = c.ter_id
and category in ('therapy', 'visual');
-- etc...
If you really need to satisfy criteria:
if category is null display all records
it's easy to implement just adding
record with empty category name to table category:
insert into category values (1, null);
insert into category values (2, null);
-- etc.

Sql query select all messages from everybody inside every group where this one user is at

I'm trying to get all of the messages, from EVERY user, from 2 groups, where the user is located. But I don't know how to get all message from every group. This is my code so far:
SELECT DISTINCT m.*
FROM `message` m
INNER JOIN users u
ON u.id = m.idUser
LEFT JOIN whats_app w
ON w.idUser= u.id
WHERE u.id = w.idUser
So there is ONLY ONE user in 2 groups. I wan't to get all messages from everybody inside the groups where the ONE user is located at.
this is some simple sql query als example:
create table users (
id int PRIMARY KEY NOT NULL,
name varchar(60)
);
create table whatsapp(
idUser ,
idGroup int
);
create table allGroups(
id int PRIMARY KEY NOT NULL,
name varchar(60)
);
create table message_send(
id int,
idUser int,
message text
);
INSERT INTO users(id, name) VALUES
(1, 'John'),
(2, 'Martijn'),
(3, 'Rick'),
(4, 'Vera'),
(5, 'Leon');
INSERT INTO allGroups(id, name) VALUES
(1, 'School'),
(2, 'Friends'),
(3, 'moreFriends'),
(4, 'secretmeeting');
INSERT INTO message_send(id, idUser, message) VALUES
(1, 2, 'How are you feeling today?'),
(2, 1, 'What up?'),
(3, 4, 'I am fine, you?'),
(4, 1, 'hi!');
create table message_send(
id int,
idUser int,
idGroup int,
message text
);
Create message table like this and then just directly join with user and group you will get the output there is not need for the table watsapp
select b.name,message
from
message_send as a,
users as b
where
a.idUser=b.id
Similarly join the group table

Collecting entity attribute values with null for missing attributes in SQL

I have some entities in a table and their attributes and values in an other. I would like to create a select where I can see the value a specific attribute for every entity or null if that attribute is missing. How can I do this using standard SQL?
This is the setup:
create table person (id int not null, nick varchar(32) not null);
insert into person (id, nick) values (1, 'John');
insert into person (id, nick) values (2, 'Peter');
create table req_attributes (name varchar(32));
create table person_attributes (id int not null,
person_id int not null,
attribute varchar(32) not null,
value varchar(64) not null);
insert into person_attributes values (1, 1, 'age', '21');
insert into person_attributes values (2, 1, 'hair', 'brown');
insert into person_attributes values (3, 2, 'age', '32');
insert into person_attributes values (4, 2, 'music', 'jazz');
And this is my current select statement:
select * from person join person_attributes on
person.id = person_attributes.person_id
where attribute = 'hair';
Obviously Peter is not in the result set because we have no information about his hair. I would like to get him into the result set as well, but with null value.
The best would be if the result set was like
Person, Hair color
John, brown
Peter, null
I would like to avoid subqueries if possible, but if it is impossible to do with joins then they are welcome.
An outer join will do this:
select p.*, pa.value
from person p
left join person_attributes pa
on p.id = pa.person_id
and pa.attribute = 'hair';
Note that the condition for the "outer joined" table needs to go into the JOIN clause, not into the where clause. If the condition was in the where clause it would effectively turn the outer join into an inner join. This is because pa.attribute would be null due to the outer join, and the where would not match the null value thus eliminating all the rows that should actually stay in the result.
SQFiddle based on your example: http://sqlfiddle.com/#!12/d0342/1

How to create an "on-the-fly" mapping table within a SELECT statement in Postgresql

I'm creating a select statement that combines two tables, zone and output,
based on a referenced device table and on a mapping of zone_number to output_type_id.
The mapping of zone_number to output_type_id doesn't appear
anywhere in the database, and I would like to create it "on-the-fly" within the select
statement. Below is my schema:
CREATE TABLE output_type (
id INTEGER NOT NULL,
name TEXT,
PRIMARY KEY (id)
);
CREATE TABLE device (
id INTEGER NOT NULL,
name TEXT,
PRIMARY KEY (id)
);
CREATE TABLE zone (
id SERIAL NOT NULL,
device_id INTEGER NOT NULL REFERENCES device(id),
zone_number INTEGER NOT NULL,
PRIMARY KEY (id),
UNIQUE (zone_number)
);
CREATE TABLE output (
id SERIAL NOT NULL,
device_id INTEGER NOT NULL REFERENCES device(id),
output_type_id INTEGER NOT NULL REFERENCES output_type(id),
enabled BOOLEAN NOT NULL,
PRIMARY KEY (id)
);
And here is some example data:
INSERT INTO output_type (id, name) VALUES
(101, 'Output 1'),
(202, 'Output 2'),
(303, 'Output 3'),
(404, 'Output 4');
INSERT INTO device (id, name) VALUES
(1, 'Test Device');
INSERT INTO zone (device_id, zone_number) VALUES
(1, 1),
(1, 2),
(1, 3),
(1, 4);
INSERT INTO output (device_id, output_type_id, enabled) VALUES
(1, 101, TRUE),
(1, 202, FALSE),
(1, 303, FALSE),
(1, 404, TRUE);
I need to get the associated enabled field from the output table for each zone for a given device.
Each zone_number maps to an output_type_id. For this example:
zone_number | output_type_id
----------------------------
1 | 101
2 | 202
3 | 303
4 | 404
One way to handle the mapping would be to create a new table
CREATE TABLE zone_output_type_map (
zone_number INTEGER,
output_type_id INTEGER NOT NULL REFERENCES output_type(id)
);
INSERT INTO zone_output_type_map (zone_number, output_type_id) VALUES
(1, 101),
(2, 202),
(3, 303),
(4, 404);
And use the following SQL to get all zones, plus the enabled flag, for device 1:
SELECT zone.*, output.enabled
FROM zone
JOIN output
ON output.device_id = zone.device_id
JOIN zone_output_type_map map
ON map.zone_number = zone.zone_number
AND map.output_type_id = output.output_type_id
AND zone.device_id = 1
However, I'm looking for a way to create the mapping of zone nunbers to output
types without creating a new table and without piecing together a bunch of AND/OR
statements. Is there an elegant way to create a mapping between the two fields
within the select statement? Something like:
SELECT zone.*, output.enabled
FROM zone
JOIN output
ON output.device_id = zone.device_id
JOIN (
SELECT (
1 => 101,
2 => 202,
3 => 303,
4 => 404
) (zone_number, output_type_id)
) as map
ON map.zone_number = zone.zone_number
AND map.output_type_id = output.output_type_id
AND zone.device_id = 1
Disclaimer: I know that ideally the enabled field would exist in the zone
table. However, I don't have control over that piece. I'm just looking for the
most elegant solution from the application side. Thanks!
You can use VALUES as an inline table and JOIN to it, you just need to give it an alias and column names:
join (values (1, 101), (2, 202), (3, 303), (4, 304)) as map(zone_number, output_type_id)
on ...
From the fine manual:
VALUES can also be used where a sub-SELECT might be written, for
example in a FROM clause:
SELECT f.*
FROM films f, (VALUES('MGM', 'Horror'), ('UA', 'Sci-Fi')) AS t (studio, kind)
WHERE f.studio = t.studio AND f.kind = t.kind;
UPDATE employees SET salary = salary * v.increase
FROM (VALUES(1, 200000, 1.2), (2, 400000, 1.4)) AS v (depno, target, increase)
WHERE employees.depno = v.depno AND employees.sales >= v.target;
So just to complement the accepted answer, the following code is a valid, self-contained Postgresql expression which will evaluate to an 'inline' relation with columns (zone_number, output_type_id):
SELECT * FROM
(VALUES
(1, 101),
(2, 202),
(3, 303),
(4, 304)
) as i(zone_number, output_type_id)
(The (VALUES ... AS ...) part alone will not make a valid expression, which is why I added the SELECT * FROM.)
JOIN
(SELECT 1 zone_number, 101 as output_type_id
UNION ALL
SELECT 2 zone_number, 202 as output_type_id
UNION ALL
SELECT 3 zone_number, 303 as output_type_id
) mappings on mappings.zone_number = zone.zone_number

SQL Query problems exist

I'm having a lot of troubles with the last query I need and I think it's a level out of my league so any help is appreciated.
The tables:
CREATE TABLE Recipe
(
nrecipe integer,
name varchar(255),
primary key (nrecipe)
);
CREATE TABLE Food
(
designation varchar(255) unique,
quantity integer,
primary key (designation)
);
CREATE TABLE Contains
(
nrecipe integer,
designation varchar(255),
quantity integer,
primary key (nrecipe, designation),
foreign key (nrecipe) references Recepie (nrecipe),
foreign key (designation) references Food (designation)
);
Quantity in Food table is the quantity stored in warehouse.
Quantity in Contains is the amount needed of a food element to use in recipe.
Quantity in Food table and Contains differ from each other.
The query:
I want to know the names of ALL recipes that are possible to be done with the food stored in warehouse.
It requires that the quantity of every element of food in warehouse is bigger than the quantity needed for the recipe.
EDIT: also, it shouldn't show a recipe's name if there is nothing referring to it on Contains table.
To make it easier to understand, I'll give some data:
INSERT INTO Recipe VALUES ('01', 'Steak with potatos and water');
INSERT INTO Recipe VALUES ('02', 'Rice and ice tea');
INSERT INTO Recipe VALUES ('03', 'Potatos and shrimp');
INSERT INTO Recipe VALUES ('04', 'Water');
INSERT INTO Recipe VALUES ('05', 'Steak with rice');
INSERT INTO Recipe VALUES ('06', 'Steak with spaguetti');
INSERT INTO Recipe VALUES ('07', 'Potatos with rice');
INSERT INTO Food VALUES ('Water', 5);
INSERT INTO Food VALUES ('Ice tea', 10);
INSERT INTO Food VALUES ('Steak', 30);
INSERT INTO Food VALUES ('Potatos', 20);
INSERT INTO Food VALUES ('Rice', 50);
INSERT INTO Food VALUES ('Shrimp', 5);
INSERT INTO Food VALUES ('Spaguetti', 5);
INSERT INTO Contains VALUES ('01', 'Steak', 1);
INSERT INTO Contains VALUES ('01', 'Potatos', 15);
INSERT INTO Contains VALUES ('01', 'Water', 10);
INSERT INTO Contains VALUES ('02', 'Rice', 5);
INSERT INTO Contains VALUES ('02', 'Ice tea', 8);
INSERT INTO Contains VALUES ('03', 'Potatos', 1);
INSERT INTO Contains VALUES ('03', 'Shrimp', 10);
INSERT INTO Contains VALUES ('04', 'Water', 20);
INSERT INTO Contains VALUES ('05', 'Steak', 1);
INSERT INTO Contains VALUES ('05', 'Rice', 20);
INSERT INTO Contains VALUES ('06', 'Steak', 1);
INSERT INTO Contains VALUES ('06', 'Spaguetti', 10);
The outcome expected from the query is:
Rice and ice tea
Steak with rice
Since it's the only two recipes with enough quantity in warehouse.
EDIT: potatoes with rice shouldn't appear as it is a recipe but isn't in contains list
Thanks for input and time. Any help is welcome :)
I'd use >= ALL operator :
SELECT name
FROM Recipe R
WHERE 0 >= ALL (SELECT C.quantity - F.quantity
FROM Food F
INNER JOIN Contains C
USING (designation)
WHERE C.nrecipe = R.nrecipe);
The correct spelling is recipe, and you used different names for some columns (recepie, nrecipe, nrecepie) so I changed it. Note that instead of using a varchar primary key, you should use a numeric one.
Edit:
SELECT name
FROM Recipe R
WHERE 0 >= ALL (SELECT C.quantity - F.quantity
FROM Food F
INNER JOIN Contains C
USING (designation)
WHERE C.nrecipe = R.nrecipe)
AND EXISTS(SELECT NULL
FROM Contains C
WHERE C.nrecipe = R.nrecipe);
This is in SQL Server because that is what I have:
select
r.name
from
Recepie r
where
not exists
(
select 1
from
[Contains] c
where
c.nrecipe = r.nrecepie and
not exists
(
select 1
from
Food f
where
f.designation = c.designation and
f.quantity >= c.quantity
)
)
Which in plain language is "Get me all recipes where there are no ingredients of insufficient quantity"