INNER JOIN Alias sintax - inner-join

I have this
SELECT
p.id,
p.name,
p.code,
clA.code as claCode,
sclA.code as sclaCode,
clB.code as clbCode,
sclB.code as sclbCode,
clC.code as clcCode,
sclC.code as sclcCode
FROM
products p
INNER JOIN catleathers clA
ON p.catleather_id_a = clA.id
INNER JOIN subcatleathers sclA
ON p.subcatleather_id_a = sclA.id
INNER JOIN catleathers clB
ON p.catleather_id_b = clB.id
INNER JOIN subcatleathers sclB
ON p.subcatleather_id_b = sclB.id
INNER JOIN catleathers clC
ON p.catleather_id_c = clC.id
INNER JOIN subcatleathers sclC
ON p.subcatleather_id_c = sclC.id
But I need something like this
function getdatatableajaxcost()
{
$this->load->library('datatables');
$this->datatables
->select("
products.id as productid,
products.code as code,
products.name as name,
clA.code as claCode,
sclA.code as sclaCode,
clB.code as clbCode,
sclB.code as sclbCode,
clC.code as clcCode,
sclC.code as sclcCode,
products.details", FALSE)
->from('products')
->join('catleathers clA', 'products.catleather_id_a = clA.id', 'INNER')
->join('subcatleathers sclA', 'products.subcatleather_id_a = sclA.id', 'INNER')
->join('catleathers clB', 'products.catleather_id_a = clB.id', 'INNER')
->join('subcatleathers sclB', 'products.subcatleather_id_a = sclB.id', 'INNER')
->join('catleathers clC', 'products.catleather_id_a = clC.id', 'INNER')
->join('subcatleathers sclC', 'products.subcatleather_id_a = sclC.id', 'INNER')
->group_by("products.id");
$this->datatables->unset_column('productid');
$this->datatables->unset_column('image');
echo $this->datatables->generate();
Some help please!

Solved!
Thanks all!
->select("
products.id as productid,
products.image as image,
products.code as code,
products.name as name,
categories.name as cname,
subcategories.name as subcategory,
products.cost,
products.price,
clA.code as claCode,
sclA.code as sclaCode,
clB.code as clbCode,
sclB.code as sclbCode,
clC.code as clcCode,
sclC.code as sclcCode,
catSoleA.code as catSoleACode,
subcatSoleA.code as subcatSoleACode,
catSoleB.code as catSoleBCode,
subcatSoleB.code as subcatSoleBCode,
catSoleC.code as catSoleCCode,
subcatSoleC.code as subcatSoleCCode,
products.details", FALSE)
->from('products')
->join('categories', 'products.category_id=categories.id', 'left')
->join('subcategories', 'products.subcategory_id=subcategories.id', 'left')
->join('catleathers clA', 'products.catleather_id_a = clA.id', 'INNER')
->join('subcatleathers sclA', 'products.subcatleather_id_a = sclA.id', 'INNER')
->join('catleathers clB', 'products.catleather_id_b = clB.id', 'INNER')
->join('subcatleathers sclB', 'products.subcatleather_id_b = sclB.id', 'INNER')
->join('catleathers clC', 'products.catleather_id_c = clC.id', 'INNER')
->join('subcatleathers sclC', 'products.subcatleather_id_c = sclC.id', 'INNER')
->join('catsoles catSoleA', 'products.catsole_id_a = catSoleA.id', 'INNER')
->join('subcatsoles subcatSoleA', 'products.subcatsole_id_a = subcatSoleA.id', 'INNER')
->join('catsoles catSoleB', 'products.catsole_id_b = catSoleB.id', 'INNER')
->join('subcatsoles subcatSoleB', 'products.subcatsole_id_b = subcatSoleB.id', 'INNER')
->join('catsoles catSoleC', 'products.catsole_id_c = catSoleC.id', 'INNER')
->join('subcatsoles subcatSoleC', 'products.subcatsole_id_c = subcatSoleC.id', 'INNER')
->group_by("products.id");

Related

Convert SQL query to Linq2db

Some one help me to convert SQL query to linq2db join query.
Below is my query.
var query = from a in _accountRepository.Table
join b in _documentRepository.Table on a.ID equals b.AccountID
join c in _documentTypeRepository.Table on b.DocumentTypeID equals c.ID
where a.CompanyID == companyID && b.CompanyID == companyID
&& c.CompanyID == companyID
&& a.IsActive && !a.IsDeleted && c.IsInvoice
&& b.IsActive && !b.IsDeleted
&& b.Date.Date >= fromDate.Date && b.Date.Date <=
toDate.Date
&& (b.AccountID == accountID || accountID == null)
&& (costcenterID.Contains(b.CostCenterID) || costcenterID == null)
&& a.AccountTypeID == (int)DefaultAccountTypes.Customer
group b by new { a.DisplayName, a.ID } into g
select new SalesByCustomerModel
{
AccountID = g.Key.ID,
DisplayName = g.Key.DisplayName,
InvoiceCount = g.Count(),
Sales = g.Sum(x => (x.SubTotal - x.Discount)),
SalesWithTax = g.Sum(x => x.Total),
Tax = g.Sum(x => x.Tax)
};
I have to add this. How can I achive with linq2db.
INNER JOIN ( SELECT ROW_NUMBER() OVER(PARTITION by DocumentID ORDER BY DocumentID) AS SrNo,
DocumentID
FROM DocumentDetail
WHERE (DocumentItemID = #itemID OR #itemID IS NULL)
AND CompanyID = #companyID ) D ON D.DocumentID = B.ID AND SrNo = 1
Linq2db supports window functions, and we can write details subquery and add join:
var details =
from d in _documentDetailRepository.Table
where (d.DocumentItemID == itemID || itemID == null)
&& d.CompanyID == companyID
select new
{
d.DocumentID,
SrNo = Sql.Ext.RowNumber().Over()
.PartitionBy(d.DocumentID)
.OrderBy(d.DocumentID)
.ToValue()
};
// Then your query can be extended
var query =
from a in _accountRepository.Table
join b in _documentRepository.Table on a.ID equals b.AccountID
join d in details on new { DocumentID = b.Id, SrNo = 1 } equals new { d.DocumentID, d.SrNo }
...

migrate query sybase to oracle with sign "*="

Hello guys i have this query in sybase with this sign *=, I use in oracle LEFT OUTER JOIN but i dont if right.
Query in sybase:
select
right(( "00" +convert(varchar(2), cta_consol.cod_correo)) , 2) +
right(("000000000" + convert(varchar(11), cta_consol.num_cta_cte)), 9)
from
t_cuenta_consolidada cta_consol,
t_cuenta_corriente ctacte ,
t_empresa empresa,
t_comuna comuna,
t_comuna comuna_CtaCte,
t_ciudad ciudad,
t_ciudad ciudad_CtaCte ,
t_cta_cte_param param
where
empresa.ide = cta_consol.ide_cliente and
empresa.cod_comuna = comuna.codigo and
comuna.cod_ciudad = ciudad.codigo and
ctacte.cod_comuna = comuna_CtaCte.codigo and
comuna_CtaCte.cod_ciudad = ciudad_CtaCte.codigo and
cta_consol.num_cta_cte = ctacte.num_cta_cte and
cta_consol.num_cta_cte *= param.num_cta_cte
cta_consol.num_cta_cte *= param.num_cta_cte
query migrate to oracle:
select
SUBSTR(('00' || CAST(cta_consol.cod_correo AS VARCHAR2(2))),-2) ||
SUBSTR(('000000000' || CAST(cta_consol.num_cta_cte AS VARCHAR2(11))),-9)
from
t_cuenta_consolidada cta_consol
LEFT OUTER JOIN t_cta_cte_param param ON cta_consol.num_cta_cte = param.num_cta_cte,
t_cuenta_corriente ctacte,
t_empresa empresa,
t_comuna comuna,
t_ciudad ciudad
where
empresa.ide = cta_consol.ide_cliente AND
empresa.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
ctacte.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
cta_consol.num_cta_cte = ctacte.num_cta_cte
LEFT OUTER JOIN t_cta_cte_param param ON cta_consol.num_cta_cte = param.num_cta_cte,
I have compared the amount of registration of each query, and it is not the same
You can mix modern ANSI join syntax with the old proprietary Oracle join syntax, but the order is important.
It's usually easier and less confusing to either do ANSI:
select
SUBSTR(('00' || CAST(cta_consol.cod_correo AS VARCHAR2(2))),-2) ||
SUBSTR(('000000000' || CAST(cta_consol.num_cta_cte AS VARCHAR2(11))),-9)
from
t_cuenta_consolidada cta_consol
LEFT JOIN t_cta_cte_param param ON cta_consol.num_cta_cte = param.num_cta_cte
JOIN t_cuenta_corriente ctacte ON cta_consol.num_cta_cte = ctacte.num_cta_cte
JOIN t_comuna comuna ON ctacte.cod_comuna = comuna.codigo
JOIN t_empresa empresa ON empresa.ide = cta_consol.ide_cliente AND empresa.cod_comuna = comuna.codigo
JOIN t_ciudad ciudad ON comuna.cod_ciudad = ciudad.codigo
WHERE ...
Or old Oracle style:
select
SUBSTR(('00' || CAST(cta_consol.cod_correo AS VARCHAR2(2))),-2) ||
SUBSTR(('000000000' || CAST(cta_consol.num_cta_cte AS VARCHAR2(11))),-9)
from
t_cuenta_consolidada cta_consol,
t_cta_cte_param param,
t_cuenta_corriente ctacte,
t_empresa empresa,
t_comuna comuna,
t_ciudad ciudad
where
empresa.ide = cta_consol.ide_cliente AND
empresa.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
ctacte.cod_comuna = comuna.codigo AND
comuna.cod_ciudad = ciudad.codigo AND
cta_consol.num_cta_cte = ctacte.num_cta_cte AND
cta_consol.num_cta_cte = param.num_cta_cte (+)

Does the left join order matter in linq query (EF Core 2)?

I have book table which has a relationship with three tables UserFavorites, UserRates, DiscountItems and last one (DiscountItems) has a relationship with Discounts table so I want to load discount with book if it exist
When create linq left join query with this order (join userfavoirtes then discountitems then discount then userate) generated SQL code is fine as expected
But when change order like below (join userfavoirtes then userate then discountitems then discount) generated query only contain first two join only
var books = (from b in result
join uf in UnitOfWork.Context.UserFavorites
on new { b.Id, RelatedType = RelatedTypeEnum.Book, UserId = userId }
equals new { Id = uf.RelatedId, uf.RelatedType, uf.UserId } into buf
from f in buf.DefaultIfEmpty()
join di in UnitOfWork.Context.DiscountItems
on b.Id equals di.BookId into bdi
from di in bdi.DefaultIfEmpty()
join d in UnitOfWork.Context.Discounts
on (di != null ? di.DiscountId : 0) equals d.Id into bd
from d in bd.DefaultIfEmpty()
join ur in UnitOfWork.Context.UserRates
on new { b.Id, UserId = userId }
equals new { Id = ur.BookId, UserId = ur.CreatedBy } into bur
from r in bur.DefaultIfEmpty()
select new BookViewModel
{
Id = b.Id,
Title = b.Title,
Price = b.Price,
BookImage = SetDefaultImageIfNoImage(b.BookImage),
IsFavorite = f != null ? f.IsFavorite : false,
Rate = bur.Any() ? Math.Round(bur.Average(a => a.Value), 1) : 0,
Discount = d
})
.OrderBy(a => a.CategoryId)
.ThenBy(a => a.Authors)
.Take(10).ToList();
this is generated sql query
SELECT *FROM [Book] AS [a]
LEFT JOIN [UserFavorites] AS [uf] ON (([a].[Id] = [uf].[RelatedId]) AND (3 = [uf].[RelatedType])) AND [uf].[UserId] IS NULL
LEFT JOIN [DiscountItems] AS [di] ON [a].[Id] = [di].[BookId]
LEFT JOIN [Discounts] AS [d] ON CASE
WHEN [di].[Id] IS NOT NULL
THEN [di].[DiscountId] ELSE 0
END = [d].[Id]
LEFT JOIN [UserRates] AS [ur] ON ([a].[Id] = [ur].[BookId]) AND [ur].[CreatedBy] IS NULL
WHERE ((([a].[Active] = 1) AND ([a].[Id] <> 62)) AND ([a].[Status] = 1))
but when write join with this order
var books = (from b in result
join uf in UnitOfWork.Context.UserFavorites
on new { b.Id, RelatedType = RelatedTypeEnum.Book, UserId = userId }
equals new { Id = uf.RelatedId, uf.RelatedType, uf.UserId } into buf
from f in buf.DefaultIfEmpty()
join ur in UnitOfWork.Context.UserRates
on new { b.Id, UserId = userId }
equals new { Id = ur.BookId, UserId = ur.CreatedBy } into bur
from r in bur.DefaultIfEmpty()
join di in UnitOfWork.Context.DiscountItems
on b.Id equals di.BookId into bdi
from di in bdi.DefaultIfEmpty()
join d in UnitOfWork.Context.Discounts
on (di != null ? di.DiscountId : 0) equals d.Id into bd
from d in bd.DefaultIfEmpty()
select new BookViewModel
{
Id = b.Id,
Title = b.Title,
Price = b.Price,
BookImage = SetDefaultImageIfNoImage(b.BookImage),
IsFavorite = f != null ? f.IsFavorite : false,
Rate = bur.Any() ? Math.Round(bur.Average(a => a.Value), 1) : 0,
Discount = d
})
.OrderBy(a => a.CategoryId)
.ThenBy(a => a.Authors)
.Take(10).ToList();
generated SQL query contains only the first two joins
SELECT *
FROM [Book] AS [a]
LEFT JOIN [UserFavorites] AS [uf] ON (([a].[Id] = [uf].[RelatedId]) AND (3 = [uf].[RelatedType])) AND [uf].[UserId] IS NULL
LEFT JOIN [UserRates] AS [ur] ON ([a].[Id] = [ur].[BookId]) AND [ur].[CreatedBy] IS NULL
WHERE ((([a].[Active] = 1) AND ([a].[Id] <> 62)))

SQL query select

I am using MSSQL Server and Nodejs with npm mssql. I need to build a query.
Explanation:
Need to select Users from table that did not receive emails today or never receive.
Query example:
SELECT * FROM dbo.Users u
LEFT JOIN dbo.userEmailHistory ueh
ON u.id = ueh.userId
WHERE IsNull(sDate, '') = ''
OR CONVERT(date,sDate)>=CONVERT(date,DATEADD(day,1,getdate()))
Then:
Need to select the user favorite brand. I am doing async. So the code is looking like this:
function getUserSalesByMalls(params, callback) {
var usersArray = [];
var targetID = params.type;
async.eachLimit(params, 1, function (user, cb) {
sqlRequest("
SELECT TOP 1 bts.BrandCategoryID as title, b.title as brand, b.id
FROM dbo.Users st JOIN SaleView ss ON (st.ID=ss.userID)
JOIN Sales sa ON (sa.ID=ss.SaleID)
JOIN Brands b ON (b.ID=sa.BrandID)
JOIN KEY_BrandcategoryToSale bts ON (bts.SaleID=sa.ID)
WHERE st.ID="+**user.id**+"
GROUP BY bts.BrandCategoryID, b.title, b.id
ORDER BY COUNT(bts.BrandCategoryID) desc",
function (err, result) {
user.favBrand = result;
console.log(user);
usersArray.push(user);
cb();
})
}, function () {
callback(null, usersArray)
})
}
Then:
I need to select top 2 sales by user favorite brand that were most viewed in period 14 days and user never seen it:
function getUserSalesByMalls(params, callback) {
var usersArray = [];
var targetID = params.type;
async.eachLimit(params, 1, function (user, cb) {
sqlRequest("
`SELECT DISTINCT TOP 2 s.id as saleId, s.title, s.description, s.imageUrl, count(sv.saleId) as mostViewsPeriod14Days, s.guid, stm.mallId as mallId, brand.title as brandTitle FROM dbo.Sales s
INNER JOIN dbo.SalesToMall stm ON s.id = stm.saleId
INNER JOIN dbo.SaleView sv ON s.id = sv.saleId
INNER JOIN dbo.Brands brand ON s.brandID = brand.id
WHERE (sv.date <= GETDATE())
AND (sv.date >= GETDATE() - 14) AND s.isActive = 1 AND s.isHotSale = 1 AND b.id = "+user.favBrandId+"
AND s.id NOT IN (SELECT DISTINCT sv2.saleId FROM dbo.SaleView sv2
WHERE sv2.userId = "+user.id+")
GROUP BY s.id, s.title, s.description, s.imageUrl, s.guid, stm.mallId, brand.title
ORDER BY COUNT(sv.saleId) DESC`",
function (err, result) {
user.salesByBrand = result;
console.log(user);
usersArray.push(user);
cb();
})
}, function () {
callback(null, usersArray)
})
}
And then last one: i need to select 3 suggestions for the user by mall id that were most viewed in period 14 days and user never seen it:
function getUserSalesByMalls(params, callback) {
var usersArray = [];
var targetID = params.type;
async.eachLimit(params, requestPerLimit, function (user, cb) {
setTimeout(function () {
sqlRequest("SELECT DISTINCT TOP 3 s.id as saleId, s.title, s.description, s.imageUrl, count(sv.saleId) as mostViewsPeriod14Days, s.guid, stm.mallId as mallId, brand.title as brandTitle
FROM dbo.Sales s
INNER JOIN dbo.SalesToMall stm ON s.id = stm.saleId
INNER JOIN dbo.SaleView sv ON s.id = sv.saleId
INNER JOIN dbo.Brands brand ON s.brandID = brand.id
WHERE (sv.date <= GETDATE())
AND (sv.date >= GETDATE() - 14)
AND s.isActive = 1 AND s.isHotSale = 1
AND stm.mallId = "+user.mallId+"
AND s.id NOT IN (SELECT DISTINCT sv2.saleId
FROM dbo.SaleView sv2
WHERE sv2.userId = "+user.id+")
GROUP BY s.id, s.title, s.description, s.imageUrl, s.guid, stm.mallId, brand.title
ORDER BY COUNT(sv.saleId) DESC", function (err, result) {
if (!result) {
cb();
} else if (result.length == 3) {
sqlInsert("INSERT INTO UserEmailHistory (userID,sDate,targetID) VALUES (" + user.id + ",CONVERT(datetime,DATEADD(hour," + utc_diff + ",getdate()))," + targetID + ")");
console.log("USER WITH 3 SALES BY MALL");
user.sales = result;
console.log(user);
usersArray.push(user);
cb();
}
})
}, requestPerMillisecond)
}, function () {
callback(null, usersArray)
})
}
My question is:
Is there any way to combine and build only one query and get all necessary data regarding my explanation?

How to do this SQL in LINQ

Morning i would like to know how to do this bit of (MS) SQL in LINQ...
SELECT CONVERT(CHAR(10),orderDate,110) AS OrderDate,
SUM(1) AS TotalOrders
FROM Orders
WHERE OrderDate>getdate()-30
GROUP BY CONVERT(CHAR(10),orderDate,110)
ORDER BY OrderDate DESC
Many thanks in advance.
UPDATE
I ended using and edited version of the solutions provided below, thought i would share it...
using (DataDataContext dc = new DataDataContext())
{
var query = from o in dc.Orders
where o.orderDate > DateTime.Now.AddDays(-30)
let dt = o.orderDate
group o by new DateTime(dt.Year, dt.Month, dt.Day) into g
select new OrderCounts
{
OrderDate = String.Format("{0:d}", g.Key.Date),
TotalOrders = g.Count()
};
query.GroupBy(o => o.OrderDate);
query.OrderBy(o => o.OrderDate);
return query.ToList();
}
var result =(from s in Orders
where s.OrderDate > DateTime.Now.AddDays(-30)
group s by new { date = s.OrderDate.ToString() } into g
// or use ((DateTime)s.OrderDate).ToShortDateString() instead of s.OrderDate.ToString()
select new
{
OrderDate = g.Key.date,
TotalOrders = g.Count()
}).OrderByDescending(x=>x.OrderDate);;
The query will be
var query = from o in res
where o.OrderDate > DateTime.Now.AddDays(-30)
orderby o.OrderDate descending
group o by o.OrderDate into g
select new
{
OrderDate = g.Key.Date.ToString("MM/dd/yyyy")
,
TotalOrders = g.Sum(i=> 1)
};
OR by Lambda expression
var query= res
.Where(i => i.OrderDate > DateTime.Now.AddDays(-30))
.OrderByDescending(o => o.OrderDate)
.GroupBy(g => g.OrderDate)
.Select(s => new { OrderDate = s.Key.Date.ToString("MM/dd/yyyy"), TotalOrders = s.Sum(i => 1) });

Resources