sparkymark75
sparkymark75

Reputation: 593

Convert SQL query to LINQ to SQL

How do you convert a SQL query with nested SELECT statements to a LINQ statement?

I have the following SQL statement which outputs the results I need but I'm not sure how to replicate this in LINQ .

SELECT X.ITMGEDSC, (SUM(X.[ENDQTY_I]) - SUM(X.[ORDERLINES])) AS AVAIL 
FROM SELECT T1.[MANUFACTUREORDER_I],T2.[ITMGEDSC],T1.[ENDQTY_I],
(SELECT (COUNT(VW.[MANUFACTUREORDER_I]) - 1) 
FROM [PLCD].dbo.[vw_WIP_Srl] VW
WHERE VW.[MANUFACTUREORDER_I] = T1.[MANUFACTUREORDER_I]
GROUP BY VW.[MANUFACTUREORDER_I]) AS ORDERLINES 
FROM [PLCD].dbo.[vw_WIP_Srl] T1 
INNER JOIN [PLCD].dbo.IV00101 T2 ON T2.ITEMNMBR = T1.ITEMNMBR 
GROUP BY T1 [MANUFACTUREORDER_I],T2.[ITMGEDSC],T1.[ENDQTY_I]) AS X
GROUP BY X.ITMGEDSC

ITEMNMBR is the ID of an item including a revision number, for example A1008001. The last 3 numbers denote the revision. So A1008002 are the same item, just differing revisions. In my query I need to treat these as the same item and output only the quantity for the parent item number (A1008). This parent item number is the column IV00101.ITMGEDSC.

The above code would take the following data

MANUFACTUREORDER_I        ITEMNMBR      ENDQTY_I 
MAN00003140               A1048008      15 
MAN00003507               A1048008      1 
MAN00004880               A10048001     15 
MAN00004880               A10048001     15 
MAN00004880               A10048001     15 

and output the following results

ITEMNMBR      QTY 
A1048008      16 
A10048001     13*

As I mentioned at the start, the SQL above gives me the output I'm after but I'm unsure how to replicate this in Linq.

UPDATE - JEFF'S ORIGINAL SOLUTION

var query = from item in db.vw_WIP_Srls
group new { item.MANUFACTUREORDER_I, item.ENDQTY_I } by item.ITEMNMBR into items 
select new
{ 
    ItemNumber = items.Key, 
    QtyAvailable = (from item in items 
           //assumes quantities equal per order number 
           group 1 by item into orders 
           select orders.Key.ENDQTY_I - (orders.Count() - 1)) 
          .Sum()
};

Upvotes: 1

Views: 542

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134861

Here you go. Unfortunately I couldn't see the comment you left me anymore but I believe this should be equivalent. I changed the names to match closely with your query.

var query = from a in db.vw_WIP_Srl
            join b in db.IV00101 on a.ITEMNMBR equals b.ITEMNMBR
            group new { a.MANUFACTUREORDER_I, a.ENDQTY_I } by b.ITMGEDSC into g
            select new
            {
                ITMGEDSC = g.Key,
                AVAIL = (from item in g
                         group 1 by item into orders
                         select orders.Key.ENDQTY_I - (orders.Count() - 1))
                        .Sum()
            };

Upvotes: 1

Related Questions