Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
hi all,i have two tables. In tbl1 a column "nou" and in tbl2 column "qty" and "p_id".egp_id qty noua001 1 2a001 2 3a001 3 5a001 2 4a002 2 3a002 3 4and i need the following outputp_id qty nou totala001 1 2 30 a001 2 3 30a001 3 5 30a001 2 4 30a002 2 3 18 a002 3 4 18the column total is computed column (1*2+2*3+3*5+2*4) where p_id=a001and (2*3+3*4) where p_id=a002
SwePeso
Patron Saint of Lost Yaks
30421 Posts
Posted - 2009-03-13 : 03:50:37
31, not 30.
DECLARE @Sample TABLE ( p_id VARCHAR(4), qty INT, nou INT )INSERT @SampleSELECT 'a001', 1, 2 UNION ALLSELECT 'a001', 2, 3 UNION ALLSELECT 'a001', 3, 5 UNION ALLSELECT 'a001', 2, 4 UNION ALLSELECT 'a002', 2, 3 UNION ALLSELECT 'a002', 3, 4SELECT s.p_id, s.qty, s.nou, (SELECT SUM(x.qty * x.nou) FROM @Sample AS x WHERE x.p_id = s.p_id)FROM @Sample AS s