根据重复记录增加列值

时间:2019-10-27 22:09:03

标签: sql sql-server

我是否可以避免使用光标有疑问。

我有一个包含成千上万条记录的表,如下所示:

   Date    | Name  | StateData | 
-----------+-------+-----------+  
22-10-2019 | Tom   | OPENED    |   
22-10-2019 | David | NULL      |
22-10-2019 | Tom   | NULL      |
22-10-2019 | Brand | CLOSED    |
22-10-2019 | Tom   | NULL      |
23-10-2019 | Brand | NULL      |
22-10-2019 | Brand | OPENED    |
22-10-2019 | Tom   | OPENED    |
22-10-2019 | Brand | OPENED    |
22-10-2019 | Tom   | CLOSED    |
22-10-2019 | Brand | CLOSED    |

我想要实现的是一个结果,在这里我可以看到每个名称仅显示在一行上,并且可以计算出它们拥有“ StateData”状态的次数。

      Date | Name | OPENED | CLOSED | UNUSED |
-----------+------+--------+--------+--------+
22-10-2019 | Tom  |   2    |    1   |    2   |
22-10-2019 | David|   0    |    0   |    1   |
22-10-2019 | Brand|   2    |    2   |    1   |

我尝试过这样的选择

SELECT DISTINCT d.Name, d.[opened], d.[closed], d.[unused], StateData
FROM [dbo].[StateData] d

INNER JOIN (
        SELECT  DISTINCT Name, [opened], [closed], [unused]

        FROM [dbo].[StateData]
        GROUP BY  Name, [opened], [closed], [unused]

        ) dp
            ON dp.Name = d.Name 
;

我知道可以通过使用CURSOR创建存储过程来做到这一点,但是我对游标的经验并不了解。

3 个答案:

答案 0 :(得分:4)

使用条件聚合:

select 
    Date,
    Name,
    SUM(CASE WHEN StateDAte = 'Opened' THEN 1 ELSE 0 END) Opened,
    SUM(CASE WHEN StateDAte = 'Closed' THEN 1 ELSE 0 END) Closed,
    SUM(CASE WHEN StateDAte IS NULL THEN 1 ELSE 0 END) Unused
from mytable
group by Date, Name 

答案 1 :(得分:1)

您可以按以下方式使用sql pivot

;with cte as (select date,name,isnull(statedate,'unused') statedate from mytable)


select p.*  from cte 
pivot
(count(statedate) for statedate in ([Opened],[Closed], [unused]  )) as p

enter image description here

答案 2 :(得分:0)

GMB和Kemal,

谢谢

我已经尝试过了

SELECT [Date],
       [Name],
       COUNT(CASE StateData WHEN 'OPENED' THEN 1 END) AS OPENED,
       COUNT(CASE StateData WHEN 'CLOSED' THEN 1 END) AS CLOSED,
       COUNT(CASE WHEN StateData IS NULL THEN 1 END) AS UNUSED
FROM YourTable
GROUP BY [Date],
         [Name];

但结果不正确

Name  |  OPENED  |  CLOSED | UNUSED |
Tom   |  2       |   0     |  57412 |
Brad  |  2       |   0     |  57412 |
David |  2       |   0     |  57412 |

正确的结果应该是

      Date | Name | OPENED | CLOSED | UNUSED |
-----------+------+--------+--------+--------+
22-10-2019 | Tom  |   2    |    1   |    2   |
22-10-2019 | David|   0    |    0   |    1   |
22-10-2019 | Brand|   2    |    2   |    1   |

但是看起来它只是粘贴结果而已。