2017-04-25 56 views
1

我創建SQL表的數據透視表的有三個字段如何使用SQL Server

NAME  TYPE    Amount 
    RAJ  401K %   500 
    Kumar ROTH    600 
    RAJ  401K %   500 
    Kumar ROTH    700 
    Karthi 401K %   1500 
    RAj  Roth    800 
    Tony  DPD    8 

上面的表格我有三個列字段名稱,最後輸入金額。我嘗試轉換這個表像分開的列類型。在我的桌子Raj很多時間來到桌子裏,所以我想總結Raj所有的價值,這些價值與401K桌子一起最終顯示出它的單一價值。它增加了401k的價值。羅斯價值這樣分開

Name   401k% Roth  Amount 
Raj   1000  800  1800 
Kumar   0  1300  1300 
Karthi  1500  0  1500. 
Nimi   0  0   0  -- this is should Remove only value come with only 401k% and Roth . other value should be delete .  

我想要這樣。我試圖達到這個使用樞軸talbe我越來越空值

select [Name],[401k%] ,[Roth%] 
from DeductionHistory 
PIVOT 
(SUM(Amount) FOR DeductionName IN([401k%],[Roth%]) 
) 
AS Pivottable 

請任何人幫助我。如何獲得價值篩選

回答

2
CREATE TABLE #TABLE111 
    ([NAME] VARCHAR(6), [TYPE] VARCHAR(6), [AMOUNT] INT) 

INSERT INTO #TABLE111 
    ([NAME], [TYPE], [AMOUNT]) 
VALUES 
    ('RAJ', '401K %', 500), 
    ('KUMAR', 'ROTH', 600), 
    ('RAJ', '401K %', 500), 
    ('KUMAR', 'ROTH', 700), 
    ('KARTHI', '401K %', 1500), 
    ('RAJ', 'ROTH', 800) 

SELECT NAME ,ISNULL([401K %],0) [401K %] ,ISNULL([ROTH],0) [ROTH] ,ISNULL([401K %],0)+ISNULL([ROTH],0) 'TOTAL' 
FROM 
(
    SELECT * 
    FROM #TABLE111 
) SRC 
PIVOT 
(
    SUM([AMOUNT]) 
    FOR [TYPE] IN ([401K %], [ROTH]) 
) PIV 
ORDER BY NAME DESC 

輸出

NAME 401K % ROTH TOTAL 
RAJ 1000  800  1800 
Kumar 0  1300  1300 
Karthi 1500 0  1500 
+0

謝謝Chankya.u Helpmed今天lot.one更多的問題怎麼刪除,如果假設401K和羅斯都是0。如何刪除零值時,兩列來零 – sripriya

0
--I have included DPD the query 
DECLARE @DeductionHistory TABLE (NAME VARCHAR(20), [TYPE] VARCHAR(20),Amount MONEY) 
INSERT INTO @DeductionHistory VALUES 
    ('RAJ','401K%',500), 
    ('Kumar','ROTH',600), 
    ('RAJ','401K%',500), 
    ('Kumar','ROTH',700), 
    ('Karthi','401K%',1500), 
    ('RAj','ROTH',800), 
    ('Tony' ,'DPD', 8) 


/*****Use a VTE or temp table*****/ 


;WITH DeductionHistory 
AS(
SELECT * FROM @DeductionHistory 
PIVOT 
(
SUM(Amount) FOR [TYPE] IN ([401K%],[ROTH],[DPD]) 
) PV1 
) 
SELECT 
[NAME] 
,ISNULL([401K%],0) AS [401K%] 
,ISNULL([ROTH],0) AS [ROTH] 
,ISNULL([DPD],0) AS [DPD] 
,ISNULL([401K%],0)+ISNULL([ROTH],0)+ISNULL([DPD],0) AS Amount 
FROM DeductionHistory 

輸出

NAME 401K%  ROTH DPD Amount 
    Karthi 1500.00 0.00  0.00 1500.00 
    Kumar 0.00  1300.00 0.00 1300.00 
    RAJ  1000.00 800.00 0.00 1800.00 
    Tony 0.00  0.00  8.00 8.00 
+0

我想刪除誰有零401k%和羅斯。這張表從Excel工作表導入,我想選擇誰有價值401k%和羅斯我想要的其他值刪除 – sripriya

+0

如果你想刪除任何東西排除他們在哪裏從句,例如 – JonWay

+0

如果你想刪除任何東西排除他們在where子句例如WHER [401K%] <> 0 – JonWay