Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

SQL Server: filter out results based on different data in same column

I ran into a issue with a query I'm creating.

The table looks like this:

LineId|Product|orderedQty|PickedQty|Operator|TimeFinised
------+-------+----------+---------+--------+-----------
     1|   1234|        60|       40|    Joe |     125546      
     2|   1234|        60|       18|  Benny |     120025

I would like to create a query that turns this into one result where the PickedQty are summed up. I would also like to only show the last operator that picked the items based on the column Timefinished.

The result should look like this:

Product|orderedQty|PickedQty|Operator
   1234|        60|       58|     Joe

Query so far:

 select
     product,
     orderedQty,
     cast(sum(m.PickedQty) as decimal(18,1)) as PickedQty,
 from 
     Lines
 group by 
     product, orderedQty

It's easy enough to summarize the PickedQty, but I have no idea how I can filter out the first operator.

Do anyone know how I can achieve this?

question from:https://stackoverflow.com/questions/65847848/sql-server-filter-out-results-based-on-different-data-in-same-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Conditional aggregation may help:

select
   product,
   orderedQty,
   cast(sum(m.PickedQty) as decimal(18,1)) as PickedQty,
   MAX (CASE WHEN Rn = 1 THEN Operator END) AS Operator
from (
   SELECT 
      *,
      ROW_NUMBER() OVER (PARTITION BY product, orderedQty ORDER BY TimeFinised DESC) AS Rn
   FROM (VALUES
       (1, 1234, 60, 40, 'Joe',   125546),      
       (2, 1234, 60, 18, 'Benny', 120025)
   ) v (LineId, Product, orderedQty, PickedQty, Operator, TimeFinised)   
) m
group by 
   product, orderedQty

Result:

product orderedQty  PickedQty   Operator
1234    60          58.0        Joe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...