Wants this Sql Query in Linq - c#

How to write below given Sql Query in Linq?
SELECT
Invoice.ExtInvoiceId AS Id,
Invoice.ExtClientBranchId,
Invoice.CustomerReference,
Invoice.CountryDataSetId,
Invoice.JmsJobNumber,
Invoice.InvoiceDate,
Invoice.TotalAmount,
Invoice.RequestedBy,
Invoice.DateCreated,
PaidTable.Paid,
Invoice.So_Terms_Disc,
'' AS RequestedByValue,
Client.ParentId,
Invoice.CurrencyCode
FROM Invoice
INNER JOIN Client
ON Invoice.ExtClientBranchId = Client.ExtClientBranchId
LEFT OUTER JOIN (
SELECT
ExtInvoiceId,
(CASE WHEN SUM(TotalAmount) = 0 THEN 1 ELSE 0 END) AS Paid
FROM [Transaction] GROUP BY ExtInvoiceId
) AS PaidTable
ON Invoice.ExtInvoiceId = PaidTable.ExtInvoiceId

Hey yes the query looks it has few operations/join to be dealt with , so approach it step by step :
Fetch all the records , using inner join
Try using left outer join
Further simplify the query to the best of what you need.
Also note if you are visual-studio , it gives you this best interface wherein you can get to know at which point your linq is correct and what all options you can use with it.

Related

How to delete duplicates after STRING_AGG?

First of all i've to tell you that i'm a beginner in SQL.
I want to select all the informations related to my PLAN thanks to it's id to put them in a DataGridView in my C# program.
We can affect multiples voltage levels, catenary types etc... to this plan and it would be stored in a table called plans_into_voltage and plans_into_type there.
So when I try to selecet all the informations related to a plan, if it has multiple voltage and/or many catenary types, it would duplicate rows like this :
Then I tried to STRING_AGG but now I have duplicates into the row and I don't know how to avoid that/remove them..
This is my query :
SELECT TOP 20 pinfos.id
, STRING_AGG(pinfos.plan_name, '|')
, STRING_AGG (voltage.name, '|') AS vname
, STRING_AGG(catType.name, '|') AS catname
FROM [allocation_schematic.information].primary_infos pinfos
LEFT JOIN [allocation_schematic.types].plans_into_type pit
ON pinfos.id = pit.id_plan
LEFT JOIN [allocation_schematic.types].catenary_type catType
ON pit.id_type = catType.id
LEFT JOIN [allocation_schematic.types].plans_into_voltage pot
ON pinfos.id = pot.id_plan
LEFT JOIN [allocation_schematic.types].voltage voltage
ON pot.id_voltage = voltage.id
GROUP BY pinfos.id
But i want it like:
I've already check this first solution and this second one but I don't understand how to implement it with my query.
Could someone help me with this please ? I've been on this trouble since 2 days..
Thanks !
How about try this query:
SELECT TOP 20 pinfos.id
, STRING_AGG(pinfos.plan_name, '|')
, STRING_AGG (voltage.name, '|') AS vname
, STRING_AGG(catType.name, '|') AS catname
FROM (
SELECT DISTINCT pinfos.id
pinfos.plan_name,
voltage.name,
catType.name
FROM [allocation_schematic.information].primary_infos pinfos
LEFT JOIN [allocation_schematic.types].plans_into_type pit
ON pinfos.id = pit.id_plan
LEFT JOIN [allocation_schematic.types].catenary_type catType
ON pit.id_type = catType.id
LEFT JOIN [allocation_schematic.types].plans_into_voltage pot
ON pinfos.id = pot.id_plan
LEFT JOIN [allocation_schematic.types].voltage voltage
ON pot.id_voltage = voltage.id
)
GROUP BY pinfos.id
This query is modified accordding this statement:
SELECT STRING_AGG(data)
FROM (
SELECT DISTINCT FROM ...
)
I tested with my table and it works.
All data in my table employee:
Run my demo query:
SELECT emp.deptno, STRING_AGG(emp.ename,',') AS ename from (
SELECT DISTINCT ename, deptno FROM employee) as emp
GROUP BY emp.deptno
Update:
This query does't work as expected.
But Congratulations that you have solved it:
Used multiple queries and joined them thanks to a Dictionary in my c# Program and it works fine now
Hope this helps.

sql join query returns same row multiple times

select distinct "CARIHR"."BLCHKODU", "CARIHR"."BLCRKODU",
"CARIHR"."OZEL_KOD", "CARIHR"."EVRAK_NO",
"CARIHR"."ISLEM_TURU", "CARIHR"."TARIH",
"CARIHR"."BORC", "CARIHR"."TAHSILAT",
"CARIHR"."ACIKLAMA", "CARIHR"."VADE",
"CARIHR"."FATURA_HAREKETI",
"CARIHR"."VF_UYGULA", "CARIHR"."HR_ESLEME",
"CARIHR"."TAKIP", "FATURA"."BLFTKODU",
"FATURA"."BLCRKODU" as "FATURA_BLCRKODU",
"FATURA"."BLCH1KODU", "FATURA"."BLCH2KODU",
"FATURA"."TARIHI", "FATURA"."KAP_FATURA",
"FATURA"."KAP_FATTUR",
"FATURA"."ACIKLAMA" as "FATURA_ACIKLAMA",
"FATURA"."TOPLAM", "FATURA"."TOPLAM_KDV",
"FATURA"."KDV_HARIC",
"FATURA"."KESINTI_TOPLAMI",
"FATURA"."KESINTI1", "FATURA"."KESINTI2",
"FATURA"."KESINTI3", "FATURA"."KESINTI5",
"FATURA"."KESINTI4",
"FATURA"."VADE" as "FATURA_VADE",
"FATURA"."KDV_DURUMU",
"FATURA"."ALIS_SATIS_MUSTAHSIL",
"FATURA"."TAKIP" as "FATURA_TAKIP",
"FATURA"."KESILECEK_1",
"FATURA"."KESILECEK_2",
"FATURA"."KESILECEK_3",
"FATURA"."FATURANOT",
"FATURA"."KESINTI1ORAN",
"FATURA"."KESINTI2ORAN",
"FATURA"."KESINTI3ORAN",
"FATURA"."KESINTI4ORAN",
"FATURA"."KESINTI5ORAN",
"FATURAHR"."BLFHKODU",
"FATURAHR"."BLFTKODU" as "FATURAHR_BLFTKODU",
"FATURAHR"."BLSTKODU",
"FATURAHR"."BLSHKODU", "FATURAHR"."CINSI",
"FATURAHR"."BIRIMI", "FATURAHR"."MIKTARI",
"FATURAHR"."FIYAT", "FATURAHR"."ARATUTAR",
"FATURAHR"."TOPLAMTUTAR",
"FATURAHR"."KDV_ORANI",
"FATURAHR"."KDV_TUTAR", "FATURAHR"."NEM",
"FATURAHR"."KESINTI_TOPLAMI" as "FATURAHR_KESINTI_TOPLAMI",
"CARI"."CARI_KODU", "CARI"."TICARI_UNVANI",
"CARI"."ADI_SOYADI", "CARI"."ADRESI",
"CARI"."VERGI_DAIRESI", "CARI"."VERGI_NO",
"CARI"."ILI", "CARI"."ILCESI",
"CARI"."GRUBU", "CARI"."EMAIL",
"CARI"."CEP_TEL", "CARI"."TELEFON",
"CARI"."FAKS", "CARI"."OZELKOD_1",
"CARI"."OZELKOD_2", "CARI"."OZELKOD_3",
"CARI"."KAYIT_TARIHI",
"CARI"."OZEL_TARIHI", "CARI"."TC_KIMLIK",
"CARI"."BAGKUR_NO", "CARI"."KOYU",
"CARI"."NOTU",
"CARI"."BLCRKODU" as "CARI_BLCRKODU"
from ((("CARIHR" "CARIHR"
left
join "FATURA" "FATURA"
on ("FATURA"."BLCH1KODU" = "CARIHR"."BLCHKODU"))
left
join "FATURAHR" "FATURAHR"
on ("FATURAHR"."BLFTKODU" = "FATURA"."BLFTKODU"))
left
join "CARI" "CARI"
on ("CARI"."BLCRKODU" = "CARIHR"."BLCRKODU"))
I am using DevExpress XtraReport and this is my sql query. When i run this query my 104th row returns 20 times and 59th row returns 5 times etc. I tried a lot of things to solve this but im not good at sql join and i didnt find anything. I cant solve this.
You can use row_number() and select 1st row from each result that will give you unique result.
Also if you can please provide snap shot of your sample data , i can develop query using row_number()

get same result from c# linq as SQL statement

I am trying to figure out how to get all the notifications from relations that get multiple notifications, because i want to combine these notifications to 1 notification so the relation wil only get 1 e-mail instead of multiple.
I created the following SQL statement, which for as far as i can tell does what i want:
select distinct r.Notificatie
, r.RelatieNr
FROM [configuratie].[dbo].[NotificatieRecID] r
join [configuratie].[dbo].[Notificatie] n on r.Notificatie = n.ID
where n.Verzonden = 0
and r.RelatieNr in(select RelatieNr from [configuratie].[dbo].[NotificatieRecID]
group by RelatieNr having count(*) > 1)
order by r.RelatieNr
It returns the following
Notification Relation
3A2A53B9-D92A-4504-874D-5A901AD01041 114147
4C499F6C-53C8-49E0-B529-8B045819BE10 114147
AF4ED8CB-D033-47A4-96AE-F379BB484532 114147
977885C5-4C12-431B-AB72-59383B1824C6 303327
3A2A53B9-D92A-4504-874D-5A901AD01041 303327
4C499F6C-53C8-49E0-B529-8B045819BE10 303327
AF4ED8CB-D033-47A4-96AE-F379BB484532 303327
Later in my c# code i will get all the values from the different notifications and simply combine them but first i need to write this SQL statement in a way i can use it with linq in c#.
I have no idea how to do SELECT DISTINCT, and r.RelatieNr in and group by RelatieNr having count(*) > 1
Could someone provide me with an example? (it does not have to be 1 linq statement, i've kind of figured that's impossible, though i would like as little temporary Lists/Iqueriables since the tables are huge)
You can use the following
var details= (from r in NotificatieRecID
join n in Notificatie on r.Notificatie=n.ID
where n.Verzonden=0 &&
(from t in NotificatieRecID
group t by t.RelatieNr into grp
where grp.Count()>1
select grp.Key).Contains(r.relatieNr)
select new {
Notificate=r.Notificatie,
RelatieNr=r.RelatieNr
}).Distinct();

How to translate SQL statement with multiple join conditions based on subquery to LINQ

This might be one of those situations where plain SQL commands are better than LINQ. Here's a simplified version of the SQL statement I'm trying to translate:
SELECT * FROM IDTable AS idt
INNER JOIN NameTable AS nt ON nt.IDTableID=idt.Id
AND nt.Id= (SELECT TOP(1) Id
FROM NameTable AS nt2
WHERE nt2.IDTableID=11 ORDER BY nt2.DateInserted DESC)
I have the LINQ query to pull records when just joining on IDs and I've seen how to join on multiple columns, but I have no idea how to plug the subquery into the mix.
If this isnt entirely clear, please let me know and I'll edit to elaborate.
Maybe something like this?
var results = from id in db.IDTable
join n in db.NameTable on id.Id equals n.IDTableID
where n.Id = (
from n2 in db.NameTable
where n2.IDTableID = 11
orderby n2.DateInserted desc
).First()
select new { id, n };

NHibernate: hql to criteria query - help needed

I have this hql query, which works perfect:
select m
from Media m
join m.Productlines p
join m.Categories c
join m.Spaces sp
join m.Solutions so
where m.Uid != 0
and p.Uid in (:productlines)
and c.Uid in (13)
and sp.Uid in (52)
and so.Uid in (15,18)
group by m.Uid
But now it needs to be parameterized/made dynamic, not only the parameters, but also the joins (it is possible to select only from Media, without any joins, and so no *.Uid in will be required in this case).
I dont want to mess around with a StringBuilder instance and build the hql query that way, I would rather like to use the Criteria API, but I cant get a
SELECT m.*
....
GROUP BY m.Uid
query to work with Criteria.
If I add a
Projections.GroupProperty("Uid")
to my query, nhibernate selects
SELECT m.Uid
....
GROUP BY m.Uid
which is of course wrong.
After that, I also need to count the unique rows the query returned, as the result is paged.
So, my other query is quite similiar, but I cant find a Criteria equivalent for
SELECT COUNT(DISTINCT m.Uid)
Here is the HQL:
select count(distinct m.Uid)
from Media m
join m.Productlines p
join m.Categories c
join m.Spaces sp
join m.Solutions so
where m.Uid != 0
and p.Uid in (:productlines)
and c.Uid in (13)
and sp.Uid in (52)
and so.Uid in (15,18)
How can this be done with Criteria API?
Please, (N)Hibernate experts - help me with this, I cant find a working solution. Any help is greatly appreciated!
Group columns are implicitly returned as result, but you can add more columns. AFAIK, you can return full entities:
var query = session.CreateCriteria(typeof(Media), "m")
.Add(Projections.GroupProperty("m"))
.Add(Restrictions.NotEq("m.Uid", 0));
// dynamically add filters
if (filterProductLines)
{
query
.CreateCriteria("m.Productlines", "p")
.Add(Restrictions.Eq("p.Uid", productLines));
}
// more dynamic filters of this kind follow here...
IList<Media> results = query.List<Media>();
To count the full number of results you can just build up the same query with different projection:
var query = session.CreateCriteria(typeof(Media), "m")
.SetProjection(Projections.CountDistinct("m.Uid"));
// rest of the query the same way as above
long totalNumberOfResults = query.UniqueResult<long>();
I'm getting unsure about the Projections.GroupProperty("m"), you need to try this. If it doesn't work, you could make it an DetachedQuery that only returns ids:
var subquery = DetachedCriteria.For(typeof(Media), "m")
.Add(Projections.GroupProperty("m.Uid"))
.Add(Restrictions.NotEq("m.Uid", 0));
// add filtering
var query = session.CreateCriteria(typeof(Media), "outer")
.Add(Subqueries.PropertyIn("outer.Uid", subquery));
IList<Media> results = query.List<Media>();
This creates a sql query like this:
select outer.* // all properties of Media to create an instance
from Media outer
where outer.Uid in (
select Uid
from media m
where // filter
)
var count = session.CreateCriteria(typeof(Media))
// Add other criterias...
.SetProjection(Projections.CountDistinct("Id")) // or whatever the id property of Media class is called
.UniqueResult<long>();
As to your GROUP BY question, the query:
SELECT m.*
....
GROUP BY m.Uid
makes no sense because you need to select only columns that appear in the group by clause or aggregate functions. Could you elaborate a little more as to what exactly are you trying to achieve?

Categories

Resources