I’m trying to join two tables in SQL Server as below: (these are sample tables and the actual one has thousands of records)
Sales table
| ID | SALESID | ITEM | Details… |
| ------------ | ------------ | ------------ | ------------ |
| 1 | S1 | Item1 | |
| 2 | S1 | Item2 | |
| 3 | S1 | Item3 | |
| 4 | S2 | Item 4 | |
| 5 | S3 | Item 5 | |
| 6 | S3 | Item 6 | |Invoice table
| INVSALESID | Invoice amount |
| ------------ | ------------ |
| S1 | A |
| S2 | B |
| S3 | C |
| S4 | D |
| S5 | E |
| S6 | F |
I’m hoping to get the invoice amount added to the first record and rest as 0 to avoid duplication when I am taking the sum for further analysis.
Current result:
Select s.*,Invoice_amount
FROM Sales_table s
join Invoice_table inv on s.salesid=inv.InvSalesId
where s.ID = (
select top 1 s.ID FROM Sales_table s1
WHERE S.SALESID=S1.SALESID
)
ID | SALESID | ITEM | Invoice amount |
---|---|---|---|
1 | S1 | Item1 | A |
2 | S1 | Item2 | A |
3 | S1 | Item3 | A |
4 | S2 | Item 4 | B |
5 | S3 | Item 5 | C |
6 | S3 | Item 6 | C |
Expected result:
| ID | SALESID | ITEM | Invoice amount |
| ------------ | ------------ | ------------ | ------------ |
| 1 | S1 | Item1 | A |
| 2 | S1 | Item2 | 0 |
| 3 | S1 | Item3 | 0 |
| 4 | S2 | Item 4 | B |
| 5 | S3 | Item 5 | C |
| 6 | S3 | Item 6 | 0 |
1条答案
按热度按时间oalqel3c1#
Something like this perhaps:
you partition by salesid and check if it's first row then return amount, otherwise 0