Could Cross Apply be used in this query?

Y.N 80 Reputation points
2024-01-19T02:31:13.2633333+00:00

Here is a demo of my actual table:

create table #demo (ID int, ItemID int, QTY int)
insert into #demo values
(1,101,3),(2,102,1),(3,101,4),(4,102,2),(5,103,3)

I have written a query:

SELECT t2.ID,t2.QTY,t2.ItemID,t1.TotalQTY
FROM (SELECT ItemId,SUM(QTY) AS TotalQTY
      FROM #demo AS t1
      GROUP BY ItemId) AS t1
INNER JOIN #demo AS t2 ON t1.ItemId = t2.ItemID
ORDER BY ID;

Now I am wondering if I can use cross apply to simplify this query. Thanks in advance.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,740 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
95 questions
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 27,016 Reputation points
    2024-01-19T02:48:59.9266667+00:00

    Hi @Y.N

    if I can use cross apply to simplify this query

    Yes, you can use Cross Apply here.

    SELECT *
    FROM #demo t1 CROSS APPLY(SELECT SUM(QTY) AS TotalQTY FROM #demo t2 WHERE t1.ItemId = t2.ItemID GROUP BY ItemId)C
    

    If you want to simplify query, you could also try this:

    SELECT *,SUM(QTY)OVER(PARTITION BY ItemID)AS TotalQTY
    FROM #demo
    

    Best regards, Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Jingyang Li 5,891 Reputation points
    2024-01-19T02:46:15.3033333+00:00
    	  SELECT ID,QTY,ItemID 	  ,SUM(QTY) Over(Partition BY ItemId) AS TotalQTY       FROM #demo 	  ORDER BY ID;
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.