我有一个包含多行数据的表,我只需要选择每个不同组模型的最新日期,并且该列中除了“ CONSIGN”和“ N / A”外还包括“ BUY”和“ A / R”。例如: 我只想选择catm等于'BUY'/'A / R'的最后一行。
id partno model catm date
1. 001 TOYOTA CONSIGN 2010
2. 001 HONDA CONSIGN 2009
3. 001 HONDA BUY 2015
4. 001 TESLA CONSIGN 2018
5. 001 TESLA CONSIGN 2018
SELECT partno,max(date) as maxdate
FROM [mytable]
WHERE partno='001'
GROUP BY model
ORDER BY maxdate DESC
空空空空空
以上是我想要的预期结果。因为最新的日期catm是'CONSIGN',所以它什么也不会显示。但是实际结果会告诉我这一点。
id partno model catm date
1. 001 HONDA BUY 2015
答案 0 :(得分:0)
尝试以下操作:
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("partno", typeof(string));
dt.Columns.Add("model", typeof(string));
dt.Columns.Add("catm", typeof(string));
dt.Columns.Add("date", typeof(int));
dt.Rows.Add(new object[] {"1.", "001", "TOYOTA", "CONSIGN", 2010});
dt.Rows.Add(new object[] {"2.", "001", "HONDA", "CONSIGN", 2009});
dt.Rows.Add(new object[] {"3.", "001", "HONDA", "BUY", 2015});
dt.Rows.Add(new object[] {"4.", "001", "TESLA", "CONSIGN", 2018});
dt.Rows.Add(new object[] {"5.", "001", "TESLA", "CONSIGN", 2018});
List<DataRow> latest = dt.AsEnumerable()
.OrderByDescending(x => x.Field<int>("date"))
.Where(x => x.Field<string>("catm") == "BUY" || x.Field<string>("catm") == "A/R")
.ToList();
答案 1 :(得分:0)
您可以使用窗口功能执行所需的操作:
select t.*
from (select t.*, max(t.date) over (partition by t.model) as max_date
from mytable t
) t
where t.partno = '001' and
t.catm in ('Buy', 'A/R') and
t.date = t.max_date;
答案 2 :(得分:0)
您可以使用公用表表达式和ROW_NUMBER函数来执行此操作, 在这种情况下,我要按日期desc排序数据集,并在每个数据集上放置一个行号,因此RN = 1始终是最新记录,在选择之后,您可以根据需要将任何内容放在where子句中。
function createActionGetRequest()
{
var form = document.getElementById("searchForm");
var elements = form.elements;
var values = [];
for (var i = 0; i < elements.length; i++)
{
values.push(encodeURIComponent(elements[i].name) + '=' + encodeURIComponent(elements[i].value));
}
var userForm = document.getElementById("userType");
values.push(encodeURIComponent("userType") + '=' + encodeURIComponent(userForm.value));
var searchForm = document.getElementById("searchType");
values.push(encodeURIComponent("searchType") + '=' + encodeURIComponent(searchForm.value));
// dummy test for GET request
form.action += '?' + "search1=987654321" + '&' + "search2=987654321";
console.log(form.action);
alert('pause');
form.submit();
}