1st Query: result 32 seconds (1,758,220 rows)
SELECT
CAST(ID.PYYY AS varchar(8))+','+
CAST(ID.SYYY AS varchar(8))+','+
(
SELECT TOP 1 (
CAST(IMM.INVOICE_DATE1 AS varchar(8))+','+
CAST(IDD.QUANTITY AS varchar(20)) +','+
CAST(IDD.PRICE AS varchar(20)) +','+
CAST(IDD.DISCOUNT AS varchar(20)) +','+
CAST(IDD.SWITCH AS varchar(20)) +','+IDD.UNIT
)
FROM INVOICE_DETAIL IDD,INVOICE_MASTER IMM
WHERE
IMM.MASTERNO=IDD.MASTERNO AND
IDD.SYYY=ID.SYYY AND
IDD.PYYY=ID.PYYY
ORDER BY
IMM.MASTERNO DESC
) AS myData
FROM INVOICE_DETAIL ID, INVOICE_MASTER IM
WHERE IM.MASTERNO = ID.MASTERNO
GROUP BY ID.PYYY,ID.SYYY
2nd Query : result 39 seconds (1,758,220 rows)
SELECT
ID.PYYY,ID.SYYY, SQ.INVOICE_DATE1, SQ.QUANTITY, SQ.PRICE,
SQ.DISCOUNT, SQ.SWITCH, SQ.UNIT
FROM
INVOICE_MASTER IM ,INVOICE_DETAIL ID
OUTER APPLY
(
SELECT top(1)
IMM.INVOICE_DATE1, IDD.QUANTITY, IDD.PRICE,
IDD.DISCOUNT, IDD.SWITCH, IDD.UNIT
FROM
INVOICE_DETAIL IDD,INVOICE_MASTER IMM
WHERE
IMM.MASTERNO=IDD.MASTERNO AND
IDD.SYYY=ID.SYYY AND
IDD.PYYY=ID.PYYY
ORDER BY
IMM.MASTERNO DESC
) as SQ
WHERE IM.MASTERNO = ID.MASTERNO
GROUP BY
ID.PYYY, ID.SYYY, SQ.INVOICE_DATE1, SQ.QUANTITY, SQ.PRICE,
SQ.DISCOUNT,SQ.SWITCH,SQ.UNIT
GROUP BY
(unnecessarily it seems) so it's grouping by the values in theAPPLY
also. You can simulate your first query by putting the main part of the query into a derived table or CTE when grouping, thenAPPLY
afterwards. But instead of all this, you should probably just use some kind of aggregation or window functio. Sample data, expected results, your existing table and index definitions, as well as the query plan, would be immensely useful. The question is not really answerable otherwise