我有一张桌子,上面有这样的内容;
id customer is_default
1606384 5828 1
1573786 5828 0
1575316 5828 0
1817769 5828 0
对于该客户,有一个 is_default = 1 地址,而其他一些则没有。例如;
id customer is_default
1806384 5829 0
1873786 5829 0
1875316 5829 0
1917769 5829 0
我想获取 MAX(id),但查询应优先使用 is_default = 1
例如,在第一个表中查询必须返回 MAX(id)= 1606384 ,而在第二个表中查询应返回 MAX(id)= 1917769
>我无法解决这个问题。
你们能帮我吗?
回复@Strawberry的评论
我已经尝试过这种方法;
首先,我已将 is_default 与 id 相乘,并对其进行排序,以便从查询中获取最大ID。但这一切都是错误的,据我了解
SELECT MAX(id) as mid,MAX(is_default)
FROM (
(SELECT rel.maxid as id,customer,is_default FROM (
select (id+(is_default*10000000)) as maxid,customer,is_default FROM customer_address ORDER BY is_default DESC) rel ORDER BY maxid)
) rel
GROUP BY customer
答案 0 :(得分:2)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,customer INT NOT NULL
,is_default TINYINT NOT NULL
);
INSERT INTO my_table VALUES
(1606384,5828,1),
(1573786,5828,0),
(1575316,5828,0),
(1817769,5828,0),
(1806384,5829,0),
(1873786,5829,0),
(1875316,5829,0),
(1917769,5829,0);
SELECT x.customer
, COALESCE(MAX(y.id),MAX(x.id)) id
FROM my_table x
LEFT
JOIN my_table y
ON y.customer = x.customer
AND y.is_default = 1
GROUP
BY x.customer;
+----------+---------+
| customer | id |
+----------+---------+
| 5828 | 1606384 |
| 5829 | 1917769 |
+----------+---------+
答案 1 :(得分:1)
您可以执行以下操作,但@Strawberry答案似乎更好:
SELECT
customer,
(CASE WHEN is_default IS NOT NULL THEN is_default ELSE nis_default END) AS max
FROM (
SELECT
customer,
MAX(CASE WHEN is_default = 1 THEN id END) AS is_default,
MAX(CASE WHEN is_default = 0 THEN id END) AS nis_default
FROM t
GROUP BY customer) T
编辑:我的查询可以像这样用COALESCE简化:
SELECT
customer,
COALESCE(
MAX(CASE WHEN is_default = 1 THEN id END),
MAX(CASE WHEN is_default = 0 THEN id END)) AS max
FROM t
GROUP BY customer
答案 2 :(得分:0)
如果只需要单个max(id)值,最好使用is_default = 1,则使用:
select max_id
from (
select is_default, max(id) as max_id
from customer_address
group by is_default
order by is_default desc
limit 1
) as q;
答案 3 :(得分:0)
您需要一个CASE表达式:
select
customer,
case max(is_default)
when 1 then max(is_default * id)
else max(id)
end maxid
from tablename
group by customer
请参见demo。
结果:
| customer | maxid |
| -------- | ------- |
| 5828 | 1606384 |
| 5829 | 1917769 |