Database to return multi-dimensional result - sql

This is a follow-up question to my previous one.
Situation:
Table 1:
+--------------------+--------------------+
| v_id | v_name |
+--------------------+--------------------+
| 1 | v_name1 |
+--------------------+--------------------+
| etc...
Table 2:
+--------------------+--------------------+
| a_id | a_name |
+--------------------+--------------------+
| 1 | a_name1 |
+--------------------+--------------------+
| etc...
Table 3:
+--------------------+--------------------+
| v_id | a_id |
+--------------------+--------------------+
| 1 | 1 |
+--------------------+--------------------+
| 1 | 2 |
+--------------------+--------------------+
| 1 | 3 |
+--------------------+--------------------+
I want to get a join of the two tables:
SELECT t1.*, t2.a_name
FROM `table1` t1
LEFT JOIN `table_3` t3 ON t3.v_id = t1.v_id
LEFT JOIN `table_2` t2 ON t2.a_id = t3.a_id
WHERE t1.id = 1;
The result of this query will be 3 rows for the given tables, each row with the same values from Table 1, just a different a_name from Table 3.
Now, is it possible for me to make a_name an array (of 3 cells in this case)? I think that this is not possible. If it's not, how would I have to build the query so that it would return just one row, with the a_name results joined with a given 'glue' string?
EDIT
If I were to get a result in PHP, I would expect something like:
$result = array(
'v_id' => 1,
'a_name' => array('a_name1', 'a_name2', 'a_name3')
);
or
$result = array(
'v_id' => 1,
'a_name' =>'a_name1, a_name2, a_name3'), # assuming I used ', ' as the glue string
);

I believe you are looking for the GROUP_CONCAT function.
In your query it would look like this:
SELECT t1.*, GROUP_CONCAT(t2.a_name SEPARATOR ',')
FROM `table1` t1
LEFT JOIN `table_3` t3 ON t3.v_id = t1.v_id
LEFT JOIN `table_2` t2 ON t2.a_id = t3.a_id
WHERE t1.id = 1
GROUP BY [list of t1 columns here]
-- update thanks to OMG Ponies.

Use:
SELECT t1.*,
GROUP_CONCAT(DISTINCT t2.a_name SEPARATOR ',')
FROM `table1` t1
LEFT JOIN `table_3` t3 ON t3.v_id = t1.v_id
LEFT JOIN `table_2` t2 ON t2.a_id = t3.a_id
WHERE t1.id = 1
GROUP BY [list of t1 columns here]
Sean Viera's answer works as you pointed out because of the WHERE clause, and because MySQL allows for columns to be omitted from the GROUP BY. It's not a good habit - only MySQL allows this, and such queries will not port to other databases (there's lots of examples on SO).
I added the distinct in the GROUP_CONCAT - didn't think you want duplicates if any exist.

Related

What is the correct way from performance perspective to match(replace) every value in every row in temp table using SQL Server 2016 or 2017?

I am wondering what should I use in SQL Server 2016 or 2017 (CTE, LOOP, JOINS, CURSOR, REPLACE, etc) to match (replace) every value in every row in temp table? What is the best solution from performance perspective?
Source Table
|id |id2|
| 1 | 2 |
| 2 | 1 |
| 1 | 1 |
| 2 | 2 |
Mapping Table
|id |newid|
| 1 | 3 |
| 2 | 4 |
Expected result
|id |id2|
| 3 | 4 |
| 4 | 3 |
| 3 | 3 |
| 4 | 4 |
You may join the second table to the first table twice:
WITH cte AS (
SELECT
t1.id AS id_old,
t1.id2 AS id2_old,
t2a.newid AS id_new,
t2b.newid AS id2_new
FROM table1 t1
LEFT JOIN table2 t2a
ON t1.id = t2a.id
LEFT JOIN table2 t2b
ON t1.id2 = t2b.id
)
UPDATE cte
SET
id_old = id_new,
id2_old = id2_new;
Demo
Not sure if you want just a select here, or maybe an update, or an insert into another table. In any case, the core logic I gave above should work for all these cases.
You'd need to apply joins on update query. Something like this:
Update tblA set column1 = 'something', column2 = 'something'
from actualName tblA
inner join MappingTable tblB
on tblA.ID = tblB.ID
this query will compare eachrow with ids and if matched then it will update/replace the value of the column as you desire. :)
Do the self join only
SELECT t1.id2 as id, t2.id2
FROM table1 t
INNER JOIN table2 t1 on t1.id = t.id
INNER JOIN table2 t2 on t2.id = t.id2
This may have best performance from solutions posted here if you have indexes set appropriately:
select (select [newid] from MappingTable where id = [ST].[id]) [id],
(select [newid] from MappingTable where id = [ST].[id2]) [id2]
from SourecTable [ST]

Oracle Efficiently joining tables with subquery in FROM

Table 1:
| account_no | **other columns**...
+------------+-----------------------
| 1 |
| 2 |
| 3 |
| 4 |
Table 2:
| account_no | TX_No | Balance | History |
+------------+-------+---------+------------+
| 1 | 123 | 123 | 12.01.2011 |
| 1 | 234 | 2312 | 01.03.2011 |
| 3 | 232 | 212 | 19.02.2011 |
| 4 | 117 | 234 | 24.01.2011 |
I have multiple join query, one of the tables(Table 2) inside a query is problematic as it is a view which computes many other things, that is why each query to that table is costly. From Table 2, for each account_no in Table 1 I need the whole row with the greatest TX_NO, this is how I do it:
SELECT * FROM TABLE1 A LEFT JOIN
( SELECT
X.ACCOUNT_NO,
HISTORY,
X.BALANCE
FROM TABLE2 X INNER JOIN
(SELECT
ACCOUNT_NO,
MAX(TX_NO) AS TX_NO
FROM TABLE2
GROUP BY ACCOUNT_NO) Y ON X.ACCOUNT_NO = Y.ACCOUNT_NO) B
ON B.ACCOUNT_NO = A.ACCOUNT_NO
As I understand at first it will make the inner join for all the rows in Table2 and after that left join needed account_no's with Table1 which is what I would like to avoid.
My question: Is there a way to find the max(TX_NO) for only those accounts that are in Table1 instead of going through all? I think it will help to increase the speed of the query.
I think you are on the right track, but I don't think that you need to, and would not myself, nest the subqueries the way you have done. Instead, if you want to get each record from table 1 and the matching max record from table 2, you can try the following:
SELECT * FROM TABLE1 t1
LEFT JOIN
(
SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY account_no ORDER BY TX_No DESC) rn
FROM TABLE2 t
) t2
ON t1.account_no = t2.account_no AND
t2.rn = 1
If you want to continue with your original approach, this is how I would do it:
SELECT *
FROM TABLE1 t1
LEFT JOIN TABLE2 t2
ON t1.account_no = t2.account_no
INNER JOIN
(
SELECT account_no, MAX(TX_No) AS max_tx_no
FROM TABLE2
GROUP BY account_no
) t3
ON t2.account_no = t3.account_no AND
t2.TX_No = t3.max_tx_no
Instead of using a window function to find the greatest record per account in TABLE2, we use a second join to a subquery instead. I would expect the window function approach to perform better than this double join approach, and once you get used to it can even easier to read.
If table1 is comparatiely less expensive then you could think of doing a left outer join first which would considerable decrease the resultset and from that pick the latest transaction id records alone
select <required columns> from
(
select f.<required_columns),row_number() over (partition by account_no order by tx_id desc ) as rn
from
(
a.*,b.tx_id,b.balance,b.History
from table1 a left outer join table2 b
on a.account_no=b.account_no
)f
)g where g.rn=1

Select Minus with fixed column in Oracle sql

I'd like to do a MINUS operation between two tables like these:
table1:
employee_id | job | sector
----------- | ------ | ------
10 | a | 1
10 | a | 2
10 | b | 4
table2:
job | sector
---- | ------
a | 1
a | 2
a | 3
b | 1
b | 4
c | 1
c | 2
and as result I want, for every employee_id, the {job,sector} not connected in table1.
RESULT:
employee_id | job | sector
----------- | --- | ------
10 | a | 3
10 | b | 1
10 | c | 1
10 | c | 2
Is it possible?
I hope I have written in a clear way! Thanks!
First select the complete data set, i.e. employee_id X job/sector. From these remove the existing table1 entries to get the lacking ones. (I've renamed your table table2 to job_sector for readability. I also suppose you have an employee table.)
select e.employee_id, js.job, js.sector
from employee e
cross join job_sector js
minus
select employee_id, job, sector
from table1;
Left join, where t2 is null
select t1.*
from table1 t1
let join table2 t2
on t1.job = t2.job
and t1.sector = t2.sector
where t2.job is null
This sounds like just a left join (or not in or not exists):
select 10 as employee_id, t2.*
from table2 t2 left join
table1 t1
on t2.job = t1.job and t2.sector = t1.sector
where t1.job is null;
I am a bit confused on how you get the employee id if the tables are not linked.
If you have multiple employees in t1, then you can do:
select e.employee_id, t2.*
from (select distinct employee_id from t1) e cross join
table2 t2 left join
table1 t1
on t2.job = t1.job and t2.sector = t1.sector and
e.employee_id = t1.employee_id
where t1.job is null;
You can simply achieve it by doing a left join. You query will look something like this:
SELECT T2.*
FROM TABLE2 T2 LEFT JOIN
TABLE1 T1
ON T2.JOB = T1.JOB AND T2.SECTOR = T2.SECTOR
WHERE T1.JOB IS NULL;
Though table must be linked in order to get the employee id.

How do you exclude another table from a query in SQL Server?

Let's assume you have the following two SQL Server tables:
t1:
|----------------------------------------------|
|name | day_planed | day_canceled | discription|
|----------------------------------------------|
|alpha| 2015-11-02 | 2015-11-01 | some |
|alpha| 2015-11-02 | 2015-10-30 | text |
|beta | 2015-11-02 | 2015-11-01 | here |
|----------------------------------------------|
t2:
|----------------------------------------------|
|name | day_planed | day_canceled | discription|
|----------------------------------------------|
|alpha| 2015-11-02 | 2015-10-30 | text |
|----------------------------------------------|
In an query of t1 I now want every entry except those of t2. I already tried something similar to
SELECT *
FROM t1 AS A
LEFT JOIN t2 as B ON (A.name = B.name
AND A.day_planed = B.day_planed
AND A.day_canceled != B.day_canceled)
Unfortunately I don't get it why it does not exclude the row from t2 in the query of t1.
A second question would be, if there is actual an easy way to make a query of t1 without t2 by just returning the row with the maximum description. I tried looking into it in SQL Server, but could only find the first identifier, which does not work for this "wonderful" implementation of sql...
There are a few ways to do it in this "wonderful" implementation.
SELECT * FROM t1
EXCEPT
SELECT * FROM t2
is one. Another is:
SELECT *
FROM t1
WHERE NOT EXISTS
( SELECT *
FROM t2
WHERE t2.name = t1.name
AND t2.day_planed = t1.day_planed
AND t2.day_canceled = t1.day_canceled
)
Or you could use LEFT JOIN and check for rows that didn't match with WHERE t2.name IS NULL after your ON clause. Like what you have but with = instead of !=
SELECT t1.*
FROM t1
LEFT JOIN t2
ON t2.name = t1.name
AND t2.day_planed = t1.day_planed
AND t2.day_canceled = t1.day_canceled
WHERE t2.name IS NULL;
If you want to check every column (including discription), go with EXCEPT.
You are just missing a where clause and a condition on discription. You also need to change != to =.
SELECT *
FROM t1 AS A
LEFT JOIN t2 as B ON (A.name = B.name
AND A.day_planed = B.day_planed
AND A.day_canceled = B.day_canceled
AND A.discription = B.discription)
WHERE B.Name IS NULL

SQL Query - Get count of two columns from two tables

Table 1:
TicketNumber | Rules
---------------------------
PR123 | rule_123
PR123 | rule_234
PR123 | rule_456
PR999 | rule_abc
PR999 | rule_xyz
Table2:
TicketNumber | Rules
---------------------------
PR123 | rule_123
PR123 | rule_234
PR999 | rule_abc
NOTE: Both tables have the same structure: same column names but different count.
NOTE: Both tables have same set of TicketNumber values
CASE 1:
If I need ticket and rules count of each ticket from table1, the query is:
Select [TicketNo], COUNT([TicketNo]) AS Rules_Count from [Table1] group by TicketNo
This will give me output in format :
ticketNumber | Rules_Count
---------------------------
PR123 | 3
PR999 | 9
CASE 2: (NEED HELP WITH THIS)
Now, the previous query gets the ticket and the count of the ticket of only 1 table. I need the count of the same ticket (since both have same set of tkt nos) in table2 also.
I need result in this way:
ticketNumber | Count(ticketNumber) of table1 | Count(ticketNumber) of table2
---------------------------------------------------------------------------------
PR123 | 3 | 2
PR999 | 2 | 1
Both Table1 and table2 have the same set of ticket nos but different counts
How do i get the result as shown above?
A simpler solution from a "statement point of view" (without COALESCE that maybe it's not so easy to understand).
Pay attention to the performances:
Select T1.TicketNumber,T1.Rules_Count_1,T2.Rules_Count_2
FROM
(
Select [TicketNumber], COUNT([TicketNumber]) AS Rules_Count_1
from [Table1] T1
group by TicketNumber) T1
INNER JOIN
(
Select [TicketNumber], COUNT([TicketNumber]) AS Rules_Count_2
from [Table2] T2
group by TicketNumber
) T2
on T1.TicketNumber = T2.TicketNumber
SQL Fiddle Demo
You can do this with a full outer join after aggregation (or an inner join if you really know that both tables have the same tickets:
select coalesce(t1.TicketNo, t2.TicketNo) as TicketNo,
coalesce(t1.Rules_Count, 0) as t1_Rules_Count,
coalesce(t2.Rules_Count, 0) as t2_Rules_Count
from (Select [TicketNo], COUNT([TicketNo]) AS Rules_Count
from [Table1]
group by TicketNo
) t1 full outer join
(Select [TicketNo], COUNT([TicketNo]) AS Rules_Count
from [Table2]
group by TicketNo
) t2
on t1.TicketNo = t2.TicketNo;
SELECT A.center,
A.total_1st,
B.total_2nd
FROM (SELECT a.center,
Count (a.dose1) AS Total_1st
FROM table_1 a
GROUP BY a.center) A
INNER JOIN (SELECT b.center,
Count (b.dose2) AS Total_2nd
FROM table_2 b
GROUP BY b.center) B
ON a.center = b.center
ORDER BY A.center