我有一个表格,其数据类似于:
stat_id account_id discount date_from date_to type
1 1 50 2017-10-01 2017-10-31 1
2 2 40 2017-10-01 2017-10-31 1
3 1 0 2017-01-01 2017-11-30 2
我想获得所有不同的account_id
s,在给定的时间段内date_from <= '2017-10-01' and date_to >= '2017-10-31'
),每个type
type
account_id discount type
1 0 2
2 40 1
都是1或2
type = 1
我尝试了各种查询,但我无法实现这一目标。我得到的是type = 2
的一行和account_id = 1
的{{1}}的一行
account_id discount type
1 50 1
1 0 2
2 40 1
我可以在我的应用程序中过滤它们,但对于纯粹的个人娱乐,我想在一个查询中进行。任何帮助表示赞赏:)
答案 0 :(得分:0)
试试这个 -
SELECT account_id, discount, type
FROM YOUR_TABLE
WHERE (account_id, type) IN (SELECT account_id, MAX(type)
FROM YOUR_TABLE
GROUP BY account_id)
AND date_from <= '2017-10-01'
AND date_to >= '2017-10-31'