Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

drasmus's avatar

Proper use of 'selectSub()'

This is a part of a query to generate a report. Basically, I want to get the sum of each of the last recorded quantity of items per given group (iws.itemGid) prior to the said date ($dateMin). I've tried looking for possible related correlated queries but haven't found any for this specific scenario. Is there a more elegant way to reduce the 'raw' parts for this subquery? ('i' in i.id is a table found outside of the query declared in the main body of the query)

I feel that I'm doing something wrong here as well since it says that it returns multiple values when I omit the ->limit(1) when all I intend to do is just get the sum of each query (for the quantity of each group's quantity prior to the said date).

->selectSub(function($query) use ($dateMin) {

    $query->select(DB::raw("(ISNULL((SELECT TOP 1 (iws.stockDonated + iws.stockPurchased) FROM [lcovid].[dbo].[itemWeeklySnapshots] iws WHERE (iws.itemGID = 5) AND (iws.itemID = i.id) AND (weekStamp < " . $dateMin . ") ORDER BY weekStamp DESC), 0) + " .
    "ISNULL((SELECT TOP 1 (iws.stockDonated + iws.stockPurchased) FROM [lcovid].[dbo].[itemWeeklySnapshots] iws WHERE (iws.itemGID = 3) AND (iws.itemID = i.id) AND (weekStamp < " . $dateMin . ") ORDER BY weekStamp DESC), 0) + " .
    "ISNULL((SELECT TOP 1 (iws.stockDonated + iws.stockPurchased) FROM [lcovid].[dbo].[itemWeeklySnapshots] iws WHERE (iws.itemGID = 4) AND (iws.itemID = i.id) AND (weekStamp < " . $dateMin . ") ORDER BY weekStamp DESC), 0) + " .
    "ISNULL((SELECT TOP 1 (iws.stockDonated + iws.stockPurchased) FROM [lcovid].[dbo].[itemWeeklySnapshots] iws WHERE (iws.itemGID = 6) AND (iws.itemID = i.id) AND (weekStamp < " . $dateMin . ") ORDER BY weekStamp DESC), 0) + " .
    "ISNULL((SELECT TOP 1 (iws.stockDonated + iws.stockPurchased) FROM [lcovid].[dbo].[itemWeeklySnapshots] iws WHERE (iws.itemGID = 7) AND (iws.itemID = i.id) AND (weekStamp < " . $dateMin . ") ORDER BY weekStamp DESC), 0)" .
    ")"))
    ->from('itemWeeklySnapshots as iws')
    ->limit(1);

            //dd($query);
        }, 'sTotal')

For comparison, this is what I did for the other columns:

->selectSub(function($query) use ($dateMin) {
            $query->select(DB::raw('(iws.stockDonated + iws.stockPurchased)'))
            ->from('itemWeeklySnapshots as iws')
            ->where([['iws.itemGID', '=', '6'], ['iws.weekStamp' , '<', $dateMin]])
            ->whereColumn('iws.itemID', 'i.id') //['iws.itemID', '=', '[i].[id]']
            ->orderBy('iws.weekStamp', 'desc')
            ->limit(1);
        }, 'sPhar')
0 likes
0 replies

Please or to participate in this conversation.