SQL Server使用分组依据计算列

时间:2018-07-26 03:03:29

标签: sql-server group-by ssms calculated-columns

我正在尝试使用来自单独表的3列创建计算列,该表由SSMS中的外键分组。我有一个名为OrderLines的链接表,该表链接了Orders和Products表。 OrderLines表包含RowID(PK),ItemPrice,Quantity和OrderID(FK)。 Orders表包含OrderID的主键,并且是我要向其添加SubTotal列的表。所以我需要的公式是((ItemPricexQuantity)按OrderID分组),但我找不到解决方法。

OrderLines Table

OrdersTable

我已经弄清楚了如何使用查询将其作为列来获取,并且可以使用视图来创建它,但是想知道是否可以将其作为计算列添加到Orders表中。

查询将创建我需要的列:

Select orderid, SUM(itemprice*Quantity)
from orderitems
group by orderID

感谢您的宝贵时间, 斯蒂芬

2 个答案:

答案 0 :(得分:0)

之前的讨论:How do I Specify Computed Columns in a Table which are based on another Column in SQL Server?

create table orderitems 
(
orderId int,
itemid int,
productId int,
itemprice decimal(18,2),
quantity int
)
GO
create table orders
(
orderId int,
shipAmount decimal(18,2),
TaxAmount decimal(18,2)
)
GO
insert into orderitems (orderId,itemid,productId,itemprice,quantity) values
(1,1,2,1199,1),
(2,2,8,489.99,1),
(3,3,1,2517,1),
(3,4,9,415,1),
(4,5,2,1199,1),
(5,6,10,299,1),
(6,7,10,299,1)
GO
insert into orders (orderId,shipAmount,TaxAmount) values
(1,5,58.71),
(2,5,58.72),
(3,10,58.73),
(4,10,58.74),
(5,5,58.75),
(6,5,58.76);
GO
select * from orders
GO
orderId | shipAmount | TaxAmount
------: | :--------- | :--------
      1 | 5.00       | 58.71    
      2 | 5.00       | 58.72    
      3 | 10.00      | 58.73    
      4 | 10.00      | 58.74    
      5 | 5.00       | 58.75    
      6 | 5.00       | 58.76    
create function udfMyTable (@orderID  as int)
returns decimal(18, 2)
as
begin
  declare @res as decimal(19, 2);

  Select
    @res = SUM(itemprice*Quantity)
  from orderitems
  where
    orderID = @orderID    

return @res;
end
GO
alter table orderitems add SubTotal as dbo.udfMyTable(orderID)
GO
alter table orders add SubTotal as dbo.udfMyTable(orderID)
GO
Select * from orderitems
GO
orderId | itemid | productId | itemprice | quantity | SubTotal
------: | -----: | --------: | :-------- | -------: | :-------
      1 |      1 |         2 | 1199.00   |        1 | 1199.00 
      2 |      2 |         8 | 489.99    |        1 | 489.99  
      3 |      3 |         1 | 2517.00   |        1 | 2932.00 
      3 |      4 |         9 | 415.00    |        1 | 2932.00 
      4 |      5 |         2 | 1199.00   |        1 | 1199.00 
      5 |      6 |        10 | 299.00    |        1 | 299.00  
      6 |      7 |        10 | 299.00    |        1 | 299.00  
select * from orders
GO
orderId | shipAmount | TaxAmount | SubTotal
------: | :--------- | :-------- | :-------
      1 | 5.00       | 58.71     | 1199.00 
      2 | 5.00       | 58.72     | 489.99  
      3 | 10.00      | 58.73     | 2932.00 
      4 | 10.00      | 58.74     | 1199.00 
      5 | 5.00       | 58.75     | 299.00  
      6 | 5.00       | 58.76     | 299.00  

db <>提琴here

答案 1 :(得分:0)

我想你需要下面的东西

select  O.orderID ,sum(itemprice*Quantity)Orders O inner join OrderLines ol 
on O.OrderID=ol.OrderId
group by  O.OrderID