mdx cross join without intersection - ssas

I've created market basket analysis cube and I'v tried to create query that return cross join of two hierarchies ( they are identical ) and gets the results without intersection. Unfortunately I can't get correct results.
Problem:
I have 2 sets: A {a,b} and B {a,b} and I want to create new set { {a,b} } or at least { {a,b} {b,a} }
My query:
SELECT
{ [Measures].[Transaction Count] } ON COLUMNS,
TopCount(
{
Generate( {[Product].[Product Id].CurrentMember} as MyCellSet,
FILTER(Existing(NonEmptyCrossJoin (
[Product].[Product Id].[Product Id],
[Product 1].[Product Id].[Product Id]
)),[Product 1].[Product Id].CurrentMember.Name <> MyCellSet.CurrentMember.Name))
},
1000,
[Measures].[Transaction Count]
) ON ROWS FROM [Market 1]
Do you have any idea how to redesign above query to get results that looks like cross join without intersection?

Related

Aggregate by another table after annotate

I have next annotate
qs.annotate(
goods_with_sales=Count('goods', filter=Q(goods__history__sales__gt=0)),
)
Same goods_with_sales_percent=goods_with_sales / sum_sales * 100
I need get percent of goods_with_sales to sum of all goods__history__sales. I try it with Window but not happiness...
This is raw sql query:
SELECT
"wb_brand"."id",
"wb_brand"."name",
COUNT("wb_good"."id") FILTER (
WHERE
"wb_stockshistory"."sales" > 0
) AS "goods_with_sales"
FROM
"wb_brand"
LEFT OUTER JOIN "wb_good" ON (
"wb_brand"."id" = "wb_good"."brand_id"
)
LEFT OUTER JOIN "wb_stockshistory" ON (
"wb_good"."id" = "wb_stockshistory"."good_id"
)
GROUP BY
"wb_brand"."id"
Also I tried this with CTE, but not happiness also.
How can I solve it with Django ORM (prefer) or with SQL ?
P.S. Also must be CASE/WHEN condition for divisizon by zero if sum_sales == 0.

SQL - Summarizing Monthly Sales Data

I have two tables that I need to combine, but I can't get to seem the joins to work. The picture has three tables
_date_array2: Has a field DateMonthYr that contains all possible date/yr combinations
_sales_summ_tbl__ => Has 5 fields. Only months with sales show up. For example, you see only three records showing up for the second table. There is no 5/2016, for example, because there were no sales for that month.
My goal is to "pad" the second table to have TotalDemand of 0's for months with no sales. I am very close (see the third table), except I cannot get the PartNumber to show up for dates with no sales.
My guess is that it's due to the RIGHT JOIN. But I'm not sure how to handle this. The output I am hoping for is table 3 but with the part number populated for all entries.
And here is my code (the results from running this code are the third/last table in the picture):
SELECT TmpSalesTbl.PartNumber as PartNumber,
tmp_date_array.CreateDateMonth as CreateDateMonth,
tmp_date_array.CreateDateYear as CreateDateYear,
CASE WHEN TmpSalesTbl.TotalDemand is NULL THEN 0 ELSE TmpSalesTbl.TotalDemand END as TotalDemand
FROM #_sales_summ_tbl__ TmpSalesTbl
RIGHT JOIN #_date_array2 tmp_date_array on tmp_date_array.CreateDateMonthYr = TmpSalesTbl.CreateDateMonthYr
ORDER BY tmp_date_array.CreateDateYear, tmp_date_array.CreateDateMonth
It is more conventional to place the list of all dates first, then left join to the data and whilst using a case expression is fine an alternative is coalesce(). This should ensure all the wanted months/years display:
SELECT
tmpsalestbl.PartNumber AS partnumber
, tmp_date_array.CreateDateMonth AS createdatemonth
, tmp_date_array.CreateDateYear AS createdateyear
, COALESCE(tmpsalestbl.TotalDemand, 0) AS totaldemand
FROM #_date_array2 tmp_date_array
LEFT JOIN #_sales_summ_tbl__ tmpsalestbl ON tmp_date_array.CreateDateMonthYr = tmpsalestbl.CreateDateMonthYr
ORDER BY
tmp_date_array.CreateDateYear
, tmp_date_array.CreateDateMonth
To populate for evey partnumber, on every month, you will need a new subquery:
select distinct PartNumber #_sales_summ_tbl__
And then cross join that to the years/months so you have a complete set of years/months/parts.
SELECT
cj.PartNumber AS partnumber
, tmp_date_array.CreateDateMonth AS createdatemonth
, tmp_date_array.CreateDateYear AS createdateyear
, COALESCE(tmpsalestbl.TotalDemand, 0) AS totaldemand
FROM #_date_array2 tmp_date_array
CROSS JOIN (
SELECT DISTINCT
PartNumber FROM #_sales_summ_tbl__
) cj
LEFT JOIN #_sales_summ_tbl__ tmpsalestbl ON tmp_date_array.CreateDateMonthYr = tmpsalestbl.CreateDateMonthYr
AND cj.PartNumber = tmpsalestbl.PartNumber
ORDER BY
tmp_date_array.CreateDateYear
, tmp_date_array.CreateDateMonth
;

Access Crosstab Query: based on sales totals within TWO date ranges

I'm looking for a way to create an Access crosstab query reporting sales totals by 'Brand', for two different date ranges.:
For Distributor: "DistID" (column, not visible)
Sales Totals: "Sales" (column)
TWO different date ranges: "depDate" for Period 1 and Period 2 (column):
Period1 = Between [forms]![frmRPT_YTDDepl_SF]![BDT1] And [forms]![frmRPT_YTDDepl_SF]![EDT1]
Period2 = Between [forms]![frmRPT_YTDDepl_SF]![BDT2] And [forms]![frmRPT_YTDDepl_SF]![EDT2]
Brands = "DprodBrand" (rows)
Currently, I have TWO separate crosstab queries for each period, working properly. -> CODE BELOW.
I am looking for a way to create ONE query displaying Brand's sales totals for each date range, in two separate columns or one crosstab query.
Period1:
TRANSFORM Sum(tblDepletions_DETAIL.detQuan) AS Sales
SELECT tblProducts_DEPL.DprodBrand
FROM tblDepletions INNER JOIN (tblProducts_DEPL INNER JOIN tblDepletions_DETAIL ON tblProducts_DEPL.DprodZSKU = tblDepletions_DETAIL.detZSKU) ON tblDepletions.depID = tblDepletions_DETAIL.detDeplID
WHERE (((tblDepletions.depDate) Between [forms]![frmRPT_YTDDepl_SF]![BDT1] And [forms]![frmRPT_YTDDepl_SF]![EDT1]) AND ((tblDepletions.depDistID)=132))
GROUP BY tblProducts_DEPL.DprodBrand
ORDER BY tblProducts_DEPL.DprodBrand
PIVOT Format([depDate],"yy")-(Format(Date(),"yy"))+2 In (1,2);
Period2:
TRANSFORM Sum(tblDepletions_DETAIL.detQuan) AS Sales
SELECT tblProducts_DEPL.DprodBrand
FROM tblDepletions INNER JOIN (tblProducts_DEPL INNER JOIN tblDepletions_DETAIL ON tblProducts_DEPL.DprodZSKU = tblDepletions_DETAIL.detZSKU) ON tblDepletions.depID = tblDepletions_DETAIL.detDeplID
WHERE (((tblDepletions.depDate) Between [forms]![frmRPT_YTDDepl_SF]![BDT2] And [forms]![frmRPT_YTDDepl_SF]![EDT2]) AND ((tblDepletions.depDistID)=132))
GROUP BY tblProducts_DEPL.DprodBrand
ORDER BY tblProducts_DEPL.DprodBrand
PIVOT Format([depDate],"yy")-(Format(Date(),"yy"))+2 In (1,2);
Many Thanks!!! ~~ Jacob
Consider simply joining the two saved, crosstab queries like any other pair of queries or tables using the DprodBrand as join key:
SELECT CrosstabQ1.DprodBrand,
CrosstabQ1.[1] As Period1_Year1, CrosstabQ2.[1] As Period2_Year1,
CrosstabQ1.[2] As Period1_Year2, CrosstabQ2.[2] As Period2_Year2
FROM CrosstabQ1
INNER JOIN CrosstabQ2 ON CrosstabQ1.DprodBrand = CrosstabQ2.DprodBrand
Now if you only want one query to do it all, consider the conditional aggregate pivot query since crosstabs cannot be used as subqueries. Here you migrate WHERE to IIF() conditions:
SELECT p.DprodBrand,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT1]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT1])
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 1),
dt.detQuan, NULL)) AS Period1_Year1,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT2]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT2)
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 1),
dt.detQuan, NULL)) AS Period2_Year1,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT1]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT1])
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 2),
dt.detQuan, NULL)) AS Period1_Year2,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT2]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT2])
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 2),
dt.detQuan, NULL)) AS Period2_Year2
FROM tblDepletions d
INNER JOIN (tblProducts_DEPL p
INNER JOIN tblDepletions_DETAIL dt
ON p.DprodZSKU = dt.detZSKU)
ON d.depID = dt.detDeplID
WHERE ((d.depDistID)=132)
GROUP BY p.DprodBrand
ORDER BY p.DprodBrand
As this is Access, it might be simpler to save the two queries leaving out the ORDER BY.
Then create a new query:
SELECT *
FROM Q1
UNION ALL
SELECT *
FROM Q2
ORDER BY DprodBrand
By: Dale Fye (Access MVP):
I'm not sure you need a CrossTab for this.
Select DProdBrand,
SUM(IIF([DepDate] BETWEEN [Forms]![frmRpt_YTDDepl_SF]![BDT1]
AND [[forms]![frmRPT_YTDDepl_SF]![EDT1], [Sales], 0) as Period1,
SUM(IIF([DepDate] Between [forms]![frmRPT_YTDDepl_SF]![BDT2]
AND [forms]![frmRPT_YTDDepl_SF]![EDT2], [Sales], 0) as Period2,
SUM([Sales]) as [Sales Total]
FROM yourTable
GROUP BY DProdBrand
https://www.experts-exchange.com/questions/28978325/Access-Crosstab-Query-based-on-sales-totals-within-TWO-date-ranges.html

SQL on salesforce not applicable

I have this code on SQL and I am trying to use it in Salesforce. I get an error that it does not recognize the JOIN function.
Here is the code :
SELECT
lu_table.Name,
lu_table.id,
primary.Start_date,
primary.end_date,
secondary.metric
FROM primary
LEFT JOIN secondary
ON primary.xyz= secondary.xyz
LEFT JOIN lu_table
ON primary.id = lu_table.id
group by lu_table.Name;
Salesforce has own query language named SOQL. This language has no JOIN function. Here is the reference
SOQL syntax:
SELECT fieldList [subquery][...]
[TYPEOF typeOfField whenExpression[...] elseExpression END][...]
FROM objectType[,...]
[USING SCOPE filterScope]
[WHERE conditionExpression]
[WITH [DATA CATEGORY] filteringExpression]
[GROUP BY {fieldGroupByList|ROLLUP (fieldSubtotalGroupByList)|CUBE (fieldSubtotalGroupByList)}
[HAVING havingConditionExpression] ]
[ORDER BY fieldOrderByList {ASC|DESC} [NULLS {FIRST|LAST}] ]
[LIMIT numberOfRowsToReturn]
[OFFSET numberOfRowsToSkip]
[FOR {VIEW | REFERENCE}[,...] ]
[ UPDATE {TRACKING|VIEWSTAT}[,...] ]
EDIT
You query in SOQL it'd be something like that.
SELECT
Start_date,
end_date,
(SELECT Id, Name FROM lu_table),
(SELECT metric FROM secondary)
FROM primary
WHERE xyz IN (SELECT xyz FROM secondary WHERE condition)
AND Id IN (SELECT id FROM lu_table WHERE condition)
GROUP BY lu_table.Name;
But I'm not sure that in such form the query will not reach SF limits

SQL View - Challenge

I have a small challenge trying to create a "work in progress view"
I'm not convinced my statement is the best or correct and resulted in an error "Subquery returned more than 1 value"
I have three key tables;
Tasks
PurchaseOrderItem
Resource
There is a unique reference field across all the tables e.g. Tasks.TA_SEQ, PurchaseOrderItem.TA_SEQ and Resource.TA_SEQ
I need to sum different totals from all these tables and the relationship are as follows;
1 Task - many PurchaseOrderItem
1 Task - many Resources
I need to sum all the Purchase order cost values (line items can vary) against active purchase orders for the Task and also sum all the resource cost (3 people - quantity can vary) against the task, any help would be much appreciated. if I can make it also any easier any advice would be appreciated.
Part of my Query as it stands;
SELECT
dbo.F_TASKS.TA_SEQ,
(
SELECT
SUM(POI_TOTAL)
From F_PO_ITEM
where POI_FKEY_TA_SEQ = dbo.F_TASKS.TA_SEQ
and POI_FKEY_POH_SEQ in
(
select
POH_SEQ
from F_PO_HEAD
where POH_STATUS in ('DORMANT', 'ACTIVE')
)
) AS [Pending PO Cost],
dbo.F_TASKS.TA_PO_COST AS [PO Cost],
dbo.F_TASKS.TA_LABOUR_COST AS [Labour Cost],
dbo.F_TASKS.TA_LABOUR_COST - SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS) AS [New Labour Cost],
-----------Not Working from
(select
SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS)
from F_TASK_TIME
where TT_FKEY_TA_SEQ = dbo.F_TASKS.TA_SEQ) + dbo.F_TASKS.TA_PO_COST AS [Subcontractor Costs],
(SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS + dbo.F_TASKS.TA_PO_COST)) * 0.12 AS [Subcontractor Uplift],
((SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS + dbo.F_TASKS.TA_PO_COST)) * 0.12) + (SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS + dbo.F_TASKS.TA_PO_COST)) AS [Subcontractor Uplift Total]
-----------Not Working To
FROM dbo.F_TASKS
LEFT OUTER JOIN dbo.F_TASK_TIME
ON dbo.F_TASKS.TA_SEQ = dbo.F_TASK_TIME.TT_FKEY_TA_SEQ
LEFT OUTER JOIN dbo.F_PO_ITEM
ON dbo.F_TASKS.TA_SEQ = dbo.F_PO_ITEM.POI_FKEY_TA_SEQ
WHERE (dbo.F_TASKS.TA_TASK_DESC = 'BREAKDOWN')
AND (dbo.F_TASKS.TA_PO_COST >= 0)
AND (dbo.F_TASKS.TA_STATUS IN ('ACTIVE', 'ASSIGNED', 'COMPLETE'))
GROUP BY dbo.F_TASKS.TA_PO_COST, dbo.F_TASKS.TA_SEQ, dbo.F_TASKS.TA_LABOUR_COST
Rather than trying to fix your SQL, I'm going to propose a different wau of doing it. I couldn';t easily understand all the wheres in your selects in the select clause, so I've just done the first two.
This approach uses LEFT OUTER JOINs to queries which total by ta_seq. These are guaranteed to return only one row/ta_seq as that's how there're grouped:
SELECT
t.TA_SEQ,
isnull(po.poi_total, 0) [Pending PO Cost],
t.TA_PO_COST AS [PO Cost],
t.TA_LABOUR_COST AS [Labour Cost],
t.TA_LABOUR_COST - isnull(tt.other_costs, 0) AS [New Labour Cost],
-- other cols missed
FROM dbo.F_TASKS t
left outer join
(
t.ta_seq, SUM(POI_TOTAL) poi_total
From F_PO_ITEM poi
where POI_FKEY_POH_SEQ in
(
select
POH_SEQ
from F_PO_HEAD
where POH_STATUS in ('DORMANT', 'ACTIVE')
)
group by t.ta_seq
) po on po.ta_seq = t.ta_seq
left outer join
(
select tt.TT_FKEY_TA_SEQ ta_seq, sum(tt.tt_other_costs) other_costs
from F_TASK_TIME tt
group by tt.TT_FKEY_TA_SEQ
) tt on tt.ta_seq = t.ta_seq
WHERE (t.TA_TASK_DESC = 'BREAKDOWN')
AND (t.TA_PO_COST >= 0)
AND (t.TA_STATUS IN ('ACTIVE', 'ASSIGNED', 'COMPLETE'))
GROUP BY t.TA_PO_COST, t.TA_SEQ, t.TA_LABOUR_COST
I've also used table aliases as I find the schema.tablename format is making me blind (and not helping me decode the missed subqueries).
To put in the missing columns, just translate them into additional LEFT OUTER JOINs as above.
Cheers -