sql server查询显示数据

时间:2015-02-03 07:09:42

标签: sql sql-server-2008

我的数据为:

id empid  amount   billamt
1   101   150.00   150.00
2   102   300.00   700.00 (sum(300+400))
3   102   400.00   700.00 (should be NULL)
--> i want this value to not repeat again,should be NULL
4   104   600.00   600.00 
5   105   200.00   600.00(sum(200+400))
6   105   400.00   600.00(should be NULL)
--> i want this value to not repeat again,should be NULL

由于empid是相同的,所以我想只显示一次总和值。

2 个答案:

答案 0 :(得分:1)

使用Window function计算每amount

的总empid
;WITH cte
     AS (SELECT Row_number()OVER(partition BY empid ORDER BY id)        AS Rn,
                id, empid, amount,
                Sum(amount)OVER(partition BY empid) AS billamt
         FROM   yourtable)
SELECT id, empid, amount,
       CASE
         WHEN rn <> 1 THEN NULL
         ELSE billamt
       END billamt
FROM   cte 

SqlFiddle Demo

答案 1 :(得分:1)

你可以写成:

DECLARE @Emp TABLE (id INT,  empid INT, amount DECIMAL(10,2),billamt DECIMAL(10,2))

INSERT INTO @Emp VALUES      
(1,101,150.00,150.00),(2,102,300.00,700.00 ),(3,102,400.00,700.00 )

;WITH CTE AS
( SELECT id,empid,amount,billamt
         , ROW_NUMBER() OVER( PARTITION BY empid ORDER BY Id ASC) AS Rownum
FROM @Emp) 
UPDATE CTE
SET billamt = NULL 
WHERE Rownum > 1

SELECT * from @Emp