I know you cant Group By one column in a table (Although I wish it was that easy) but can I at last grab the fields of the row selected by the min?
prd_id prd_description Stock Todays Order Tomorrows Order Next Batch prd_status Prd_line prd_estimate_time left_to_produce
7 Product A 14 14 234 16249 New 2 17May16 17:54:02 16249
9 Product B 754 0 0 2128 New 5 17May16 18:11:28 2128
11 Product C 0 157 5106 6850 New 2 17May16 18:40:04 6850
17 Product D 1248 4296 9120 4728 New 8 18May16 04:50:09 9456
17 Product D 1248 4296 9120 4728 New 10 18May16 16:55:09 9456
Now for Product D all is the same except its produced on two lines and different times of the day.
I want one product per line with the lowest Estimated time displayed and the line its produced on
such as
prd_id prd_description Stock Todays Order Tomorrows Order Next Batch prd_status Prd_line prd_estimate_time left_to_produce
7 Product A 14 14 234 16249 New 2 17May16 17:54:02 16249
9 Product B 754 0 0 2128 New 5 17May16 18:11:28 2128
11 Product C 0 157 5106 6850 New 2 17May16 18:40:04 6850
17 Product D 1248 4296 9120 4728 New 8 18May16 04:50:09 9456
答案 0 :(得分:2)
假设sql-server(> = 2005)为rdbms,您可以使用排名函数ROW_NUMBER
:
WITH CTE AS
(
SELECT t.*, RN = ROW_NUMBER() OVER (PARTITION BY prd_id -- add more columns if you want to group by multiple columns
ORDER BY prd_estimate_time ASC)
FROM dbo.TableName
)
SELECT prd_id, prd_description, Stock, [Todays Order], [Tomorrows Order], [Next Batch], prd_status, Prd_line, prd_estimate_time, left_to_produce
FROM CTE
WHERE RN = 1