question

S9844673241 avatar image
S9844673241 asked

kindly help me to get the following result

Hi, my table data: Date Code open in out close 07/04/2017 1001 1 2 2 1 08/07/2017 1001 1 4 2 3 08/08/2017 1001 3 0 1 2 07/04/2017 1002 1 2 3 0 08/07/2017 1002 0 4 2 2 08/08/2017 1002 2 0 3 -1 i want the result like Code open in out close 1001 1 6 5 2 1002 1 6 8 -1 open=Opening in min date in=sum of in out=sum of out close=closing of max date
sql query
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
ThomasRushton avatar image
ThomasRushton answered
Well, you could try something like this: WITH d AS (SELECT Date, Code, [open], [in], out, [close], --these next two give us the ability to identify particular date rows in a single group by clause ROW_NUMBER() OVER (PARTITION BY [Code] ORDER BY [Date]) AS odt, ROW_NUMBER() OVER (PARTITION BY [Code] ORDER BY [Date] DESC) AS cdt FROM ) SELECT Code, MAX( CASE WHEN odt = 1 THEN d.[open] ELSE NULL END ) AS [open], SUM(d.[in]) AS [in], SUM(d.[out]) AS [out], MAX( CASE WHEN cdt = 1 THEN [close] ELSE NULL END ) AS [close] FROM d GROUP BY d.Code;
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.