Lookup row in another table that has the maximum value among all rows that are related to the current record - powerpivot

There are two tables, say A and B. I want to create a calculated column in A with the following data from B. For a given row i in A, I want the ID of that row in B that has the maximum value among all rows that are related to row i.
For example:
Table A:
ID
1
2
Table B:
ID | A_ID | Value
x | 1 | 100
y | 1 | 200
x | 2 | 400
y | 2 | 300
Desired result:
Table A:
ID | B_ID
1 | y
2 | x
I hope this is clear. A SQL statement as the following one would do the job.
update A set B_ID = (select B.ID from B where B.A_ID = ID order by Value desc limit 1)
The closest I got so far was with LOOKUPVALUE, but it gave me the value of the global MAX, instead of the MAX within the relevant window.

Here is a solution:
=SELECTCOLUMNS(
FILTER(B,[Flow]=CALCULATE(MAX(B[Value])) &&
A[ID]=B[A_ID]),"some name", [ID])

Related

SQL: reverse groupby : EDIT

Is there a build in function in sql, to reverse the order in which the groupby works? I try to groupby a certain key but i would like to have the last inserted record returned and not the first inserted record.
Changing the order with orderby does not affect this behaviour.
Thanx in advance!
EDIT:
this is the sample data:
id|value
-----
1 | A
2 | B
3 | B
4 | C
as return i want
1 | A
3 | B
4 | C
not
1 | A
2 | B
4 | C
when using group by id don't get the result i want.
Question here is how are you identifying last inserted row. Based on your example, it looks like based on id. If id is auto generated, or a sequence then you can definitely do this.
select max(id),value
from your_table
group by value
Ideally in a table design, people uses a date column which holds the time a particular record was inserted, so it is easy to order by that.
Use Max() as your aggregate function for your id:
SELECT max(id), value FROM <table> GROUP BY value;
This will return:
1 | A
3 | B
4 | C
As for eloquent, I've not used it but I think it would look like:
$myData = DB::table('yourtable')
->select('value', DB::raw('max(id) as maxid'))
->groupBy('value')
->get();

Sqlite : Loop through rows and match, break when distinct row encountered

I want to compare two tables A and B, row by row on the basis of a column name.As soon as I encounter a distinct row I want to break.
I want to do this using a query, something like this :
select case
when ( compare row 1 of A and B
if same continue with row+1
else break
)
if all same, then 1
else 0
end
as result
I am not sure how to loop through rows and break? Is it even possible in sqlite?
EDIT
Table looks like this
-------------------------- -----------------------------------
id | name id | name
-------------------------- -----------------------------------
1 | A 1 | A (same)
2 | C 2 | C (same)
3 | B 3 | Z (different break)
4 | K
Both tables have same structure. I want to just compare the names row by row, to see whether there is any order difference.

How do I select rows where only return keys that don't have '1' in column c

Title is confusing I know, I'm just not sure how to word this. Anyway let me describe with a table:
| key | column b | column c |
|-----|----------|----------|
| a | 13 | 2 |
| a | 14 | 2 |
| a | 15 | 1 |
| b | 16 | 2 |
| b | 17 | 2 |
I'd like to select all keys where column c doesn't equal 1, so the select will result in returning only key 'b'
To clarify, my result set should not contain keys that have a row where column c is set to 1. Therefore I'd like a sql query that would return the keys that satisfy the previous statement.
To make my question as clear as possible. From the table above, what I want returned by some sql statement is a result set containing [{b}] based on the fact that key 'a' has at least one row where column c is equal to 1 whereas key 'b' does not have any rows that contain 1 in column c.
SELECT t.[Key]
FROM TableName t
WHERE NOT EXISTS (SELECT 1
FROM TableName
WHERE t.[key] = [key]
AND ColumnC = 1)
GROUP BY t.[Key]
SELECT KEY
FROM WhateverYourTableNameIs
WHERE c <> '1'
I would do this using group by and aggregation:
select [key]
from table t
group by [key]
having sum(case when c = 1 then 1 else 0 end) = 0;
The having clause counts the number of rows that have c = 1. The = 0 says that there are no such rows for a given key.
Elaboration based on other comments:
You asked for ALL keys where column c doesn't equal 1. That is exactly what the query I suggested will give you. The other part of your question so the SELECT will result in returning only key 'b', is ambiguous. The question as asked will give you results from columns A and B. There is nothing in your question to limit the result set. You either need an additional condition to your WHERE clause, or your question is inherently unanswerable.

Merge several columns from two tables into one rows for id in the former table each

If there are a table A and table B. The structure of them are below:
A :
id
1
2
B:
col_1 col_2
m q
n w
How Can I get the results of C which is below by SQL?
id col_1 col_2 col_1 col_2
1 m q n w
2 m q n w
For each data in Table B, they are related with the id in Table A. After concatenating the two table into Table C. once the id in Table C changes(which belongs to the id in Table A), the corresponding rows in Table C change. So in order to get the final Table C, there should be some calculations for getting each data in Table C(col_1, col_2, col_1 col_2)
As far as I understood, you want to get all rows from table B and associate as columns with id from table A.
I think it is impossible with just a query (don't know if a procedure can solve it), but I have an approach that may help (I tested it on MySQL).
SELECT
`a`.`id`,
GROUP_CONCAT(`b`.`key`) AS `keys`,
GROUP_CONCAT(`b`.`value`) AS `values`
FROM `a`, `b`
GROUP BY `a`.`id` ASC;
As result we have:
---- ------ --------
| id | keys | values |
---- ------ --------
| 1 | m,n | 3,4 |
| 2 | m,n | 3,4 |
---- ------ --------
The first key in column keys and first value in column values refers to the first row of table b. The second refers to the second row and so on. This way you will just need to split on the delimiter ',' with some server side code.
I searched for the matching command from Postgres to the MySQL GROUP_CONCAT and found that STRING_AGG may do the same job.
Hope it helps!
As long as you know in advance how many distinct key values can appear in B (and there are not too many), this should work:
select A.id, Once.key k1, Once.value v1, Twice.key k2, Twice.value v2
from A,(select * from B where B.key='m') Once,
(select * from B where B.key='n') Twice;
EDIT: This is the result obtained with the above query:
| ID | K1 | V1 | K2 | V2 |
--------------------------
| 1 | m | 3 | n | 4 |
| 2 | m | 3 | n | 4 |

SQLite - select the newest row with a certain field value

I have an SQLite question which essentially boils down to the following problem.
id | key | data
1 | A | x
2 | A | x
3 | B | x
4 | B | x
5 | A | x
6 | A | x
New data is appended to the end of the table with an auto-incremented id.
Now, I want to create a query which returns the latest row for each key, like this:
id | key | data
4 | B | x
6 | A | x
I've tried some different queries but I have been unsuccessful. How do you select only the latest rows for each "key" value in the table?
use this SQL-Query:
select * from tbl where id in (select max(id) from tbl group by key);
You could split the main task into two subroutine.
You could move with the approach first retrieve all id/key value then get the id for the latest value of A and B keys,
Now you could easly write a query to get latest value for A and B because you have value of id's for both A and B keys.
SELECT *
FROM mytable
JOIN
( SELECT MAX(id) AS maxid
FROM mytable
GROUP BY "key"
) AS grp
ON grp.maxid = mytable.id
Side note: it's best not to use reserved words like keyas identifiers (for tables, fields. etc.)
Without nested SELECTs, or JOINs but only if the field determining "newest" is primary key (e.g. autoincrement):
SELECT * FROM table GROUP BY key DESC;