SQL查询只显示一个具有多个记录的字段

时间:2016-06-03 10:10:26

标签: sql sql-server tsql

projName - percentage-
-----------------------
A        - 10        -
A        - 25        -
B        - 20        -
B        - 30        -

结果应为

projName - percentage-
-----------------------
A        - 10        -
         - 25        -
B        - 20        -
         - 30        -

1 个答案:

答案 0 :(得分:1)

使用CASE Con​​dition和Row_number,我们可以实现上述输出

纯粹基于您的样本数据

DECLARE @Table1 TABLE 
    (projName varchar(1), percentage int)
;

INSERT INTO @Table1
    (projName, percentage)
VALUES
    ('A', 10),
    ('A', 25),
    ('B', 20),
    ('B', 30)
;

Select CASE WHEN RN = 1 THEN projName ELSE NULL END projName, percentage from (
select projName, percentage,ROW_NUMBER()OVER(PARTITION BY projName ORDER BY (SELECT NULL))RN from @Table1 )T

在您的查询中,我修改了答案

Select CASE WHEN T.RN = 1 THEN T.projName ELSE NULL END projName, T.percentage FROM  (select 
i.invoice_id,
pr.name as projname ,
ROW_NUMBER()OVER(PARTITION BY projName ORDER BY (SELECT NULL))RN
from annexure a,
project pr,
sow s,
invoice i 
where pr.project_id = s.project_id 
and a.sow_id = s.sow_id 
and i.annexure_id = a.annexure_id 
group by pr.name,i.invoice_date,i.invoice_id )T