SQL에서 여러 날짜와 관련된 다양한 조건을 기반으로 결과를 선택하는 방법은 무엇입니까?

정력

항목 이름, SoldDate (판매 된 경우) 및 DisplayInWebsiteDate (판매되지 않은 경우 해당 항목이 웹 사이트에 표시되어야하는 최신 날짜)가 포함 된 다음과 유사한 항목이있는 테이블이 있습니다.

Id      ItemName      IsSold       SoldDate        DisplayInWebsiteDate
-------------------------------------------------------------------------
1         Shirt         0            NULL              2020-03-28
2         Pant          1          2019-10-20          2020-04-25
3         Jacket        1          2020-01-05          2020-01-20
4         Trouser       0            NULL              2020-01-10

다음 조건에 따라 항목 선택 하고 싶습니다 .

1. If item is not Sold i.e SoldDate is NULL then check if its DisplayInWebsiteDate is 
   greater than current date and that would be valid

2. If item is Sold i.e SoldDate has some date then ignore DisplayInWebsiteDate and check if that item was 
   sold within last 30 days, and display. If it was sold more than 30 days earlier, then don't get that record

오늘 날짜는 2020-01-22이므로 결과는 다음과 같습니다.

1. Shirt is VALID because it is not sold, and DisplayInWebsiteDate is greater than today's date
2. Pant is INVALID because it is sold, so we ignore its DisplayInWebsiteDate. 
   And its sold date has passed more than 30 days form today's date
3. Jacket is VALID because it was sold just 17 days ago i.e it falls within range of 30 days sold date
4. Trouser is INVALID because it is not sold and its DisplayInWebsiteDate has already passed on January 10, 2020

예상 결과:

 Id      ItemName      IsSold       SoldDate        DisplayInWebsiteDate
 -------------------------------------------------------------------------
 1         Shirt         0            NULL              2020-03-28
 3         Jacket        1          2020-01-05          2020-01-20
Tyron78

다음 문을 통해 매우 간단해야합니다.

CREATE TABLE t(
  ID int,
  ItemName nvarchar(100),
  IsSold int,
  SoldDate datetime,
  DisplayInWebsiteDate datetime
)

INSERT INTO t VALUES
(1, 'Shirt', 0, NULL, '2020-03-28')
,(2, 'Pant', 1, '2019-10-20', '2020-04-25')
,(3, 'Jacket', 1, '2020-01-05', '2020-01-20')
,(4, 'Trouser', 0, NULL, '2020-01-10');


SELECT *
  FROM t
  WHERE (SoldDate IS NULL AND DisplayInWebsiteDate > GETDATE())
    OR (SoldDate IS NOT NULL AND DateDiff(d, SoldDate, GETDATE()) <= 30)

그러나 Days 등을 매개 변수화 할 수는 있지만 기본적으로 그게 다라고 생각합니다.

자세한 내용은 SQL Fiddle을 참조하십시오 : http://sqlfiddle.com/#!18/36538/4/1

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관