使用不同的GROUP by子句在SQL VIEW中添加列?

时间:2016-03-16 15:17:58

标签: sql-server-2008

我有一个看起来像这样的表:

Age|Account_Number
1  |101  
1  |101
1  |102   
2  |102
2  |102
3  |101    
3  |102   
4  |101 
4  |101 
5  |102     
5  |102     
5  |102
5  |101

到目前为止,我创建了一个类似的视图:

Create VIEW view1 as
SELECT age, count(Account_Number) as totalAttempts
GROUP by Age

我的目标是建立一个如下所示的视图表:

Age  | totalAttempts  | 1attempt   | 2attempt | 3attempt | 
1    |3               |1           |2         |0         |
2    |2               |0           |2         |0         |
3    |2               |2           |0         |0         |
4    |2               |0           |2         |0         |
5    |4               |1           |0         |3         |

添加1次尝试+2次尝试+ 3次尝试= totalAttempts。基本上我要添加的这些新列依赖于Account_Number以及它们在表中每行显示的次数。如果Account_number中的值102在表中出现一次但仅在Age 1中出现,那么1attempt = 1.如果Account_number中的值101在表中出现两次但仅在Age 1中出现,那么2attempt = 2.我将如何添加这些列观点?

1 个答案:

答案 0 :(得分:0)

我还包括测试数据创建以便能够测试

IF OBJECT_ID('tempdb..#test') IS NOT NULL 
  DROP TABLE #test

CREATE TABLE #test (Age int, account varchar(5))
INSERT INTO #test VALUES 
(1, '101'),  (1, '101'), (1, '102'), (2, '102'), (2, '102'), 
(3, '101'), (3, '102'), (4, '101'), (4, '101'), 
(5, '102'), (5, '102'), (5, '102'), (5, '101')

;WITH tot AS (
  SELECT Age, account, count(*) cnt
  FROM #test 
  GROUP BY Age, account
)
, at1 AS (
  SELECT * FROM tot
  WHERE cnt = 1
)
, at2 AS (
  SELECT * FROM tot
  WHERE cnt = 2
)
, at3 AS (
  SELECT * FROM tot
  WHERE cnt = 3
)
, final AS (
  SELECT tot.Age, tot.cnt
    , at1.cnt AS attempt_1, at2.cnt AS attempt_2, at3.cnt AS attempt_3
  FROM tot 
    Full JOIN at1 ON at1.Age = tot.Age AND at1.account = tot.account
    Full JOIN at2 ON at2.Age = tot.Age AND at2.account = tot.account
    Full JOIN at3 ON at3.Age = tot.Age AND at3.account = tot.account
)
SELECT Age, sum(cnt) TotalAttempts
 , sum(isnull(attempt_1, 0)) Attempt_1, sum(isnull(attempt_2, 0)) Attempt_2
, sum(isnull(attempt_3, 0)) Attempt_3
FROM final 
GROUP BY Age
ORDER BY Age

这将是结果

Age TotalAttempts   Attempt_1   Attempt_2   Attempt_3
1       3               1           2           0
2       2               0           2           0
3       2               2           0           0
4       2               0           2           0
5       4               1           0           3