Fetch SQL rows with priority - sql

I have following tables structure:
forms
RID | MODULE
------------
1 | indiv
2 | indiv
3 | indiv
translations
RID | LANG | VALUE | MODULE | TAG |
-----------------------------------
1 | en |car | | |
1 | en |truck |indiv | |
1 | en |boat |indiv |C100 |
2 | en |hat | | |
3 | en |cat | | |
3 | en |dog |indiv | |
4 | en |light | | |
5 | en |dark | | |
I need to fetch only one row per RID from translations table, based on additional (but not mandatory) parameters for module and tag columns, i.e.:
RESULT without input parameters:
RID | LANG | VALUE | MODULE | TAG |
-----------------------------------
1 | en |car | | |
2 | en |hat | | |
3 | en |cat | | |
RESULT with one input parameter module='indiv':
RID | LANG | VALUE | MODULE | TAG |
-----------------------------------
1 | en |truck |indiv | |
2 | en |hat | | |
3 | en |dog |indiv | |
If I have two input parameters the result to be:
RESULT with two parameters: module='indiv' AND tag='c100'
RID | LANG | VALUE | MODULE | TAG |
-----------------------------------
1 | en |boat |indiv |C100 |
2 | en |hat | | |
3 | en |dog |indiv | |
How can I achieve this with SQL only on ORACLE DB server? A query example for the last case with two parameters will be enough for me as previous cases are subsets from last one with NULL of these columns I believe. If you think that all these cases are too different and require different SQL statements, you are more than welcome to write them as well.
Thank you!

SELECT *
FROM (
SELECT t.*,
ROW_NUMBER() OVER (
PARTITION BY RID
ORDER BY CASE
WHEN module = LOWER( :mod ) AND tag = UPPER( :tag ) THEN 1
WHEN tag = UPPER( :tag ) THEN 2
WHEN module = LOWER( :mod ) AND tag IS NULL THEN 3
WHEN module IS NULL AND tag IS NULL THEN 4
ELSE 5
END
) AS rn
FROM translations t
WHERE ( module IS NULL OR module = LOWER( :mod ) )
OR ( tag IS NULL OR tag = UPPER( :tag ) )
)
WHERE rn = 1;

I think this should do.
SELECT *
FROM (
SELECT F.RID,
T.LANG,
T.VALUE,
T.MODULE,
T.TAG,
RANK() OVER(PARTITION BY F.RID
ORDER BY DECODE(T.MODULE, :module, 1, 2),
DECODE(T.TAG, :tag, 1, 2)) RANK
FROM forms F INNER JOIN translations T
ON T.RID = F.RID)
WHERE RANK = 1
So you rank rows with MODULE = :module or/and TAG = :tag higher. You still need something to do with ties, but you get the idea. RANK leaves ties, ROW_NUMBER does not.
I put MODULE higher than TAG because of your examples. You might need to change it if you can input tags without modules.
And also, DECODE maps NULL to NULL, so if :module is not set, you will get match with rows having NULL in MODULE.

Related

SQL Check if the User has IN and Out

I need help getting the User which has an 'IN' and 'Out' in Column isIN. If the user has an IN and OUT do not select them in the list. I need to select the user who has only had an IN. Please I need help. Thanks in advance.
This is the table:
| Users | IsIN |
|:------------------:|:-----:|
| MHYHDC61TMJ907867 | IN |
| MHYHDC61TMJ907867 | OUT |
| MHYHDC61TMJ907922 | IN |
| MHYHDC61TMJ907922 | OUT |
| MHYHDC61TMJ907923 | IN |
| MHYHDC61TMJ907923 | OUT |
| MHYHDC61TMJ907924 | IN | - I need to get only this row
| MHYHDC61TMJ907925 | IN |
| MHYHDC61TMJ907925 | OUT |
| MHYHDC61TMJ908054 | IN | - I need to get only this row
| MHYHDC61TMJ908096 | IN | - I need to get only this row
| MHYHDC61TMJ908109 | IN | - I need to get only this row
Need to get the result like
| Users | IsIN |
|:------------------:|:-----:|
| MHYHDC61TMJ907924 | IN |
| MHYHDC61TMJ908054 | IN |
| MHYHDC61TMJ908096 | IN |
| MHYHDC61TMJ908109 | IN |
I tried using this query and sample query below but it doesn't work.
select s.[Users], s.[isIn] [dbo].[tblIO] s
where not exists (
select 1
from [dbWBS].[dbo].[tblIO] s2
where s2.[Users] = s.[Users] and s2.isIn = 'IN'
);
You can use not exists:
select s.*
from sample s
where not exists (select 1
from sample s2
where s2.user = s.user and s2.inout = 'OUT'
);
If you want only users that meet the condition (and not the full rows):
select user
from sample s
group by user
having min(inout) = max(inout) and min(inout) = 'IN';
Bearing in mind that an 'OUT' IsIn must be always preceded by an 'IN' record, you could use a query like this:
select s.Users, 'IN' as IsIn
from sample s
group by s.Users
having count(distinct s.IsIn) = 1

How to use JOIN, CROSS JOIN to combine globalized stored values in SQL into a single table

We have various tables pertaining to different entities where we would like to globalize the stored values. We do not know how to proceed technically anymore and are open to any form of help, hints or tips.
Language
ID | Culture | Description |
---+---------+-------------+
1 | EN | English |
2 | FR | French |
3 | ES | Spanish |
Job
ID | Description |
---+-------------+
1 | Doctor |
2 | Firefighter |
JobGlobalization
ID | JobID | Description | Culture |
---+-------+-------------+---------+
1 | 1 | Docteur | FR |
2 | 1 | Doctora | ES |
We attempted to use CROSS JOIN to obtain something of the following:
ID | Description | Culture |
---+-------------+---------+
1 | Doctor | EN |
1 | Doctor | FR |
1 | Doctor | ES |
2 | Firefighter | ES |
2 | Firefighter | ES |
2 | Firefighter | ES |
Query used:
SELECT Job.ID, Job.Description, Language.Culture
CROSS JOIN Language
ORDER BY Job.ID
We experienced with different joins on the child globalization table in order to correlate the entities together, however the results set kept multiplying itself in the wrong way.
We would like that for every parent entity, whether it has any related child entities, a row is selected for every culture in the Language table. The description column will default to the parent entity in the case where there are no associated records in the child table.
The resulting table should be as follows:
ID | Description | Culture |
---+-------------+---------+
1 | Doctor | EN |
1 | Docteur | FR |
1 | Doctora | ES |
2 | Firefighter | EN |
2 | Firefighter | FR |
2 | Firefighter | ES |
We had in mind a condition that would select the 'Description' column from the parent table 'Job' if there were no corresponding record for it in the child table.
e.g.
IIF(JobGlobalization.Description IS NOT NULL, JobGlobalization.Description, Job.Description)
We attempted to use CROSS JOIN to obtain something of the following:
This should produce the result set you describe:
SELECT j.ID, j.Description, l.Culture
FROM Job j CROSS JOIN
Language l
ORDER BY j.ID, l.Culture;
You can insert this into JobGlobalization (although you might want to truncate it first). Or you can use CREATE TABLE AS (or the equivalent for your database) to create JobGlobalization from scratch.
You would then need to update this table with the appropriate values for the culture.

SQL GROUPING with conditional

I am sure this is easy to accomplish but after spending the whole day trying I had to give up and ask for your help.
I have a table that looks like this
| PatientID | VisitId | DateOfVisit | FollowUp(Y/N) | FollowUpWks |
----------------------------------------------------------------------
| 123456789 | 2222222 | 20180802 | Y | 2 |
| 123456789 | 3333333 | 20180902 | Y | 4 |
| 234453656 | 4443232 | 20180506 | N | NULL |
| 455344243 | 2446364 | 20180618 | Y | 12 |
----------------------------------------------------------------------
Basically I have a list of PatientIDs, each patient can have multiple visits (VisitID and DateOfVisit). FollowUp(Y/N) specifies whether the patients has to be seen again and in how many weeks (FollowUpWks).
Now, what I need is a query that extracts PatientsID, DateOfVisit (the most recent one and only if FollowUp is YES) and the FollowUpWks field.
Final result should look like this
| PatientID | VisitId | DateOfVisit | FollowUp(Y/N) | FollowUpWks |
----------------------------------------------------------------------
| 123456789 | 3333333 | 20180902 | Y | 4 |
| 455344243 | 2446364 | 20180618 | Y | 12 |
----------------------------------------------------------------------
The closest I could get was with this code
SELECT PatientID,
Max(DateOfVisit) AS LastVisit
FROM mytable
WHERE FollowUp = True
GROUP BY PatientID;
The problem is that when I try adding the FollowUpWks field to the SELECT I get the following error: "The query does not include the specified expression as part of an aggregate function." However, if I add FollowUpWks to the GROUP BY statement than I get all visits, not just the most recent ones.
You need to match back to the most recent visit. One method uses a correlated subquery:
SELECT t.*
FROM mytable as t
WHERE t.FollowUp = True AND
t.DateOfVisit = (SELECT MAX(t2.DateOfVisit)
FROM mytable as t2
WHERE t2.PatientID = t.PatientID
);

When Querying Many-To-Many Relationship in SQL, Return Multiple Connections As an Array In Single Row?

Basically, I have 3 tables, titles, providers, and provider_titles.
Let's say they look like this:
| title_id | title_name |
|------------|----------------|
| 1 | San Andres |
| 2 |Human Centipede |
| 3 | Zoolander 2 |
| 4 | Hot Pursuit |
| provider_id| provider_name |
|------------|----------------|
| 1 | Hulu |
| 2 | Netflix |
| 3 | Amazon_Prime |
| 4 | HBO_GO |
| provider_id| title_id |
|------------|----------------|
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
| 3 | 3 |
| 4 | 4 |
So, clearly there are titles with multiple providers, yeah? Typical many-to-many so far.
So what I'm doing to query it is with a JOIN like the following:
SELECT * FROM provider_title JOIN provider ON provider_title.provider_id = provider.provider_id JOIN title ON title.title_id = provider_title.title_id WHERE provider.name IN ('Netflix', 'HBO_GO', 'Hulu', 'Amazon_Prime')
Ok, now to the actual issue. I don't want repeated title names back, but I do want all of the providers associated with the title. Let me explain with another table. Here is what I am getting back with the current query, as is:
| provider_id| provider_name | title_id | title_name |
|------------|---------------|----------|---------------|
| 1 | Hulu | 1|San Andreas |
| 1 | Hulu | 2|Human Centipede|
| 2 | Netflix | 1|San Andreas |
| 3 | Amazon_Prime | 1|San Andreas |
| 3 | Amazon_prime | 3|Zoolander 2 |
| 4 | HBO_GO | 4|Hot Pursuit |
But what I really want would be something more like
| provider_id| provider_name |title_id| title_name|
|------------|-----------------------------|--------|-----------|
| [1, 2, 3] |[Hulu, Netflix, Amazon_Prime]| 1|San Andreas|
Meaning I only want distinct titles back, but I still want each title's associated providers. Is this only possible to do post-sql query with logic iterating through the returned rows?
Depending on your database engine, there may be an aggregation function to help achieve this.
For example, this SQLfiddle demonstrates the postgres array_agg function:
SELECT t.title_id,
t.title_name,
array_agg( p.provider_id ),
array_agg( p.provider_name )
FROM provider_title as pt
JOIN
provider as p
ON pt.provider_id = p.provider_id
JOIN title as t
ON t.title_id = pt.title_id
GROUP BY t.title_id,
t.title_name
Other database engines have equivalents. For example:
mySQL has group_concat
Oracle has listagg
sqlite has group_concat (as well!)
If your database isn't covered by the above, you can google '[Your database engine] aggregate comma delimited string'

SQL - Joining columns from the same table in a Query

SOLVED ! See the answer bellow !
Before I explain my problem I want to apologise for those who would feel this question is too long but I feel like I must give some details to make things the clearer possible. Though, the problem is simple to understand it is not that simple to me to implement.
I have 3 tables.
Hata and Icon contains images I want to link with Succes which contains texts
[Hata]
id, INTEGER, AUTO_INCREMENT, PRIMARY_KEY
hata Image
idLang, VARCHAR(5)
[Icon]
id, INTEGER, AUTO_INCREMENT, PRIMARY_KEY
icon, IMAGE
idPhrase, INTEGER
[Succes]
id, INTEGER, AUTO_INCREMENT, PRIMARY_KEY
idPhrase, INTEGER
titre, VARCHAR(25)
desc, VARCHAR(125)
idLang, VARCHAR(5)
Here is a sample showing how the Succes table looks like
+----+----------+-----------------+------------------+--------+
| id | idPhrase | titre | desc | idLang |
+----+----------+-----------------+------------------+--------+
| 1 | 1 | Hello | Desc in English | en-GB |
+----+----------+-----------------+------------------+--------+
| 2 | 1 | Salut | Desc in French | fr-FR |
+----+----------+-----------------+------------------+--------+
| 3 | 1 | 今日は | Desc in Japanese | ja-JP |
+----+----------+-----------------+------------------+--------+
| 4 | 2 | Goodbye | Desc in English | en-GB |
+----+----------+-----------------+------------------+--------+
| 5 | 2 | Au revoir | Desc in French | fr-FR |
+----+----------+-----------------+------------------+--------+
| 6 | 2 | またね | Desc in Japanese | ja-JP |
+----+----------+-----------------+------------------+--------+
| 7 | 3 | You're welcome | Desc in English | en-GB |
+----+----------+-----------------+------------------+--------+
| 8 | 3 | Je vous en prie | Desc in French | fr-FR |
+----+----------+-----------------+------------------+--------+
| 9 | 3 | どういたしまして | Desc in Japanese | ja-JP |
+----+----------+-----------------+------------------+--------+
...
The tables are now joined using this WHERE conditions
Icons.idPhrase = Succes.idPhrase AND Hata.idLang=Succes.idLang
Everything would be fine if there would be nothing specific in the Succes table.
In fact, for each Icon there are 3 sentences and the idPhrase links them but in the actual result set I somehow have redundancies.
Icon1|FlagIcon1|TitreLang1|DescLang1
Icon1|FlagIcon2|TitreLang2|DescLang2
Icon1|FlagIcon3|TitreLang3|DescLang3
Icon2|FlagIcon1|TitreLang1|DescLang1
Icon2|FlagIcon2|TitreLang2|DescLang2
Icon2|FlagIcon3|TitreLang3|DescLang3
...
What I'd like to achieve is the following (just the very first row):
Icon1|FlagIcon1|TitreLang1|DescLang1|FlagIcon2|TitreLang2|DescLang2|FlagIcon3|TitreLang3|DescLang
or
Icon1|FlagIcon1|FlagIcon2|FlagIcon3|TitreLang1|DescLang1|TitreLang2|DescLang2|TitreLang3|DescLang3
or even
Icon1|FlagIcon1|FlagIcon2|FlagIcon3|TitreLang1|TitreLang2|TitreLang3|DescLang1|DescLang2|DescLang3
In other words, it would be like I'd joined several queries together such as
SELECT icon FROM Icon
Joined with
SELECT Hata.hata AS fEN, Succes.titre AS tEN, Succes.desc AS dEN
FROM Hata, Succes
WHERE Hata.idLang=Succes.idLang AND Succes.idLang='en-GB'
Joined With
SELECT Hata.hata AS fFR, Succes.titre AS tFR, Succes.desc AS dFR
FROM Hata, Succes
WHERE Hata.idLang=Succes.idLang AND Succes.idLang='fr-FR'
And so on...
Just the problem of ensuring the links between tables (icon 1 with sentence 1)
Here's another sample on how it should (may) look like
+-------+-------+-------+-------+----------------+------------------+------------+-----------------+----------------+------------------+
| icon | fEN | fFR | fJP | tEN | tFR | tJA | dEN | dFR | dJA |
+-------+-------+-------+-------+----------------+------------------+------------+-----------------+----------------+------------------+
| <img> | <img> | <img> | <img> | Hello | Salut | 今日は | Desc in English | Desc in French | Desc in Japanese |
+-------+-------+-------+-------+----------------+------------------+------------+-----------------+----------------+------------------+
| <img> | <img> | <img> | <img> | Goodbye | Au revoir | またね | Desc in English | Desc in French | Desc in Japanese |
+-------+-------+-------+-------+----------------+------------------+------------+-----------------+----------------+------------------+
| <img> | <img> | <img> | <img> | You're welcome | Je vous en pries | どういたしまして | Desc in English | Desc in French | Desc in Japanese |
+-------+-------+-------+-------+----------------+------------------+------------+-----------------+----------------+------------------+
...
I've browsed for SQL reference to try many things but they don't seem to do what I expect (CONCATENATE, UNION, etc...)
I also tried the following query but it gives me an error message.
SELECT Icon.icon, Hata.hata AS fEN,Hata.hata AS fFR,Hata.hata AS fJA
,'FR'.'titre', 'FR'.'desc'
,'JA'.'titre', 'JA'.'desc'
,'UK'.'titre', 'UK'.'desc'
FROM Hata, Icon
LEFT JOIN Succes AS FR ON 'FR'.'idLang' = 'Hata'.'idLang' AND 'FR'.'idLang' = 'fr-FR'
LEFT JOIN Succes AS JA ON 'JA'.'idLang' = 'Hata'.'idLang' AND 'FR'.'idLang' = 'ja-JP'
LEFT JOIN Succes AS UK ON 'UK'.'idLang' = 'Hata'.'idLang' AND 'FR'.'idLang' = 'en-GB'
the message is
Statut SQL: HY000
Error Code: 1000
syntax error, unexpected $end, expecting BETWEEN or IN or SQL_TOKEN_LIKE
but it seems my syntax is good according to sample I've found even on StackOverflow.
I must also specify that I'm using OpenOffice Base and my purpose is publishing a document. Maybe there is something specific to OOo such as LEFT JOIN not implemented but the code get coloured so I think it should be fine.
Thank you for your availability and help.
I really don't get it.
I've tried with MySQL and it does something like an exclusive join
mysql> SELECT titre AS tfr, titre AS ten, titre AS tjp FROM data WHERE idlang=1
-> UNION
-> SELECT null,titre AS ten, null FROM data WHERE idlang=2
-> UNION
-> SELECT null, null, titre as tjp FROM data WHERE idlang=3;
+------------------+------------------+------------------+
| tfr | ten | tjp |
+------------------+------------------+------------------+
| Salut | Salut | Salut |
| Au revoir | Au revoir | Au revoir |
| Je vous en pries | Je vous en pries | Je vous en pries |
| NULL | Hello | NULL |
| NULL | Goodbye | NULL |
| NULL | You're Welcome | NULL |
| NULL | NULL | Konnichiha |
| NULL | NULL | Mata ne |
| NULL | NULL | Douitashimashite |
+------------------+------------------+------------------+
9 rows in set (0.00 sec)
If in the 1st SELECT I do titre AS tfr, null, null the column headers get to null.
mysql> SELECT titre AS tfr, titre AS ten, titre AS tjp FROM data WHERE idlang=1
-> UNION
-> SELECT null,titre AS ten, null FROM data WHERE idlang=2
-> UNION
-> SELECT null, null, titre as tjp FROM data WHERE idlang=3;
+------------------+------------------+------------------+
| tfr | NULL | NULL |
+------------------+------------------+------------------+
| Salut | NULL | NULL |
| Au revoir | NULL | NULL |
| Je vous en pries | NULL | NULL |
| NULL | Hello | NULL |
| NULL | Goodbye | NULL |
| NULL | You're Welcome | NULL |
| NULL | NULL | Konnichiha |
| NULL | NULL | Mata ne |
| NULL | NULL | Douitashimashite |
+------------------+------------------+------------------+
It still doesn't looks like the result I want.
I need to concentrate on that data table to get all in one line but I keep wondering how to achieve this. In principle it is very simple but I can't translate that in SQL.
mysql> DESCRIBE data;
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| id_phrase | int(11) | YES | | NULL | |
| titre | varchar(20) | YES | | NULL | |
| desc | varchar(50) | YES | | NULL | |
| idicon | int(11) | YES | | NULL | |
| idlang | int(11) | YES | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
Actually idicon is redundant with id_phrase (don't really need it so pretend it does not exist).
Thank you.
HERE ARE SOME PROPOSITIONS IF YOU WOULD MEET A RESEMBLING PROBLEM.
NB: The column names and table names may differ from the original question but the problem is the same.
I've been asking this question on another forum and here are 2 queries I tested and can certify are working with MySQL 5.5
Query 1 :
SELECT id_phrase
, idicon
, max(case idlang when 1 then titre end) AS tfr
, max(case idlang when 1 then DESC end) AS dfr
, max(case idlang when 2 then titre end) AS ten
, max(case idlang when 2 then DESC end) AS den
, max(case idlang when 3 then titre end) AS tjp
, max(case idlang when 3 then DESC end) AS djp
FROM DATA
WHERE idlang IN (1, 2, 3)
GROUP BY id_phrase, idicon
ORDER BY id_phrase ASC
Query 2 :
SELECT t1.id_phrase, t1.idicon, t1.titre AS tfr, t1.descr AS dfr, t2.titre AS ten, t2.descr AS den, t3.titre AS tjp, t3.descr AS djp
FROM DATA AS t1
LEFT OUTER JOIN DATA AS t2
ON t1.id_phrase=t2.id_phrase
LEFT OUTER JOIN DATA AS t3
ON t1.id_phrase=t3.id_phrase
WHERE t1.idlang=1 AND t2.idlang=2 AND t3.idlang=3
You're welcome if these queries may help you.
Source (french)