我的表格包含以下列:product_id
,customer_id
,start_date
,end_date
,product
,product_use
。我的目标是找到客户在每个月初和每个月末使用的产品?有任何想法如何在SQL中执行此操作?感谢。
product_id cust_id START_DT END_DT
8398D 8678 12/18/2013 3/10/2014
270B9 8678 2/14/2014 3/16/2014
C0867 8678 3/25/2014 4/1/2014
2F9D2 8678 4/3/2014 5/7/2014
9AE65 8678 4/25/2014 5/6/2014
预期结果
Month product_begining_of_month product_end_of_month
December 8398D 8398D
January 8398D 8398D
February 8398D 8398D and 270B9
March 8398D and 270B9 C0867
April 2F9D2 2F9D2 AND 9AE65
答案 0 :(得分:0)
您可以选择ID,第一个和最后一个日期作为结果集;然后使用外表查询这些结果,使用日期和customerid的内部表结果选择productId ..
SELECT CustID, (SELECT product_id FROM CustomerTable CTBL2 WHERE
(CustID=INNTBL.CustID and (TranscationDate=INNTBL.LastmostDate)) AS
LastmostProduct, (SELECT product_id FROM CustomerTable CTBL3 WHERE
(CustID=INNTBL.CustID_ and (TranscationDate=INNTBL.FirstDate)) AS FirstProduct
FROM
(Select CustId, Max(TranscationDate) AS LastmostDate,
Min(TranscationDate) as FirstDate FROM CustomerTable as CTBL
Group by CustId) AS INNTBL