2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【SalesForce, Apex】SOQLでn日前のレコードを取得したい時にLAST_N_DAYS:nを使ったけど思い通りにはならなかった

Last updated at Posted at 2021-03-09

n日前を起点にそれ以前のデータを取得するという条件を作りたい

SELECT Id From Account WHERE CreatedDate <= n日前

LAST_N_DAYS:nが使えるかな?

こんな条件になるのですが、 n日前 をSOQLの日付リテラルが使ってできないかなーと思いながら見ていて
LAST_N_DAYS:n がそれっぽくできるかなと思ったんですけど、

数値 n が指定されている場合、本日から、その n 日前までが指定されます。
これには、過去の日だけではなく、本日も含まれます。たとえば、LAST_N_DAYS:1 には、昨日と本日が含まれます。

https://developer.salesforce.com/docs/atlas.ja-jp.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_dateformats.htm
思い通りにいかなかった。

過去の日だけではなく、本日も含まれます

こう書いてある通り、その期間を含んで条件を作るんですよね。つまり、

CreatedDate <= IN (2/12, 2/13, 2/14, 2/15) 

こんな書き方はないけど、↑みたいなイメージになる。

要するに、

CreatedDate <= 2/15

と変わらない。

LAST_N_DAYS:nを活かして期待するレコードを取得するとしたら?

SELECT Id
From Account
WHERE CreatedDate <= last_n_days:3
  AND CreatedDate != last_n_days:3

こんな感じになるんですけど、分かりづらいですね。

結果

Apex側で三日前の値を作り、クエリ文にbindして作る感じにするというところに落ち着きました。

Date threeDaysAgo = Date.today() - 3;
Datetime dateTimeOfThreeDaysAgo = Datetime.newInstance(threeDaysAgo, Time.newInstance(0, 0, 0, 0));
String query = 'SELECT Id FROM Account WHERE CreatedDate = :dateTimeOfThreeDaysAgo';

いい方法あったら教えてください。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?