Get total orders by zone - opencart

on admin panel opencart have a world map, and show total orders by country. i can change map by country, and need get total orders by zone, but standart get orders by country. how to change?
public function getTotalOrdersByCountry() {
$query = $this->db->query("SELECT COUNT(*) AS total, SUM(o.total) AS amount, c.iso_code_2 FROM `" . DB_PREFIX . "order` o LEFT JOIN `" . DB_PREFIX . "country` c ON (o.payment_country_id = c.country_id) WHERE o.order_status_id > '0' GROUP BY o.payment_country_id");
return $query->rows;
}
its code from controller

$query = $this->db->query("SELECT COUNT(*) AS total, SUM(o.total) AS amount, z.code as iso_code_2
FROM `" . DB_PREFIX . "order` o
LEFT JOIN `" . DB_PREFIX . "zone` z ON (o.payment_zone_id = z.zone_id)
WHERE o.order_status_id > '0' GROUP BY o.payment_zone_id");

Related

Search for Value and Return All Columns In Which Value Appears

I have the following set of lists of names in a Google Sheet:
╔═══╦════════════╦══════════╦══════════╗
║ ║ A ║ B ║ C ║
╠═══╬════════════╬══════════╬══════════╣
║ 1 ║ Barry ║ Rich ║ David ║
╠═══╬════════════╬══════════╬══════════╣
║ 2 ║ Rich ║ Jeff ║ Michael ║
╠═══╬════════════╬══════════╬══════════╣
║ 3 ║ Bruce ║ Bruce ║ Jeff ║
╠═══╬════════════╬══════════╬══════════╣
║ 4 ║ Rober ║ Barry ║ Joel ║
╠═══╬════════════╬══════════╬══════════╣
║ 5 ║ David ║ Joel ║ Howard ║
╠═══╬════════════╬══════════╬══════════╣
║ 6 ║ Michael ║ Howard ║ Rich ║
╚═══╩════════════╩══════════╩══════════╝
I'm trying to figure out a formula to use that searches for a name and returns all the names that appear in each column the name appears in. For example, if I search for Joel I want to get the entire contents of columns B and C.
You asked for a formula that
...searches for a name and returns all the names that appear in each column the name appears in
Please use the following formula
=query(ArrayFormula(regexextract(
query(flatten(TRANSPOSE(ArrayFormula(column(A2:C)&"-"&A2:C))),
"where Col1 matches '"&textjoin("|",1,(ArrayFormula(if(A2:C=A1,column(A2:C)&"-.*",""))))&"' ")
,"-(.*)")),
"where Col1 is not null ")
You can try following formula:
=IFERROR(INDEX($A:$C,0,SMALL(FILTER(FLATTEN(COLUMN($A:$C)*("Jeff"=$A:$C)),FLATTEN(COLUMN($A:$C)*("Jeff"=$A:$C))>0),COLUMN(A1))),"")
This formula autofill rows, but not columns, so copy it to the right.
try like this:
=VLOOKUP("Joel", A:C, {2, 3}, 0)
next level:
=IFNA(VLOOKUP(A1, Sheet1:A:C, {2, 3}, 0))
next level:
=ARRAYFORMULA(IFNA(VLOOKUP(A1:A, Sheet1:A:C, {2, 3}, 0)))
if more columns:
=ARRAYFORMULA(IFNA(VLOOKUP(A1:A, Sheet1:A:C, COLUMN(B:K), 0)))
if Joel is in B column and you want to return A and C column:
=ARRAYFORMULA(IFNA(VLOOKUP(A1:A, {Sheet1!B:B, Sheet1!A:C}, {2, 4}, 0)))
Are you looking for an output like this:
Let us know if this helps or not.
The main formula is a bit brute force, but pretty straightforward.
But it might have issues depending on how many rows or columns you might have in your data.
=TRANSPOSE(QUERY({TRANSPOSE(A1:C6)},"
where Col1 = '" & F1 & "'
or Col2 = '" & F1 & "'
or Col3 = '" & F1 & "'
or Col4 = '" & F1 & "'
or Col5 = '" & F1 & "'
or Col6 = '" & F1 & "' ",0))
UPDATE:
To put all of the results into a single column, there are several options. You haven't said if you want unique values, or the names sorted, so I'll ignore those aspects, and just stack the results vertically.
One simple way is the use of an undocumented function, FLATTEN, which may be or may not be removed from Sheets at some point.
Added to my original formula, that gives:
=FLATTEN(TRANSPOSE(QUERY({TRANSPOSE(A1:C6)},"
where Col1 = '" & F1 & "'
or Col2 = '" & F1 & "'
or Col3 = '" & F1 & "'
or Col4 = '" & F1 & "'
or Col5 = '" & F1 & "'
or Col6 = '" & F1 & "' ",0)))
But you may want one column stacked on top of another, not a merger of them. In that case, you could try this ugly formula, which needss to repeat the query multiple times, to check how many columns there are in the output. If you have to go this way, I recommend to either save the query results in a helper range, or perhaps submit a new more specific question:
={query({TRANSPOSE(QUERY({TRANSPOSE(A1:C6)},"
where Col1 = '" & F1 & "'
or Col2 = '" & F1 & "'
or Col3 = '" & F1 & "'
or Col4 = '" & F1 & "'
or Col5 = '" & F1 & "'
or Col6 = '" & F1 & "' ",0))},"select Col1 ",0);
if(columns(TRANSPOSE(QUERY({TRANSPOSE(A1:C6)},"
where Col1 = '" & F1 & "'
or Col2 = '" & F1 & "'
or Col3 = '" & F1 & "'
or Col4 = '" & F1 & "'
or Col5 = '" & F1 & "'
or Col6 = '" & F1 & "' ",0)))>1,
query({TRANSPOSE(QUERY({TRANSPOSE(A1:C6)},"
where Col1 = '" & F1 & "'
or Col2 = '" & F1 & "'
or Col3 = '" & F1 & "'
or Col4 = '" & F1 & "'
or Col5 = '" & F1 & "'
or Col6 = '" & F1 & "' ",0))},"select Col2 ",0),
"");
if(columns(TRANSPOSE(QUERY({TRANSPOSE(A1:C6)},"
where Col1 = '" & F1 & "'
or Col2 = '" & F1 & "'
or Col3 = '" & F1 & "'
or Col4 = '" & F1 & "'
or Col5 = '" & F1 & "'
or Col6 = '" & F1 & "' ",0)))>2,
query({TRANSPOSE(QUERY({TRANSPOSE(A1:C6)},"
where Col1 = '" & F1 & "'
or Col2 = '" & F1 & "'
or Col3 = '" & F1 & "'
or Col4 = '" & F1 & "'
or Col5 = '" & F1 & "'
or Col6 = '" & F1 & "' ",0))},"select Col3 ",0),
"")}
or maybe:
=ARRAYFORMULA(FLATTEN(SPLIT(TRIM(REGEXREPLACE(FILTER(A:A&" "&B:B&" "&C:C,
REGEXMATCH(A:A&" "&B:B&" "&C:C, D10)), D10, )), " ")))

sas sum based on row by row and flag

I have a data like below
laonno debit childno credit
1234 4162.98 . .
1234 0.02 . .
. . 1234 1387.66
. . 1234 1387.66
. . 1234 1387.66
I need output as when the debit sum is equals to credit sum then for those observations flag should be generated as mentioned below
laonno debit childno credit flag
1234 4162.98 . . matched
1234 0.02 . . N
. . 1234 1387.66 matched
. . 1234 1387.66 matched
. . 1234 1387.66 matched
The data rows will be dynamic but when the sum of debit matches credit then the following flag should be as "MATCHED" .
If your data is representative, here is one way
data want (drop=s);
if _N_ = 1 then do;
dcl hash h ();
h.definekey ('childno');
h.definedata ('s');
h.definedone ();
dcl hash hh ();
hh.definekey ('laonno');
hh.definedone ();
do until (lr);
set yy(where=(childno)) end=lr;
if h.find() ne 0 then s = credit;
else s = sum(s, credit);
h.replace();
end;
end;
set yy;
s = .;
if h.find(key : laonno) = 0 & round(s, .001) = debit then do;
flag = 'Matched';
hh.ref();
end;
else flag = 'N';
if hh.check(key : childno) = 0 then flag = 'Matched';
run;

Group by with percentages and raw numbers

I have a dataset that looks like this:
I would like to create a table that groups by area and shows the total amount for the area both as a percentage of total amount and as a raw number, as well as the percent of the total number of records/observations per area and total number of records/observations as a raw number.
The code below works to generate a table of raw numbers but does not the show percent of total:
tabstat amount, by(county) stat(sum count)
There isn't a canned command for doing what you want. You will have to program the table yourself.
Here's a quick example using auto.dta:
. sysuse auto, clear
(1978 Automobile Data)
. tabstat price, by(foreign) stat(sum count)
Summary for variables: price
by categories of: foreign (Car type)
foreign | sum N
---------+--------------------
Domestic | 315766 52
Foreign | 140463 22
---------+--------------------
Total | 456229 74
------------------------------
You can do the calculations and save the raw numbers in variables as follows:
. generate total_obs = _N
. display total_obs
74
. count if foreign == 0
52
. generate total_domestic_obs = r(N)
. count if foreign == 1
22
. generate total_foreign_obs = r(N)
. egen total_domestic_price = total(price) if foreign == 0
. sort total_domestic_price
. local tdp = total_domestic_price
. display total_domestic_price
315766
. egen total_foreign_price = total(price) if foreign == 1
. sort total_foreign_price
. local tfp = total_foreign_price
. display total_foreign_price
140463
. generate total_price = `tdp' + `tfp'
. display total_price
456229
And for the percentages:
. generate pct_domestic_price = (`tdp' / total_price) * 100
. display pct_domestic_price
69.212173
. generate pct_foreign_price = (`tfp' / total_price) * 100
. display pct_foreign_price
30.787828
EDIT:
Here's a more automated way to do the above without having to specify individual values:
program define foo
syntax varlist(min=1 max=1), by(string)
generate total_obs = _N
display total_obs
quietly levelsof `by', local(nlevels)
foreach x of local nlevels {
count if `by' == `x'
quietly generate total_`by'`x'_obs = r(N)
quietly egen total_`by'`x'_`varlist' = total(`varlist') if `by' == `x'
sort total_`by'`x'_`varlist'
local tvar`x' = total_`by'`x'_`varlist'
local tvarall `tvarall' `tvar`x'' +
display total_`by'`x'_`varlist'
}
quietly generate total_`varlist' = `tvarall' 0
display total_`varlist'
foreach x of local nlevels {
quietly generate pct_`by'`x'_`varlist' = (`tvar`x'' / total_`varlist') * 100
display pct_`by'`x'_`varlist'
}
end
The results are identical:
. foo price, by(foreign)
74
52
315766
22
140463
456229
69.212173
30.787828
You will obviously need to format the results in a table of your liking.
Here's another approach. I stole #Pearly Spencer's example. It could be generalised to a command. The main message I want to convey is that list is useful for tabulations and other reports, with just usually some obligation to calculate what you want to show beforehand.
. sysuse auto, clear
(1978 Automobile Data)
. preserve
. collapse (sum) total=price (count) obs=price, by(foreign)
. egen pc2 = pc(total)
. egen pc1 = pc(obs)
. char pc2[varname] "%"
. char pc1[varname] "%"
. format pc* %2.1f
. list foreign obs pc1 total pc2 , subvarname noobs sum(obs pc1 total pc2)
+-----------------------------------------+
| foreign obs % total % |
|-----------------------------------------|
| Domestic 52 70.3 315766 69.2 |
| Foreign 22 29.7 140463 30.8 |
|-----------------------------------------|
Sum | 74 100.0 456229 100.0 |
+-----------------------------------------+
. restore
EDIT Here's an essay in egen with similar flavour but leaving the original data in place and new variables also available for export or graphics.
. sysuse auto, clear
(1978 Automobile Data)
. egen total = sum(price), by(foreign)
. egen obs = count(price), by(total)
. egen tag = tag(foreign)
. egen pc2 = pc(total) if tag
(72 missing values generated)
. egen pc1 = pc(obs) if tag
(72 missing values generated)
. char pc2[varname] "%"
. char pc1[varname] "%"
. format pc* %2.1f
. list foreign obs pc1 total pc2 if tag, subvarname noobs sum(obs pc1 total pc2)
+-----------------------------------------+
| foreign obs % total % |
|-----------------------------------------|
| Domestic 52 70.3 315766 69.2 |
| Foreign 22 29.7 140463 30.8 |
|-----------------------------------------|
Sum | 74 100.0 456229 100.0 |
+-----------------------------------------+

how to Create Get Products Api based on Category Id using limit & offset though GET Method & display the api response in json?

<?php
class ControllerSystemProducts1 extends Controller{
private $debugIT=false;
public function getProducts(){
$results = array();
$query = $this->db->query("SELECT DISTINCT *, pd.name AS name, p.image, m.name AS manufacturer, (SELECT price FROM " . DB_PREFIX . "product_discount pd2 WHERE pd2.product_id = p.product_id AND pd2.customer_group_id = '" . (int)$this->config->get('config_customer_group_id') . "' AND pd2.quantity = '1' AND ((pd2.date_start = '0000-00-00' OR pd2.date_start < NOW()) AND (pd2.date_end = '0000-00-00' OR pd2.date_end > NOW())) ORDER BY pd2.priority ASC, pd2.price ASC LIMIT 1) AS discount, (SELECT price FROM " . DB_PREFIX . "product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '" . (int)$this->config->get('config_customer_group_id') . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special, (SELECT points FROM " . DB_PREFIX . "product_reward pr WHERE pr.product_id = p.product_id AND customer_group_id = '" . (int)$this->config->get('config_customer_group_id') . "') AS reward, (SELECT ss.name FROM " . DB_PREFIX . "stock_status ss WHERE ss.stock_status_id = p.stock_status_id AND ss.language_id = '" . (int)$this->config->get('config_language_id') . "') AS stock_status, (SELECT wcd.unit FROM " . DB_PREFIX . "weight_class_description wcd WHERE p.weight_class_id = wcd.weight_class_id AND wcd.language_id = '" . (int)$this->config->get('config_language_id') . "') AS weight_class, (SELECT lcd.unit FROM " . DB_PREFIX . "length_class_description lcd WHERE p.length_class_id = lcd.length_class_id AND lcd.language_id = '" . (int)$this->config->get('config_language_id') . "') AS length_class, (SELECT AVG(rating) AS total FROM " . DB_PREFIX . "review r1 WHERE r1.product_id = p.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating, (SELECT COUNT(*) AS total FROM " . DB_PREFIX . "review r2 WHERE r2.product_id = p.product_id AND r2.status = '1' GROUP BY r2.product_id) AS reviews, p.sort_order FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) LEFT JOIN " . DB_PREFIX . "manufacturer m ON (p.manufacturer_id = m.manufacturer_id) WHERE p.product_id = '" . (int)$this->config->get('config_language_id') . "' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') ."'");
$results=$query->rows;
if(count($results )){
$json['success'] = true;
$json['product_description']= $results ;
}else {
$json['success'] = false;
}
if ($this->debugIt) {
echo '<pre>';
print_r($json);
echo '</pre>';
} else {
$this->response->setOutput(json_encode($json));
}
}
in this code i am trying to get the product description through get method its working fine but along with this i need obtaine the product based on the category id using limit and offset .how can i do this?
Update your code this way. Hope it may be helpful for you
public function getProducts($data){
$results = [];
$sql = "SELECT DISTINCT *, pd.name AS name, p.image, m.name AS manufacturer, (SELECT price FROM " . DB_PREFIX . "product_discount pd2 WHERE pd2.product_id = p.product_id AND pd2.customer_group_id = '" . (int)$this->config->get('config_customer_group_id') . "' AND pd2.quantity = '1' AND ((pd2.date_start = '0000-00-00' OR pd2.date_start < NOW()) AND (pd2.date_end = '0000-00-00' OR pd2.date_end > NOW())) ORDER BY pd2.priority ASC, pd2.price ASC LIMIT 1) AS discount, (SELECT price FROM " . DB_PREFIX . "product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '" . (int)$this->config->get('config_customer_group_id') . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special, (SELECT points FROM " . DB_PREFIX . "product_reward pr WHERE pr.product_id = p.product_id AND customer_group_id = '" . (int)$this->config->get('config_customer_group_id') . "') AS reward, (SELECT ss.name FROM " . DB_PREFIX . "stock_status ss WHERE ss.stock_status_id = p.stock_status_id AND ss.language_id = '" . (int)$this->config->get('config_language_id') . "') AS stock_status, (SELECT wcd.unit FROM " . DB_PREFIX . "weight_class_description wcd WHERE p.weight_class_id = wcd.weight_class_id AND wcd.language_id = '" . (int)$this->config->get('config_language_id') . "') AS weight_class, (SELECT lcd.unit FROM " . DB_PREFIX . "length_class_description lcd WHERE p.length_class_id = lcd.length_class_id AND lcd.language_id = '" . (int)$this->config->get('config_language_id') . "') AS length_class, (SELECT AVG(rating) AS total FROM " . DB_PREFIX . "review r1 WHERE r1.product_id = p.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating, (SELECT COUNT(*) AS total FROM " . DB_PREFIX . "review r2 WHERE r2.product_id = p.product_id AND r2.status = '1' GROUP BY r2.product_id) AS reviews, p.sort_order FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) LEFT JOIN " . DB_PREFIX . "manufacturer m ON (p.manufacturer_id = m.manufacturer_id) LEFT JOIN " . DB_PREFIX . "product_to_category pc ON (p.product_id = pc.product_id) p.product_id = '" . (int)$this->config->get('config_language_id') . "' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') ."'";
if($data['category_id']){
$sql .= " AND pc.category_id =". (int)$data['category_id'];
}
if($data['limit']){
$sql .= " Limit ". $data['limit'];
}
if($data['offset']){
$sql .= " OFFSET ". $data['offset']
}
$query = $this->db->query($sql)
....
....
}

Reshaping Data in "chains" format (stata .DTA file)

I've got data in "chain" format where there are subjects that get a treatment "locks" and subjects, or "links", that are recruited from each "lock". Therefore, my data are shaped both widely and long - how can I write a Stata .DTA program to reshape for running models? My data start like this
idlock idlink1 idlink2 ...
1 10 11 ...
2 20 21 ...
21 30 31 ...
and a link can be come a lock later on, but it is still a part of the chain of the original lock. So, 21 is a link in the chain that starts with 1.
There are up to 5 links for each new lock (idlink1-idlink5)
More details on what you want to do with the data are needed, but the first thing I would do is create some vars that summarize the number of links per lock (or describe the chains). Then you can treat the data as long panel data with the initial lock as the panelid and the timevar as the number of links or nodes in the chain. I assume you have some more variables in the dataset that you want to model (I've generated them as a random DV and some IVs), then you can model whatever it is you want to model using the suite of -xt- commands in Stata (some examples are provided below):
*******************************! BEGIN EXAMPLE
//this first part will input the dataset into stata//
clear
inp id link0 link1 link2 link3 link4
1 1 2 3 4 5
1000 97 98 99 . .
3 . . . . .
4 . . . . .
5 6 7 8 9 10
6 . . . . .
7 . . . . .
8 11 12 13 14 15
9 . . . . .
10 . . . . .
11 . . . . .
12 . . . . .
13 . . . . .
14 . . . . .
15 . . . . .
99 100 . . . . .
100 101 . . . .
101 . . . . .
end
//grab local macro with variables of interest//
unab cou: link*
di "`cou'"
//1. DETERMINE THE INITIAL LOCK//
tempvar pn
g `pn' = .
forval z=0/4{
forval x=1/`=_N' {
replace `pn'= id[_n-`x'] if id==link`z'[_n-`x']
}
}
gen ilock=.
lab var ilock "Initial Lock #"
replace ilock=1 if mi(`pn')
order ilock
l ilock
//2. Links assoc. with each ilock //
**count those with no links established**
count if mi(link0)
//ilocks//
levelsof id if ilock==1, local(ilocks)
foreach n in `ilocks' {
//initial step//
preserve
keep if id==`n'
global s`n' "`=link0' `=link1' `=link2' `=link3' `=link4'"
di "${s`n'}"
global s`n':subinstr global s`n' "." "", all
di "${s`n'}"
restore
}
macro li
//branches off each ilock//
foreach n in `ilocks' {
//branches//
di in red "Branch `b' for macro s`n'"
di as err "${s`n'}"
forval b = 1/10 {
qui token `"${s`n'}"'
while "`1'" != "" {
*di in y "`1'"
preserve
keep if id==`1'
if _N==1 {
global s`n' ${s`n'} `=link0' `=link1' `=link2' `=link3' `=link4'
di "${s`n'}"
global s`n':subinstr global s`n' "." "", all
di in yellow "${s`n'}"
global s`n':list uniq global(s`n')
}
restore
mac shift
}
}
}
//g ilock_number = ilock number if ilocks==branches//
g ilock_number = .
foreach n in `ilocks' {
replace ilock_number = id if id==`n'
di in y "${s`n'}"
global s`n':list uniq global(s`n')
qui token `"${s`n'}"'
while "`1'" != "" {
di in y "`1'"
replace ilock_number = `n' if id==`1'
mac shift
}
}
order ilock_number
sort ilock_number id
count if mi(ilock)
**Decriptives:Count # OF linknodes**
sort ilock id
bys ilock_number: count if mi(ilock)
sort id ilock
bys ilock_number, rc0: g linknodes = _n
order id link* linknodes ilock_n
l id link* ilock linknodes ilock_n, ta clean div
**descriptives**
ta ilock
ta ilock linknodes
**here are all the chains in your data**
levelsof ilock_number, loc(al)
foreach v in `al' {
macro list s`v'
}
// Running models //
**what kind of model do you want to run?**
**assume using ids to identify panels-->
**create fake dv/iv's for models**
drawnorm iv1-iv5
g dv = abs(int(rbinomial(10, .5)))
xtset ilock_number linknodes
xtreg dv iv*, re
**or model some link/lock info like the #links**
bys ilock_number: g ttl_nodes = _N
xtpoisson ttl_nodes iv* dv , re
*******************************! END EXAMPLE
^note: watch for wrapping issues in the code above!