开发者

How do I get only one row from a list of items in SQL Server?

I've got a non-normalized sales database like this:

Invoice  Item     P开发者_如何学Crice  Total_Sale
-------  ----     -----  ----------
565      Nails    1.25   6.25
565      Hammer   5.00   6.25
566      Paint    7.95   7.95
...

As you can see, the "total_sale" is repeated for each line item in the invoice. Invoice #565 has two items, for a total of $6.25. Invoice #566 only has one item, the total is $7.95. The sum(total_sale) for both invoices should be $14.20.

Q: Is there any easy way to get all the columns* for just one row for each different invoice? Regardless if the invoice has one, two or one hundred line items?


Q: Is there any easy way to get all the columns* for just one row for each different invoice?

WITH T AS
(
SELECT 
      Invoice,
      Item,
      Price,
      Total_Sale,
      ROW_NUMBER() OVER (PARTITION BY Invoice ORDER BY (SELECT 0)) AS RN
FROM YourTable
)
SELECT 
      Invoice,
      Item,
      Price,
      Total_Sale
FROM T 
WHERE RN=1;


A simple query would be:

Select SUM(Price), Invoice, Total_Sale From InvoicesTable
Group By Invoice, Total_Sale
Order By Invoice

The item column cannot be included as the group by would yield multiple rows.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜