嗨,我有一张“发票”表
customer_number | Invoice_Number | Name | Address | Total_Amount
选择我正在使group by
为客户编号
并合计发票的Total_amount。
我仍然想在输出中显示他的名字和地址。
转储发票编号。
但是我的住址和客户名称都是我的更改,我想根据特定客户的最后发票编号创建最新的address
和name
列。
我该怎么做? 我是usind ms sql
答案 0 :(得分:1)
类似这样的东西:
SELECT customer_number
,Name
,Address
,Total_Amount
FROM
(
SELECT customer_number
,Name
,Address
,SUM(Total_Amount) OVER (PARTITION BY customer_number) AS Total_Amount
,DENSE_RANK() OVER (PARTITION BY customer_number ORDER BY Invoice_Number DESC) AS row_id
FROM [my_table]
) DS
WHERE row_id = 1;
使用OVER
子句,我们可以计算每一行的总和。就像分组一样,但是group by
却使用PARTITION BY
,每组一行,而是返回所有行。
同时,我们使用排名功能按invoce_number desc
从最新到第一的顺序排列每个客户的行。
最后,我们只需要获取所需的行即可。
答案 1 :(得分:0)
有许多方法可以根据您的SQL Server版本进行此操作。 以下方法适用于任何版本,但如果您有数百万行,则可能会很慢。 如果您使用的是较早版本,则还有更多不错的方法。
select customer_number, TotamAmount = sum(Total_Amount)
, Name = (select top 1 Name from myTable where customer_number = t1.customer_number order by Invoice_Number desc)
, Address = (select top 1 Address from myTable where customer_number = t1.customer_number order by Invoice_Number desc)
from myTable t1
group by customer_number
答案 2 :(得分:0)
您可以尝试查询
SELECT customer_number,
sumamount,
[name],
[address]
FROM (SELECT customer_number,
Sum (total_amount)
OVER (
partition BY customer_number ) sumAmount,
[name],
[address],
Row_number()
OVER(
partition BY customer_number
ORDER BY [primarykey] ) AS [CustomerInvoiceId]
FROM [tablename])X
WHERE [customerinvoiceid] = 1
答案 3 :(得分:-1)
创建表#temp (
customer_number int
,发票编号为int
,名称为varchar(50)
,地址varchar(50)
,总计金额int
)
插入#temp值(1,1,'sam','india',100)
插入#temp值(1,2,'sam k','USA',200)
插入#temp值(2,3,“桑迪”,“非洲”,100)
插入#temp值(2,4,'sandy sharma','india',200)
选择t1。客户编号,t1。发票编号,名称,地址,总和(总计)
来自#temp t1
内部加入
(
从#temp中选择max(Invoice_Number)作为Invoice_Number,客户编号
按客户编号分组
)t2在t1.Invoice_Number = t2.Invoice_Number
和t1.customer_number = t2.customer_number
按t1.customer_number,t1.Invoice_Number,名称,地址分组