我有一个名为License的表,其列为:
pk_license
fk_customer
option_1
和值:
4297 1 0
30640 1 1
29990 87 0
29373 134 0
2720 144 1
30579 144 0
24799 172 0
30035 183 1
27855 197 0
30337 197 1
30596 198 1
28083 216 0
我需要获取option_1的值,以获得每个不同fk_customer的最高pk_license。我试过了:
SELECT *
FROM License li
INNER JOIN
(SELECT opt_2, fk_station, MAX(pk_license) AS MaxLicense
FROM License
GROUP BY opt_2, fk_station) groupedli
ON li.opt_2 = groupedli.opt_2
AND li.pk_license = groupedli.MaxLicense
ORDER BY li.fk_station
...但我为option_1的每个值获得了两行。我想要做的是确定每个客户的最新option_1值。
答案 0 :(得分:1)
试试这个:
SELECT li.*
FROM License li
INNER JOIN
(SELECT fk_customer,
max(pk_license) as maxLicense
FROM License
GROUP BY fk_customer) lm
ON li.fk_customer = lm.fk_customer
AND li.pk_license = lm.MaxLicense
ORDER BY li.fk_customer, li.pk_license
答案 1 :(得分:1)
你可以试试这个:
SELECT DISTINCT(`fk_customer`),`pk_license`,`option_1` FROM `License` order by `pk_license` DESC
查询结果:
1 | 30640 | 1 198 | 30596 | 1 144 | 30579 | 0 197 | 30337 | 1 183 | 30035 | 1 87 | 29990 | 0 134 | 29373 | 0 216 | 28083 | 0 197 | 27855 | 0 172 | 24799 | 0 1 | 4297 | 0 144 | 2720 | 1
答案 2 :(得分:0)
这是我的解决方案:
Create table tblLicense
(
pk_license int,
fk_customer int,
option_1 int
)
Go
Insert into tblLicense values (4297, 1, 0)
Insert into tblLicense values (30640, 1 ,1)
Insert into tblLicense values (29990, 87 ,0)
Insert into tblLicense values (29373, 134,0)
Insert into tblLicense values (2720 , 144,1)
Insert into tblLicense values (30579, 144,0)
Insert into tblLicense values (24799, 172,0)
Insert into tblLicense values (30035, 183,1)
Insert into tblLicense values (27855, 197,0)
Insert into tblLicense values (30337, 197,1)
Insert into tblLicense values (30596, 198,1)
Insert into tblLicense values (28083, 216,0)
Go
SELECT tblLicense.pk_license,tblLicense.fk_customer,option_1 FROM tblLicense
INNER JOIN
(
SELECT fk_customer,MAX(pk_license) as pk_license from tblLicense
GROUP BY fk_customer
) groupedTbl
on tblLicense.fk_customer = groupedTbl.fk_customer
AND tblLicense.pk_license = groupedTbl.pk_license
ORDER BY tblLicense.fk_customer
答案 3 :(得分:0)
无需执行joins
您可以使用相关subquery
select * from table t
where pk_license =
(select max(pk_license) from table where fk_customer = t.fk_customer)
order by fk_customer
对于您当前的尝试,您根据可能影响所需结果的两列(group by
,opt_2
)执行fk_station
。