SQL Server:对表中的数据进行分类

时间:2015-12-11 06:24:37

标签: sql sql-server

我正在尝试在SQL Server 2012中将表与自身进行比较。该表包含客户端名称,客户端编号和会计年度等其他列。表中有2015财年和2016财年的数据,客户可以重复多次。

我正在尝试向表中添加一个列,该列将规定每行中的客户端是否为" New" (存在于2016财年,但不存在于2015财年),"现有" (存在于FY16和FY15),或者#34; Lost" (存在于FY15,但未存在于FY16)。

我尝试将表格加入到自身并使用案例陈述但没有运气。

2 个答案:

答案 0 :(得分:0)

您可以使用LEFT JOIN

来完成
SELECT c1.Name, c1.Number, c1.FiscalYear,   
       CASE 
          WHEN c1.FiscalYear = 2015 AND c2.FiscalYear = 2016 THEN 'Existing'
          WHEN c1.FiscalYear = 2015 AND c2.FiscalYear IS NULL THEN 'Lost'
          WHEN c1.FiscalYear = 2016 AND c2.FiscalYear = 2015 THEN 'Existing'
          WHEN c1.FiscalYear = 2016 AND c2.FiscalYear IS NULL THEN 'New'
       END AS category   
FROM clients AS c1
LEFT JOIN clients AS c2 
   ON c1.Name = c2.Name AND 
      ((c1.FiscalYear = 2015 AND c2.FiscalYear = 2016) OR
      (c1.FiscalYear = 2016 AND c2.FiscalYear = 2015))

Demo here

如果您只想获取每个客户名称的类别,那么您可以使用GROUP BY

SELECT Name,
       CASE 
          WHEN COUNT(DISTINCT FiscalYear) = 2 THEN 'Existing'
          WHEN SUM(FiscalYear = 2015) > 0 AND SUM(FiscalYear = 2016) = 0 THEN 'Lost'
          WHEN SUM(FiscalYear = 2016) > 0 AND SUM(FiscalYear = 2015) = 0 THEN 'New'
       END AS category   
FROM clients
WHERE FiscalYear IN (2015, 2016)
GROUP BY Name

Demo here

您还可以使用上述查询来执行UPDATE

UPDATE clients
INNER JOIN (
  SELECT Name,
         CASE 
            WHEN COUNT(DISTINCT FiscalYear) = 2 THEN 'Existing'
            WHEN SUM(FiscalYear = 2015) > 0 AND SUM(FiscalYear = 2016) = 0 THEN 'Lost'
            WHEN SUM(FiscalYear = 2016) > 0 AND SUM(FiscalYear = 2015) = 0 THEN 'New'
         END AS category   
  FROM clients
  WHERE FiscalYear IN (2015, 2016)
  GROUP BY Name 
) AS t ON clients.name = t.name
SET clients.category = t.category

Demo here

答案 1 :(得分:0)

版本更新:

update customer 
set status = case when 
   (select count(*) from customer C2 where C2. ClientName = customer.ClientName and C2.Year in (2015,2016) ) = 2 then 'Existing' 
   when  
      (select count(*) from customer C2 where C2.clientName = customer.ClientName and C2.Year = 2015  ) = 1 then  'Lost'
   when 
     (select count(*) from customer C2 where C2.clientName = customer.ClientName and C2.Year in (2016) ) = 1 then  'New'
     end;

此处SQL Fiddle中的示例