SQL subtract alias and create another - sql

i would like to subtract the "alias" i created called "SALES" & "GP" and create a new column call GP
SELECT OEEL.invoicedt, UCASE(OEEL.whse) AS Whse, OEEL.orderno, OEEL.ordersuf,
OEEL.custno, UCASE(OEEL.shipto) AS Shipto, UCASE(OEEL.slsrepin) AS Slsrepin,
UCASE(OEEL.slsrepout) AS Slsrepout, OEEL.returnfl, OEEL.netamt, OEEL.wodiscamt,
OEEL.discamtoth, OEEL.qtyship, OEEL.commcost, ICSS.csunperstk,
UCASE(ICSD.name) AS Name, UCASE(ICSD.region) AS Region,
UCASE(OEEL.prodcat) AS Prodcat, UCASE(SASTA.descrip) AS Descrip,
UCASE(OEEL.transtype) AS Transtype, UCASE(ARSS.user2) AS User2,
OEEL.transdt, ICSS.transdt AS "ICSS.Transdt", ICSD.transdt AS "ICSD.Transdt",
SASTA.transdt AS "SASTA.Transdt", ARSS.transdt AS "ARSS.Transdt",
{ fn CURDATE() } AS CURDATE1, { fn CURTIME() } AS CURTIME2,
OEEL.lineno,
CASE
WHEN OEEL.returnfl = '0' THEN (OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth)
ELSE (-1*(OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth))
END AS "SALES",
CASE
WHEN OEEL.returnfl = '0' THEN (OEEL.qtyship*OEEL.commcost*NVL(ICSS.csunperstk,1))
ELSE (-1*OEEL.qtyship*OEEL.commcost*NVL(ICSS.csunperstk,1))
END AS "COST"
FROM { oj
{ oj
{ oj
{ oj PUB.oeel OEEL
LEFT OUTER JOIN PUB.icss ICSS
ON OEEL.cono = ICSS.cono
AND OEEL.shipprod = ICSS.prod
AND OEEL.icspecrecno = ICSS.icspecrecno
}
LEFT OUTER JOIN PUB.icsd ICSD
ON OEEL.cono = ICSD.cono AND OEEL.whse = ICSD.whse
}
LEFT OUTER JOIN PUB.sasta SASTA
ON OEEL.cono = SASTA.cono AND OEEL.prodcat = SASTA.codeval
}
LEFT OUTER JOIN PUB.arss ARSS
ON OEEL.cono = ARSS.cono
AND OEEL.custno = ARSS.custno
AND OEEL.shipto = ARSS.shipto
}
WHERE (OEEL.cono = 1)
AND (OEEL.invoicedt BETWEEN { d '2014-06-02' } AND { d '2014-06-03' })
AND (SASTA.codeiden IN ('C', 'c'))
ORDER BY OEEL.custno, OEEL.shipto, OEEL.prodcat

Add the following at last column
(CASE WHEN OEEL.returnfl = '0' THEN (OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth) ELSE (-1*(OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth)) END) - (CASE WHEN OEEL.returnfl = '0' THEN (OEEL.qtyship*OEEL.commcost*NVL(ICSS.csunperstk,1)) ELSE (-1*OEEL.qtyship*OEEL.commcost*NVL(ICSS.csunperstk,1)) END) AS GP

Related

How to perform SQL "SELECT SUM(item.cost * item.amount)... " query

im trying to write equivalent of SQL query:
SELECT tax.name as tax, SUM(item.cost * item.amount) as total FROM Invoices inv
JOIN InvoiceItems item ON( item.invoice = inv.id )
JOIN Taxes tax ON( tax.id = it.tax )
WHERE inv.id = 1
GROUP BY tax.id
I can't figure out how to "add" total column to the query, my code is as follows
val res = Invoices
.innerJoin(InvoiceItems, { Invoices.id }, { InvoiceItems.invoice })
.innerJoin(Taxes, { InvoiceItems.tax }, { Taxes.id })
.slice( Taxes.name.alias("tax"), InvoiceItems.cost, InvoiceItems.amount )
.select { Invoices.id eq 1 }
Is it even possible to do it this way or i have to do it later in code?
You can use TimesOp within Expression.build{} block, like this:
val total = Expression.build { Invoices.cost * Invoices.amount }
val taxAndTotal = Invoices.innerJoin(InvoiceTaxes).innerJoin(Taxes)
.slice(Taxes.name, total)
.select{ Invoices.id eq 1 }
.groupBy(Taxes.id)
.map { it[Taxes.name] to it[total] }
I did not find how can we use times like InvoiceItems.cost times InvoiceItems.amount, but you can construct your own TimesOp object like this:
val taxAlias = Taxes.alias("tax")
val itemAlias = InvoiceItems.alias("item")
val invoiceAlias = Invoices.alias("inv")
println(invoiceAlias
.innerJoin(itemAlias, { invoiceAlias[Invoices.id] }, { itemAlias[InvoiceItems.invoice] })
.innerJoin(taxAlias, { itemAlias[InvoiceItems.tax] }, { taxAlias[Taxes.id] })
.slice(
taxAlias[Taxes.name].alias("tax"),
TimesOp(
itemAlias[InvoiceItems.cost],
itemAlias[InvoiceItems.amount],
InvoiceItems.amount.columnType
).sum().alias("total"))
.select { invoiceAlias[Invoices.id] eq 1 }
.groupBy(taxAlias[Taxes.id])
.prepareSQL(QueryBuilder(false))
)
Outputs the following sql for h2 syntax:
SELECT TAX.NAME tax, SUM((ITEM.COST) * (ITEM.AMOUNT)) total FROM INVOICES inv
INNER JOIN INVOICEITEMS item ON INV.ID = ITEM.INVOICE
INNER JOIN TAXES tax ON ITEM.TAX_ID = TAX.ID
WHERE INV.ID = 1
GROUP BY TAX.ID

I try to get results from table with multiple where and/or clauses Query Builder

i try to get results from table with multiple where and/or clauses.
My SQL statement is:
select *
from ceri.movimentacao_parcela_repasse mpr
inner join ceri.movimentacao_parcela mp on (mp.id_movimentacao_parcela = mpr.id_movimentacao_parcela)
inner join ceri.pedido p on (p.id_pedido = mp.id_pedido)
inner join ceri.produto pd on (pd.id_produto = p.id_produto)
where mpr.id_repasse = 4
and mpr.in_repasse_aberto = 'S'
and ( (pd.id_grupo_produto = 1 and p.id_situacao_pedido_grupo_produto = 7 ) or (pd.id_grupo_produto = 2
and p.id_situacao_pedido_grupo_produto = 17) )
My Code in Laravel is:
first attempt
->where('movimentacao_parcela_repasse.id_repasse', '=', DB::raw('4'))
->where('movimentacao_parcela_repasse.in_repasse_aberto', '=', DB::raw('\'S\''))
->where(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('1')) //-- 1 Pesquisa
->where('produto.id_situacao_pedido_grupo_produto',DB::raw('7')); // 7 -- Finalizado
})
->orWhere(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('2')) //2 Certidão /
->where('produto.id_situacao_pedido_grupo_produto',DB::raw('17')); //17 -- Finalizado
});
// RESULT
and ("produto"."id_grupo_produto" = 1 and "pedido"."id_situacao_pedido_grupo_produto" = 7) or ("produto"."id_grupo_produto" = 2 and "pedido"."id_situacao_pedido_grupo_produto" = 17)
second attempt
->where('movimentacao_parcela_repasse.id_repasse', '=', DB::raw('4'))
->where('movimentacao_parcela_repasse.in_repasse_aberto', '=', DB::raw('\'S\''))
->where(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('1'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('7'))
->orWhere(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('2'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('17'));
});
});
// RESULT
and ("produto"."id_grupo_produto" = 1 and "pedido"."id_situacao_pedido_grupo_produto" = 7 or ("produto"."id_grupo_produto" = 2 and "pedido"."id_situacao_pedido_grupo_produto" = 17))
I do not want the way i wanted
and ( (pd.id_grupo_produto = 1 and p.id_situacao_pedido_grupo_produto = 7 ) or (pd.id_grupo_produto = 2 and p.id_situacao_pedido_grupo_produto = 17) )
Try this:
->where('movimentacao_parcela_repasse.id_repasse', '=', DB::raw('4'))
->where('movimentacao_parcela_repasse.in_repasse_aberto', '=', DB::raw('\'S\''))
->where(function($query) {
->where(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('1'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('7'))
})
->orWhere(function($query) {
$query->where('produto.id_grupo_produto',DB::raw('2'))
->where('pedido.id_situacao_pedido_grupo_produto',DB::raw('17'));
});
});

Translating SQL results to LINq with join of literal

All,
This is my first post to this forum and I have searched all throughout this site to find an answer to my question, but it looks like there is not an example of what I need to do.
Below is a SQL query I need to adapt to a LINQ statement:
select COUNT(pe2.*)
from SomeTable pe1
inner join SomeTable pe2 on (pe2.Id=pe1.Id and pe2.TypeCode='X')
where pe1.TypeCode='Y'
I have tried to join this as illustrated below, but it doesn't work:
var query = (from pe2 in SomeTable
join pe1 in SomeTable
on new { pe1.Id } equals new {pe2.Id }
where pe2.TypeCode == "X"
&& pe1.TypeCode == "Y"
select pe2).Count();
Since the TypeCode is HardCoded you can pass it to the where clause
select pe2.*
from SomeTable pe1
inner join SomeTable pe2 on pe2.Id=pe1.Id
where pe1.TypeCode='Y'
and pe2.TypeCode='X'
And here it's how I would do it in linq
var l1 = new List<dynamic> { new { Id = 1, Code = "X" }, new { Id = 2, Code = "Y" } };
var l2 = new List<dynamic> { new { Id = 1, Code = "Y" }, new { Id = 2, Code = "X" } };
//lambda expression
l1.Join(l2,
x => x.Id,
y => y.Id,
(x, y) => new { Pe1 = x, Pe2 = y })
.Where(x => x.Pe1.Code == "Y" && x.Pe2.Code == "X")
.Select(x => x.Pe2);
//query...
from x in l1
join y in l2 on x.Id equals y.Id
where x.Code == "Y"
&& y.Code == "X"
select y
from x in l1
from y in l2
where x.Id == y.Id
&& x.Code == "Y"
&& y.Code == "X"
select y

onchage dropdown data not getting refreshed in codeigniter

I have following code to load data in website based on location selected, on change the ajax is getting fired and getting value in controller and from controller to model and going into where clause for sql by the result of sql is not getting showed on website.But always enters into else loop of model
View:
$(document).on('change','#delvloc',function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = this.value; // anchors do have text not values.
$.ajax({
url: 'index.php?route=product/category/newfunc',
data: {'title': title}, // change this to send js object
type: "get",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
Controller:
public function newfunc(){
$data = array(
'title' => $this->request->get['title']
);
$this->load->model('catalog/product');
$this->model_catalog_product->getProducts($data);
}
Model:
public function getProducts($data = array()) {
$sql="SELECT p.product_id,p.city, (SELECT AVG(rating) AS total FROM monster_review r1 WHERE r1.product_id = p.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating, (SELECT price FROM monster_product_discount pd2 WHERE pd2.product_id = p.product_id AND pd2.customer_group_id = '1' 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 monster_product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '1' 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 FROM monster_product p LEFT JOIN monster_product_description pd ON (p.product_id = pd.product_id) LEFT JOIN monster_product_to_store p2s ON (p.product_id = p2s.product_id) WHERE pd.language_id = '1' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '0'"
if (!empty($data['title'])) {
$sql .= " and p.city='". $data['title']. "' GROUP BY p.product_id";
}
else{$sql .= " and p.city='Pune' GROUP BY p.product_id";}
}
My HTML:
Delivery Location:
<select name="delvloc" id="delvloc" style="width: 100px;" ">
<?php foreach ($city as $user_group) { ?>
<?php if ($user_group['city'] == $user_group_id) { ?>
<option value="<?php echo $user_group['user_group_id']; ?>" selected="selected"><?php echo $user_group['city']; ?></option>
<?php } else { ?>
<option value="<?php echo $user_group['city']; ?>"><?php echo $user_group['city']; ?></option>
<?php } ?>
<?php } ?>
</select>
</li>
In Model
function getProducts($data) {
$sql="SELECT p.product_id,p.city, (SELECT AVG(rating) AS total FROM monster_review r1 WHERE r1.product_id = p.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating, (SELECT price FROM monster_product_discount pd2 WHERE pd2.product_id = p.product_id AND pd2.customer_group_id = '1' 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 monster_product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '1' 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 FROM monster_product p LEFT JOIN monster_product_description pd ON (p.product_id = pd.product_id) LEFT JOIN monster_product_to_store p2s ON (p.product_id = p2s.product_id) WHERE pd.language_id = '1' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '0'"; # Mssing ; here
if (!empty($data['title']))
{
$sql .= " and p.city='". $data['title']. "' GROUP BY p.product_id";
}
else{
$sql .= " and p.city='Pune' GROUP BY p.product_id";
}
$query = $this->db->query($sql);
$result = $query->result_array();
return $result;
}
In Controller
function newfunc()
{
$data = array(
'title' => $this->request->get['title']
);
$this->load->model('catalog/product');
$result = $this->model_catalog_product->getProducts($data);
$response['data'] = '';
if (empty($result))
{
$response['data'] = false;
}
else {
$response['data'] = $result;
}
echo json_encode($response);
}

SQL Query IF Statment

Im trying to add a if else type function in the below sql query
SELECT OEEL.invoicedt, UCASE(OEEL.whse) AS Whse, OEEL.orderno, OEEL.ordersuf, OEEL.custno, UCASE(OEEL.shipto) AS Shipto, UCASE(OEEL.slsrepin) AS Slsrepin,
UCASE(OEEL.slsrepout) AS Slsrepout, OEEL.returnfl, OEEL.netamt, OEEL.wodiscamt, OEEL.discamtoth, OEEL.qtyship, OEEL.commcost, ICSS.csunperstk, UCASE(ICSD.name) AS Name,
UCASE(ICSD.region) AS Region, UCASE(OEEL.prodcat) AS Prodcat, UCASE(SASTA.descrip) AS Descrip, UCASE(OEEL.transtype) AS Transtype, UCASE(ARSS.user2) AS User2,
OEEL.transdt, ICSS.transdt AS "ICSS.Transdt", ICSD.transdt AS "ICSD.Transdt", SASTA.transdt AS "SASTA.Transdt", ARSS.transdt AS "ARSS.Transdt", { fn CURDATE() } AS CURDATE1, { fn CURTIME() } AS CURTIME2,
OEEL.lineno
FROM { oj { oj { oj { oj PUB.oeel OEEL LEFT OUTER JOIN
PUB.icss ICSS ON OEEL.cono = ICSS.cono AND OEEL.shipprod = ICSS.prod AND OEEL.icspecrecno = ICSS.icspecrecno } LEFT OUTER JOIN
PUB.icsd ICSD ON OEEL.cono = ICSD.cono AND OEEL.whse = ICSD.whse } LEFT OUTER JOIN
PUB.sasta SASTA ON OEEL.cono = SASTA.cono AND OEEL.prodcat = SASTA.codeval } LEFT OUTER JOIN
PUB.arss ARSS ON OEEL.cono = ARSS.cono AND OEEL.custno = ARSS.custno AND OEEL.shipto = ARSS.shipto }
WHERE (OEEL.cono = 1) AND (OEEL.invoicedt BETWEEN { d '2014-06-02' } AND { d '2014-06-03' }) AND (SASTA.codeiden IN ('C', 'c'))
ORDER By OEEL.custno, OEEL.shipto, OEEL.prodcat
i would the if to be something like
if OEEL.returnfl = False THEN (OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth) AS "SALES"
Else (-1*(OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth)) AS "SALES"
You can add CASE Statement in your query
CASE WHEN OEEL.returnfl = 'False' THEN (OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth) ELSE (-1*(OEEL.netamt-OEEL.wodiscamt-OEEL.discamtoth)) END AS "SALES"