需要创建一个新列,从另一列中提取数据,使用变量作为日期范围,并根据输出返回一个值

时间:2018-01-02 21:07:59

标签: sql sql-server sql-server-2008

我需要创建一个新列,该列的数据基于来自同一数据库中标记为(Sys_Created)的另一列的日期或日期范围。它需要在标记为“Cust_Status

的新列中返回”New“或”Existing“的值

如果我们在过去6个月内收到订单或付款,我也想退还此值。这将重新建立这个“现有”客户作为“新”客户。

- 这是我目前的代码:此查询的目的是报告2017年作为客户或潜在客户创建的所有客户的销售情况。这将很快扩展到所有日期范围,但为了速度,我刚做了1年。

`declare @startdate datetime = '1/1/2017'
declare @enddate datetime = '12/20/2017'

SELECT C.cmp_name, 
       C.debcode,
       C.statecode as State,
       c.cmp_fcity as City,
       c.ClassificationId,
       c.SalesPersonNumber as SalesPerson,
       Max(C.type_since)AS TypeSince, 
       Max(C.syscreated)AS SysCreated, 
       Max(C.cmp_status)AS CmpStatus, 
       SUM(( 1 - L.discount_pct / 100 ) * L.qty_ordered * L.unit_price * 
L.uom_ratio *  
(  CASE WHEN L.ord_type = 'C' THEN -1  ELSE 1      END )) as TotDollars


FROM  cicmpy AS C 
       LEFT JOIN oehdrhst_sql AS H 
              ON C.debcode = h.cus_no 
       LEFT JOIN oelinhst_sql AS L 
              ON H.ord_no = L.ord_no 
                 AND H.ord_type = L.ord_type 

WHERE  C.cmp_type = 'C' 
       AND L.sls_amt > '0.00'  
       AND C.type_since >= @startdate 
       AND C.type_since <= @enddate 
GROUP  BY C.cmp_name, 
          C.debcode,C.statecode,c.cmp_fcity,c.ClassificationId, 
c.SalesPersonNumber`

1 个答案:

答案 0 :(得分:0)

--Add column to existing table
alter customers
add cust_ctatus int

-- set status "1" if any payments in last 6 mo
-- I assume you have a column with last payment date. You can use data from other table instead.
update customers
set cust_ctatus = 1
where month(getdate)-month(payment_date)<7

注意:您的描述不够。因此,上述和平只是为了给出方向,而不是最终答案。当给出更好的描述时,我可能会修改我的答案。