how to convert SQL select statement to LINQ - sql

Hi i'm new to SQL and LINQ and i need to convert this sql statement to LINQ
select r.*,
(Select name From org_table where org_ID= r.org_ID )org
(Select name From Depart_table where Depart_ID= r.Depart_ID)depart
from reserve_table r
where name like '

try it this way:
var result = from r in reserve_table
where r.name.Contains("something")
select new {
org = (from o in org_table where o.Org_ID = r.Org_ID select o.name)
depart = (from d in Depart_table where d.Depart_ID = r.Depart_ID select d.name)
// add the rest
}

Related

Add an alias for a subquery that I can reference in the main WHERE clause

I want to create an alias for a subquery so I can reference in the WHERE clause from the main query but it keeps throwing me error telling me that the column doesn't exist.
SELECT x.id_lib, (
SELECT sg.nom FROM subgenres sg WHERE (x.id_gen = sg.id)
)as genname, x.id_gen
FROM subgenres_books x WHERE x.id_lib = 1 and genname LIKE 'Satira'
As zip suggests, you can phrase the query as a simple join:
SELECT sb.id_lib, s.nom, sb.id_gen
FROM subgenres_books sb JOIN
subgenres s
ON s.id_gen = sb.id
WHERE sb.id_lib = 1 and s.nom = 'Satira';
However, there seems to be no reason to return the subgenre -- it is constant. So I'm thinking that an EXISTS subquery is appropriate:
SELECT sb.id_lib, sb.id_gen
FROM subgenres_books sb
WHERE sb.id_lib = 1 AND
EXISTS (SELECT 1
FROM subgenres s
WHERE s.id_gen = sb.id
s.nom = 'Satira'
);
Try this:
SELECT x.id_lib, x.id_gen, genname.nom
FROM subgenres_books x inner join
subgenres genname on x.id_gen = genname.id
WHERE x.id_lib = 1 and genname.nom LIKE 'Satira'

How i turned postgres query to query builder format codeigniter?

i want to select datas from many tables here is the code
how to turned this
SELECT a.*, b.penyusun, c.keywords
FROM cb_monograf a
INNER JOIN (
select row_number() over (order by id_monograf) nomer, id_monograf, string_agg(id_penyusun::varchar,'-') penyusun
from cb_penyusun_monograf
group by id_monograf
) b ON a.id_monograf = b.id_monograf
INNER JOIN (
select row_number() over (order by id_monograf) nomer, id_monograf, string_agg(id_keywords::varchar,'-') keywords
from cb_keywords_monograf
group by id_monograf
) c ON a.id_monograf = c.id_monograf
WHERE a.jenis = 'buku'
into somekind of this format
$this->db->select('a.*,b.penyusun')
->from('cb_monograf a')
->join("($subquery1) b","a.id_monograf = b.id_monograf","inner")
->where('jenis', $param_type);
You're not far off - try this:
// Just to keep code a bit clearer
$db = $this->db;
// Firstly build the selects
$db->select('row_number() over (order by id_monograf) nomer, id_monograf, string_agg(id_penyusun::varchar,'-') penyusun')
$db->group_by('id_monograf');
$q1 = $db->get_compiled_select('cb_penyusun_monograf');
$db->select('row_number() over (order by id_monograf) nomer, id_monograf, string_agg(id_keywords::varchar,'-') keywords');
$db->group_by('id_monograf');
$q2 = $db->get_compiled_select('cb_keywords_monograf');
// Final query
$db->select('a.*, b.penyusun, c.keywords');
$db->join("($q1) b",'a.id_monograf = b.id_monograf','inner');
$db->join("($q2) c",'a.id_monograf = c.id_monograf','inner');
$db->where('a.jenis','buku');
$data = $db->get('cb_monograf a')->result_array(); // or row_array()
Note this query can be improved if your postgresl supports USING() (and inner can probably be dropped as well) to this:
$db->select('a.*, b.penyusun, c.keywords');
$db->join("($q1) b",'id_monograf'); // inner may also not be required
$db->join("($q2) c",'id_monograf'); // inner may also not be required
$db->where('a.jenis','buku');
$data = $db->get('cb_monograf a')->result_array(); // or row_array()

SQL query to LINQ INNER JOIN

I need to translate SQL query to LINQ and have no idea how.
I have two tables: Bins and DataFromBins.
DataFromBins contains column BinId which refers to Bins.Id
What my query does is selecting most recent row for each BinId from DataFromBins and joining some data from Bins for these BinIds.
Please help :(
SELECT BinId, Address, Lon, Lat, MaxFillLevel, Distance
FROM (
SELECT DataFromBins.*
FROM (
SELECT DataFromBins.BinId, MAX(DataFromBins.Date) AS Date
FROM DataFromBins
GROUP BY DataFromBins.BinId
) AS latest_records
INNER JOIN DataFromBins ON DataFromBins.BinId = latest_records.BinId
AND DataFromBins.Date = latest_records.Date
) AS most_recent
INNER JOIN Bins ON most_recent.BinId = Bins.Id
I guess you are seeking the code below. The trick is to split your subqueries ;)
suppose _db is your context.
var latestRecords = from t in _db.DataFromBins
group t by t.BinId into g
select new
{
BinId = g.Key,
Date = (from t2 in g select t2.Date).Max()
};
var mostRecents = from itm in latestRecords
join bin in _db.DataFromBins on new {BinId = itm.BinId, Date =itm.Date } equals new {BinId = bin.BinId , Date =bin.Date}
select bin;
var finalQuery = from recent in mostRecents
join bin _db.Bins on recent.BinId equals bin.Id
select new {
bin.BinId,bin.Address, bin.Lon, bin.Lat, bin.MaxFillLevel, bin.Distance
}

Linq to sql - Join 2 tables, select 1 row from right table with a 1 to many relationship

I am trying to select the forum categories and the last post in each respective category. I have been able to accomplish this in SQL using OUTER APPLY, but haven't been able to successfully convert this to LINQ.
Produces the desired result in SQL:
SELECT fc.CategoryID, fc.CategoryName, fc.PostCount, ft.Title, ft.LastPost, ft.LastPostId, ft.TopicId
FROM ForumCategory AS fc
OUTER APPLY
(
SELECT TOP (1) *
FROM ForumTopic
WHERE ForumTopic.CategoryID = fc.CategoryID
ORDER BY ForumTopic.lastpost DESC
) ft
My attempt at converting to LINQ:
Dim query = From fc In ctx.ForumCategories _
Join ft In ctx.ForumTopics On fc.CategoryID Equals ft.CategoryID _
Select New With {
fc.CategoryID,
fc.CategoryName,
fc.PostCount,
ft.Title,
ft.LastPostId,
ft.LastPost.OrderByDescending().First()
}
I am getting an error stating: 'OrderByDescending' is not a member of 'Date?'
You write it as follows:
var q = from fc in ctx.ForumCategories
from ft in (from x in ctx.ForumTopic
where x.CategoryID == fc.CategoryID
order by x.lastpost desc
select new
{
x.Title,
x.LastPost,
x.LastPostId,
x.TopicId
}).Take(1).DefaultIfEmpty()
select new
{
fc.CategoryID,
fc.CategoryName,
fc.PostCount,
ft.Title,
ft.LastPost,
ft.LastPostId,
ft.TopicId
};

Translating from SQL to Linq when having group by and order by

is it possible to transform this sql code into linq?
SELECT top 3 t.tProductIDF, Count(t.tQty)as QtyBought, p.pName, v.vName
From Transactions t, Product p, Vendor v
where t.tProductIDF = p.pID and p.pdeleted = 0 and p.pVendorIDF = v.vID and v.vActive = 1
Group By t.tProductIDF, p.pName, v.vName
Order By QtyBought desc;
i am currently here:
var topProds = (from t in this._entities.Transactions
group t by t.tProductIDF into g
orderby g.Count() descending
select new {g.Key }).Take(3);
but since i cannot access t from the select part, i do not know how i can get pName and vName
var topProds = (from t in this._entities.Transactions
group t by t.tProductIDF into g
orderby g.Count() descending
select new { ProductIDF = g.Key , Qty= g.Sum(cc=>cc.tQty) , Vname = g.Select(cc=>cc.vName).FirstOrDefault() }).Take(3);
Your g hold each row in group.