Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Adding one row to another but only for one column

Tags:

sql

sql-server

Probably best understood by the picture below.

I have the table on the left but want the table on the right. I want to add together any items that share a reference number without adding up the table number column. My SQL is of the form

SELECT

[Order Reference]
,[Item Price]
,[Table Number]

From Orders

I'm pretty sure I need to SELECT from a second SELECT that sums the items prices but I can't get the exact syntax for summing over the order reference without summing the table numbers also.

Edit :

I think I left out important info for the first answerers. And I clearly messed up the sample data. Many apologies. The table has other columns that I haven't included in my query so when I try a group by I still get multiple rows. I want to isolate the particular column and merge the rows disregarding any column that is different (I don't mind which data of the other columns is chosen)

So for clarity (hopefully) the table also has 20 other columns like discount yes or no which I basically want to ignore but which seem to prevent the rows from merging together from a simple group by clause.

enter image description here

like image 924
tomdemaine Avatar asked Feb 02 '26 00:02

tomdemaine


2 Answers

You need to SUM() up the Items and GROUP your result BY your (desired unique) value(s).

SELECT [Order Reference],
       SUM(PRICE) as 'Items Total',           
       [Table Number] as 'Table Number'
FROM Orders
Group By [Order Reference], [Table Number]

Note:

When working with aggregate functions such as SUM, MAX and others you have to group by every column you want to display in your SELECT.

like image 124
Felix D. Avatar answered Feb 03 '26 17:02

Felix D.


try this query to find your answer

SELECT Order_Reference, SUM(Item_Price) AS 'Total_Item', Table_Number 
FROM Your_Table_Name
GROUP BY Order_Reference,Table_Number 
ORDER BY Order_Reference ASC;
like image 25
Minhaj Patel Avatar answered Feb 03 '26 15:02

Minhaj Patel