开发者

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

开发者 https://www.devze.com 2023-04-08 14:21 出处:网络
I\'ve got a non-normalized sales database like this: InvoiceItemP开发者_如何学CriceTotal_Sale --------------------------

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

精彩评论

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