我有一个包含大量列的表,但我只需要从表中返回5列:
Name | Charge Code | Charge Amount | Modifier | Date
我希望仅根据“不同名称”,“费用代码”,“费用金额”和“修改符”返回字段。日期可以是记录存在的最新日期。我怎么能这样做?
目前我有:
Select
Name, Charge_code, Charge_amount, Modifier, Date
From
Table1
group by
Name, Charge_code, Charge_amount, Modifier
但是,当我这样做时,它告诉我日期在选择列表中无效,因为它不包含在聚合函数或组中。我不希望按功能原因在组中包含Date,然后它将返回一堆不必要的无关行。但我确实希望日期显示该人收取该金额的最新日期。
我也试过
Select
Date, Distinct Name, Charge_Code, Charge_amount, Modifier
From
Table 1
任何想法都会对我有所帮助。
由于
答案 0 :(得分:1)
典型的方法是使用row_number()
:
select Name, ChargeCode, ChargeAmount, Modifier, Date
from (select t.*,
row_number() over (partition by Name, ChargeCode, ChargeAmount, Modifier
order by date desc
) as seqnum
from t
) t
where seqnum = 1;
答案 1 :(得分:1)
SELECT distinct main.Name, main.ChargeCode, main.ChargeAmount, main.Modifier,
b.Date
FROM Table1 as main
Outer Apply (Select Top 1 Date
from Table1 as sub
where main.Name = sub.Name and main.ChargeCode = sub.ChargeCode and main.ChargeAmount = sub.ChargeAmount and main.Modifier = sub.Modifier
Order by sub.Date desc
) b
答案 2 :(得分:1)
您也可以尝试这一点,简单易行
Select name,
charge_code,
charge_amount,
modifier,
max(date) date
From table1
Group by name, charge_code, charge_amount, modifier