简体   繁体   中英

SQL Aggregate Function Min with Group

I have a table named Prices. Which contain ID, fkProductID (foregnkey of Products Table), PriceDate, Price, fkStore (the supplier ID who gives the prices)

Now I need to find the best price for each product for each month and the SUPPLIER name also. Also some suppliers are giving duplicates prices. For example product id 8 got two times 1200 (ID# 8 and 3). If possible i only need to show the first supplier or a column with count values..


ID  fkProductID PriceDate   Price   fkStore
-----------------------------------------------------
1   8           26-10-2014  1250    13
2   8           10-09-2014  1200    13
3   8           25-10-2014  1200    1
4   8           13-10-2014  1500    1
5   8           03-09-2014  1000    1
6   8           15-09-2014  1300    15
7   8           09-09-2014  950     21
8   8           10-10-2014  1200    23
9   8           09-09-2014  950     27

10  15          10-10-2014  3500    5
11  15          11-10-2014  3400    6
12  15          09-09-2014  3100    6
13  15          10-09-2014  3200    14
14  15          16-09-2014  3100    17
-----------------------------------------------------

my expected result.

-----------------------------------------------------
ID  fkProductID Month       Price   Supplier
-----------------------------------------------------
7   8           September   950     21
2   8           October     1200    1
13  15          September   3100    13
11  15          October     3400    6

=================================================================

SCHEMA

SQL FIDDLE

You can do what you want with the substring_index() / group_concat() trick:

select substring_index(group_concat(idPrices order by Price, idPrices), ',', 1) as id,
       fkProductId, monthname(PriceDate) as mon,
       min(Price) as price,
       substring_index(group_concat(fkStore order by Price, idPrices), ',', 1) as spec_id
from prices p
group by fkProductId, monthname(PriceDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM