我正在加入2个表并显示InvNumber,InvAmount和JobNumber的数据。我只需要在第一行显示InvNumber和InvAmount。发票有多个应显示的作业编号。
HEre是DDL
DECLARE @Date datetime;
SET @Date = GETDATE();
DECLARE @TEST_DATA TABLE
(
DT_ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED
,InvNumber VARCHAR(10) NOT NULL
,InvAmount VARCHAR(10) NOT NULL
,JobNumber VARCHAR(10) NOT NULL
);
INSERT INTO @TEST_DATA (InvNumber, InvAmount,JobNumber)
VALUES
('70001', '12056','J65448')
,('70001', '12056','J12566')
,('70001', '12056','J35222')
,('70001', '12056','J45222')
,('70001', '12056','456855')
,('70001', '12056','J55254')
;
SELECT
J.DT_ID
,InvNumber
,InvAmount
,JobNumber
FROM @TEST_DATA AS J
答案 0 :(得分:6)
您可以使用ROW_NUMBER和CASE表达式执行类似的操作。
SELECT DT_ID,
CASE WHEN RN = 1 THEN InvNumber
ELSE ''
END InvNumber,
CASE WHEN RN = 1 THEN InvAmount
ELSE ''
END InvAmount,
JobNumber
FROM (SELECT DT_ID,
InvNumber,
InvAmount,
JobNumber,
ROW_NUMBER() OVER (PARTITION BY InvNumber,InvAmount ORDER BY DT_ID) RN
FROM @TEST_DATA
) j
答案 1 :(得分:1)
使用SQL你无法轻易做到这一点。
您可以在select语句中使用GROUP BY子句来按发票对JobNumbers进行分组。
答案 2 :(得分:1)
我几乎符合JamieD77的回答。但我不确定这个解决方案是否会显示所有InvNumbers和所有InvAmounts(如果有的话)。所以,这就是我的建议:
select td.DT_ID,
case when td.DT_ID = j.DT_ID then td.InvNumber
else ''
end as InvNumber,
case when td.DT_ID = j.DT_ID then td.InvAmount
else ''
end as InvAmount,
td.JobNumber
from @TEST_DATA as td
left join (
select InvNumber,
InvAmount,
min(DT_ID) as DT_ID
from @TEST_DATA
group by InvNumber,
InvAmount
) j