How can I combine 2 different models with union? - django

I want to combine the results of the queries of two different models with union, but sql code parts are different, and Django throws an exception:
Unable to get repr for <class 'django.db.models.query.QuerySet'>
django.db.utils.ProgrammingError: UNION types numeric and character varying cannot be matched
LINE 1: ...order"."update_date", "core_filled"."status", "core_trig..
custom_qs = active_qs.annotate(**{'order_numberx': F('order_number'),
'condition_side': Value('GTE', output_field=CharField()),
}).values("order_number", "account_id",
"order_type", "price",
"buy_sell", "status",
"add_date", "update_date",
"status", "condition_side",
"total_price")
filled_qs = trigger_qs.annotate(**{'order_numberx': F('order_number'),
'total_price': Value(0, output_field=DecimalField())
}).values("order_number", "account_id",
"order_type", "price",
"buy_sell", "status",
"add_date", "update_date",
"status", "condition_side",
"total_price")
orders_qs = active_qs.union(trigger_qs)
SQL QUERY
(SELECT "core_custom"."order_number", "core_custom"."account_id", "core_custom"."order_type", "core_custom"."market_code", "core_custom"."channel_code", "core_custom"."price", "core_custom"."volume", "core_custom"."volume_executed", "core_custom"."buy_sell", "core_custom"."status", "core_custom"."add_date", "core_custom"."update_date", "core_custom"."client_id", "core_custom"."post_only", "core_custom"."status", "core_custom"."total_price", GTE AS "condition_side"
FROM "core_custom"
WHERE ("core_custom"."account_id" = 1549 AND "core_custom"."status" IN (N, P)))
UNION
(SELECT "core_filled"."order_number", "core_filled"."account_id", "core_filled"."order_type", "core_filled"."market_code", "core_filled"."channel_code", "core_filled"."price", "core_triggerorder"."volume", "core_filled"."volume_executed", "core_filled"."buy_sell", "core_filled"."status", "core_filled"."add_date", "core_filled"."update_date", "core_filled"."client_id", "core_filled"."post_only", "core_filled"."status", "core_filled"."condition_side", 0 AS "total_price"
FROM "core_filled"
WHERE ("core_triggerorder"."account_id" = 1549 AND "core_filled"."status" = N))
How can I control order of columns in sql query generated by ORM?

Related

How to filter a Table type column by values of an adjacent column

I want to filter the content of each row of a Table column using values from other columns of the same row of the main table.
I have a table like this, with a Table type column:
Specifically, I want to use the values of FirstLogin to filter the content of the AddIndex tables, using the column SessionStart.
I thought using Table.SelectRows but it seems that it doesn't differentiate well columns of the main table from the embedded table.
Table.SelectRows([AddIndex], each [SessionStart] > _[FirstLogin])
I would appreciate any idea. Thanks.
Assuming your table look like this
Id
FirstLogin
AddIndex
1
01/01/2020
[Table]
2
01/01/2020
[Table]
I have created this calculation. Source is the table above.
let
Source =
Table.FromRecords(
{
[Id = 1 , FirstLogin = #date(2020,01,01),AddIndex = Table.FromRecords({[SessionId = 1, SessionStart = #date(2020,01,01)],[SessionId = 2, SessionStart = #date(2020,02,01)]})],
[Id = 2 , FirstLogin = #date(2020,01,01),AddIndex = Table.FromRecords({[SessionId = 1, SessionStart = #date(2020,01,01)],[SessionId = 2, SessionStart = #date(2020,02,01)]})]
}
),
Step2 = Table.AddColumn(Source, "AddIndexFiltered", (row) => Table.SelectRows(row[AddIndex],each [SessionStart] = row[FirstLogin])),
#"Expanded AddIndexFiltered" = Table.ExpandTableColumn(Step2, "AddIndexFiltered", {"SessionId", "SessionStart"}, {"SessionId", "SessionStart"})
in
#"Expanded AddIndexFiltered"
Output
Id
FirstLogin
AddIndex
SessionId
SessionStart
1
01/01/2020
[Table]
1
01/01/2020
2
01/01/2020
[Table]
1
01/01/2020
You may use following approach:
filter = Table.ReplaceValue(YourLastStep, each [FirstLogin], 0,(a,b,c)=>
Table.SelectRows(a, each [SessionStart] > b),{"AddIndex"})

Custom Function Power Query (M) - Return Table

I need a custom function that takes two parameters, Column1 and Column2, so:
For each Row, return the value of Column1 but only if exists a Value in the Column2 else return null
I have tried this:
let ColumnsFilter = (Tabla,C1,C2)=>
Table.AddColumn(Tabla, "Custom", each if [C2] <> null then [C1] else null)
in
ColumnsFilter
And calling the function:
#"Previous Step" = .....
#"P" = ColumnsFilter(#"Previous Step","Column1","Column2")
in
P
And is not working. clearly I am not using the syntax properly.
In summary I need a table as input and a table as output adding custom columns.
How can I write this?
(Please don't tell me to use the assisted of Power Query, I need to write similar functions manually)
Since you're passing column names as text and individual rows are a record type, you have to use Record.Field to pull the right column (field) from the current row (record).
let
ColumnsFilter = (Tabla as table, C1 as text, C2 as text) as table =>
Table.AddColumn(Tabla, "Custom",
each if Record.Field(_, C2) <> null then Record.Field(_, C1) else null
)
in
ColumnsFilter

Power Bi Compare two tables and get values that do not matched criteria

i have 2 tables and, i would like to check if table 1 (Type_Sorting) == (CCSClassCode_Type) is matched with table 2 (_Type Sorting) == (_CCS Class Type):
for example, you can see vi got the wrong value in table 1 (CCSClassCode_Type)
and, the right value is XLBas you can see in table 2 (_CCS Class Type) not ULM,
the idea of table 2 to check if people type the right values, Please not that table 2 (_CCS Class Type) have duplicate values
thank you in advance :)
You can calculate this like that:
Table 2 =
Var trt =
SELECTCOLUMNS(Table_2, "XX"
, COMBINEVALUES(",",Table_2[_CCS Class Type],Table_2[_Type Sorting]))
return
SUMMARIZECOLUMNS(Table_1[Column1]
, Table_1[CCSClassCode_Type]
, Table_1[Type_Sorting]
, FILTER(ALL(Table_1[CCSClassCode_Type],Table_1[Type_Sorting]), not( COMBINEVALUES(",",Table_1[CCSClassCode_Type],Table_1[Type_Sorting])
in trt )
))

How to remove null rows from MDX query results

How can I remove the null row from my MDX query results?
Here is the query I'm currently working with
select
non empty
{
[Measures].[Average Trips Per Day]
,[Measures].[Calories Burned]
,[Measures].[Carbon Offset]
,[Measures].[Median Distance]
,[Measures].[Median Duration]
,[Measures].[Rider Trips]
,[Measures].[Rides Per Bike Per Day]
,[Measures].[Total Distance]
,[Measures].[Total Riders]
,[Measures].[Total Trip Duration in Minutes]
,[Measures].[Total Members]
} on columns
,
non empty
{
(
[Promotion].[Promotion Code Name].children
)
} on rows
from [BCycle]
where ([Program].[Program Name].&[Madison B-cycle])
;results
This is not a null value however it is one of the children of [Promotion].[Promotion Code Name].Children.
You can exclude that particular value from children using the EXCEPT keyword of MDx.
Example query:
//This query shows the number of orders for all products,
//with the exception of Components, which are not
//sold.
SELECT
[Date].[Month of Year].Children ON COLUMNS,
Except
([Product].[Product Categories].[All].Children ,
{[Product].[Product Categories].[Components]}
) ON ROWS
FROM
[Adventure Works]
WHERE
([Measures].[Order Quantity])
Reference -> https://learn.microsoft.com/en-us/sql/mdx/except-mdx-function?view=sql-server-2017

spring-data Specification and joined subquery

I have the following Named query on my spring-data repository:
#Query("FROM Pedido p JOIN FETCH p.status ps WHERE ps.status IN (?1) AND ps.id IN (SELECT MAX(ps2.id) FROM PedidoStatus ps2 GROUP BY ps2.pedido)")
I'm trying to achieve the same result using the Criteria API and spring-data Specifications, this is what I have so far:
public static Specification<Pedido> byUltimoStatus(final List<PedidoStatus.StatusPedido> ultimoStatus) {
return new Specification<Pedido>() {
public Predicate toPredicate(Root<Pedido> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Expression<PedidoStatus.StatusPedido> status = root.join("status").get("status");
Predicate predicateByStatus = status.in(ultimoStatus);
final Subquery<Long> subQuery = query.subquery(Long.class);
final Root<PedidoStatus> ps = subQuery.from(PedidoStatus.class);
Expression<Long> psId= ps.get("id");
Expression<Long> maxId = builder.max(psId);
subQuery.select(maxId);
subQuery.groupBy(ps.get("pedido").get("id"));
Predicate predicateByUltimoStatus = builder.in(root.join("status").get("id")).value(subQuery);
return builder.and(predicateByStatus, predicateByUltimoStatus);
}
};}
It's still not working, looks like there is an extra
INNERJOIN PedidoStatus
in the result query.
This is the result of the #Query:
select ... from Pedido pedido0_ inner join PedidoStatus status1_ on pedido0_.id=status1_.pedido where (status1_.status in (? , ?)) and (status1_.id in (select max(pedidostat2_.id) from PedidoStatus pedidostat2_ group by pedidostat2_.pedido))
And this is the result of the Criteria API:
select ... from Pedido pedido0_ inner join PedidoStatus status1_ on pedido0_.id=status1_.pedido inner join PedidoStatus status2_ on pedido0_.id=status2_.pedido where (pedido0_.id is not null) and status1_.status IN (?, ?) and (status2_.id in (select max(pedidostat3_.id) from PedidoStatus pedidostat3_ group by pedidostat3_.pedido))
Knowing that this is a very old question, it looks to me like the reason for the duplicate INNERJOIN in the query generated by a CriteriaQuery is that the code building the query, does actually invoke root.join("status") twice. The result of the first invocation should be saved into a local variable, so you can reuse it, instead of joining twice.
First you do:
Expression<PedidoStatus.StatusPedido> status = root.join("status").get("status");
And later you do:
Predicate predicateByUltimoStatus = builder.in(root.join("status").get("id")).value(subQuery);