PostgresSQL - How to get a string instead of NULL when there is no value in left join? - postgresql

I have 2 tables that have list of workers and events.
When I'm trying to bring the list of ALL the workers with the current event that is still not finished , I either get an event name or NULL , but instead of null , I would like to get empty string because when I'm sending the result back to HTML , I get "NULL" on the screen.
I tried
select workers.id, workers.name , events.name
from workers left join events on events.workerid = workers.id
where events.isfinished = false;
results is :
1 Dave NULL
2 Charlie Event 2
3 Steve Event 3
My Tables
Workers
Id Name
-----------------
1 Dave
2 Charlie
3 Steve
Events
Id Description workderId isFinished
------------------------------------------------------
1 Event 1 1 true
2 Event 2 2 false
3 Event 3 3 false
What should my sql be in order to get empty string or different value instead of NULL ?

Try adding COALESCE(), something like this:
SELECT workers.id, workers.name AS worker, COALESCE(events.name, '') AS event
FROM workers
LEFT JOIN events ON events.workerid = workers.id
WHERE events.isfinished = false

Use COALESCE:
SELECT
w.id,
w.name AS workers_name,
COALESCE(e.name, '') AS events_name -- or replace with some other string value
FROM workers w
LEFT JOIN events e
ON e.workerid = w.id
WHERE
e.isfinished = false;
Note that your current query is selecting two columns both of which are called name. I aliased them to different things, to keep the result set readable.

Related

How to create an inline table from an existing table

I have a table in qlik Sense loaded from the database.
Example:
ID
FRUIT
VEG
COUNT
1
Apple
5
2
Figs
10
3
Carrots
20
4
Oranges
12
5
Corn
10
From this I need to make a filter that will display all the Fruit/Veg records along with records from other joined tables, when selected.
The filter needs to be something like this :
|FRUIT_XXX|
|VEG_XXX |
Any help will be appreciated.
I do not know how to do it in qlicksense, but in SQL it's like this:
SELECT
ID
CASE WHEN FRUIT IS NULL THEN VEG ELSE FRUIT END as FruitOrVeg,
COUNT
FROM tablename
Not sure if its possible to be dynamic. Usually I solve these by creating a new field that combines the values from both fields into one field
RawData:
Load * Inline [
ID , FRUIT ,VEG , COUNT
1 , Apple , , 5
2 , Figs , , 10
3 , ,Carrots , 20
4 , Oranges , , 12
5 , ,Corn , 10
];
Combined:
Load
ID,
'FRUIT_' & FRUIT as Combined
Resident
RawData
Where
FRUIT <> ''
;
Concatenate
Load
ID,
'VEG_' & VEG as Combined
Resident
RawData
Where
VEG <> ''
;
This will create new table (Combined) which will be linked to the main table by ID field:
The new Combined field will have the values like this:
And the UI:
P.S. If further processing is needed you can join the Combined table to the RawData table. This way the Combined field will become part of the RawData table. To achieve this just extend the script a bit:
join (RawData)
Load * Resident Combined;
Drop Table Combined;

postgresql UPDATE and RETURNING query not returning latest value

I have the following table
p_id, j_id, completed
a b false
c b true
and am using the following query to update the complete to true
update progress_status set completed = true where p_id = 'c' returning (
select to_json(t) from (select count(*) as total, sum(case when "completed" = true then 1 else 0 end) as completed from progress_status where j_id='b') t
) as status
but the query always returns the pre existing value before the update query was executed.
In the above case I would get completed as 1 and total as 2 whereas I expected it to be
completed = 2 total = 2
What is the reason behind this and how can I avoid such a response? Also is there a performance benefit to executing these two queries in the same query or it doesn't really make a difference in performance ?
Try this:
WITH updated AS (UPDATE ... RETURNING list of columns)
SELECT your select query FROM updated;
This should make the SELECT operate on what the UPDATE returns, not on the table itself.

C# Entityframework how to include based on condition

I have a table with one to many to many relation ie
ManyToMany table:
MenuGroup
menuid groupid
1 4
1 5
Menu
menuid name
1 One
2 Two
Group
groupid name
4 group4
5 group5
Groupuser
groupid userid
4 101
4 103
5 102
i would like to get all menus of the user 101
ie
Menuid groupid name
1 4 group4
But i am getting the wrong out put eventhough writing the correct join queries. Can anyone help what am i doing wrong here?
Menuid groupid name
1 4 group4
1 5 group5
(from m in context.Menus
join mg in context.MenuGroup on m.MenuId equals mg.MenuId
join gu in context.Groupuser on mg.GroupId equals gu.GroupId
where gu.UserId == 101
select m);
i would like to include only this particular user's group details though this menu is in other group as well.
my expected output in json would be
{
"menuid": 1,
"name": "One",
"groups":[
{
"groupid":4,
"name":"group4"
}
]
}
Your linq query looks good, I suspect data issue, but would you like to try the following query to see what you get back. This following query requires navigation properties declared.
var userMenus = context.GroupUser.Where(u=>u.UserId = 101).SelectMany(g=>g.Group.Menus
.Select(m=> new {Menu=m.MenuId, GroupId=g.GroupId,GroupName=g.Group.name))
.ToList();
In case you want the complete Menu object
var userMenus = context.GroupUser.Where(u=>u.UserId = 101).SelectMany(g=>g.Group.Menus
.Select(m=> new {Menu=m.Menu, GroupId=g.GroupId,GroupName=g.Group.name))
.ToList();
In case you don't care about Group columns and just want Menu then
var userMenus = context.GroupUsers.Where(u => u.UserId == 101)
.SelectMany(g => g.Group.Menus.Select(m=>m.Menu));

Postgres bitmask group by

I have the following flags declared:
0 - None
1 - Read
2 - Write
4 - View
I want to write a query that will group on this bitmask and get the count of each flag used.
person mask
a 0
b 3
c 7
d 6
The result should be:
flag count
none 1
read 2
write 3
view 2
Any tips would be appreciated.
For Craig
SELECT lea.mask as trackerStatusMask,
count(*) as count
FROM Live le
INNER JOIN (
... --some guff
) lea on le.xId = lea.xId
WHERE le.xId = p_xId
GROUP BY lea.mask;
SQL Fiddle
select
count(mask = 0 or null) as "None",
count(mask & 1 > 0 or null) as "Read",
count(mask & 2 > 0 or null) as "Write",
count(mask & 4 > 0 or null) as "View"
from t
Simplest - pivoted result
Here's how I'd approach it:
-- (after fixing the idiotic mistakes in the first version)
SELECT
count(nullif(mask <> 0, True)) AS "none",
count(nullif(mask & 2,0)) AS "write",
count(nullif(mask & 1,0)) AS "read",
count(nullif(mask & 4,0)) AS "view"
FROM my_table;
-- ... though #ClodAldo's version of it below is considerably clearer, per comments.
This doesn't do a GROUP BY as such; instead it scans the table and collects the data in a single pass, producing column-oriented results.
If you need it in row form you can pivot the result, either using the crosstab function from the tablefunc module or by hand.
If you really must GROUP BY, explode the bitmask
You cannot use GROUP BY for this in a simple way, because it expects rows to fall into exactly one group. Your rows appear in multiple groups. If you must use GROUP BY you will have to do so by generating an "exploded" bitmask where one input row gets copied to produce multiple output rows. This can be done with a LATERAL function invocation in 9.3, or with a SRF-in-SELECT in 9.2, or by simply doing a join on a VALUES clause:
SELECT
CASE
WHEN mask_bit = 1 THEN 'read'
WHEN mask_bit = 2 THEN 'write'
WHEN mask_bit = 4 THEN 'view'
WHEN mask_bit IS NULL THEN 'none'
END AS "flag",
count(person) AS "count"
FROM t
LEFT OUTER JOIN (
VALUES (4),(2),(1)
) mask_bits(mask_bit)
ON (mask & mask_bit = mask_bit)
GROUP BY mask_bit;
I don't think you'll have much luck making this as efficient as a single table scan, though.

how to get grouped query data from the resultset?

I want to get grouped data from a table in sqlite. For example, the table is like below:
Name Group Price
a 1 10
b 1 9
c 1 10
d 2 11
e 2 10
f 3 12
g 3 10
h 1 11
Now I want get all data grouped by the Group column, each group in one array, namely
array1 = {{a,1,10},{b,1,9},{c,1,10},{h,1,11}};
array2 = {{d,2,11},{e,2,10}};
array3 = {{f,3,12},{g,3,10}}.
Because i need these 2 dimension arrays to populate the grouped table view. the sql statement maybe NSString *sql = #"SELECT * FROM table GROUP BY Group"; But I wonder how to get the data from the resultset. I am using the FMDB.
Any help is appreciated.
Get the data from sql with a normal SELECT statement, ordered by group and name:
SELECT * FROM table ORDER BY group, name;
Then in code, build your arrays, switching to fill the next array when the group id changes.
Let me clear about GroupBy. You can group data but that time its require group function on other columns.
e.g. Table has list of students in which there are gender group mean Male & Female group so we can group this table by Gender which will return two set . Now we need to perform some operation on result column.
e.g. Maximum marks or Average marks of each group
In your case you want to group but what kind of operation you require on price column ?.
e.g. below query will return group with max price.
SELECT Group,MAX(Price) AS MaxPriceByEachGroup FROM TABLE GROUP BY(group)