我一直在尝试使用重要性顺序(date2> date1)按两个日期过滤一个表,如下所示:
SELECT
t1.customer, t1.weights, t1.max(t1.date1) as date1, t1.date2
FROM
(SELECT *
FROM table
WHERE CAST(date2 AS smalldatetime) = '10/29/2017') t2
INNER JOIN
table t1 ON t1.customer = t2.customer
AND t1.date2 = t2.date2
GROUP BY
t1.customer, t1.date2
ORDER BY
t1.customer;
它首先按日期2正确过滤表格,但是max(t1.date1)并不是我想要它做的。我得到重复的客户,共享相同(和正确)的date2,但显示不同的date1。这些重复记录具有以下共同点:权重行不同。如果不考虑其他列,只需输出连接到最新日期1的客户记录,我需要做什么?
我仍然是一个菜鸟,非常感谢帮助!
t-sql解决方案(全部基于接受的答案):
SELECT * FROM (
SELECT row_number() over(partition by t1.customer order by t1.date1 desc) as rownum, t1.customer, t1.weights, t1.date1 , t1.date2
FROM
(SELECT *
FROM table
WHERE CAST(date2 AS smalldatetime) = '10/29/2017') t2
INNER JOIN
table t1 ON t1.customer = t2.customer
AND t1.date2 = t2.date2
)t3
where rownum = 1;
答案 0 :(得分:2)
如果我理解正确,那么我将使用qualify行语句而不是逻辑组:)
尝试下面的代码并告诉我它是否是您需要的 - 我告诉它要做的是每个客户ID只返回一行....但是我们根据日期选择行(按按升序对它们进行排序) - 但是,我不清楚你对2个日期的重要性是什么意思,所以我可能完全偏离这里...你能举一个输入和期望输出的例子吗?
SELECT t1.customer, t1.weights, t1.date1, t1.date2
FROM
(
Select *
FROM table
WHERE Cast(date2 as smalldatetime)='10/29/2017'
) t2
Inner Join table t1
ON t1.customer = t2.customer
AND t1.date2 = t2.date2
Qualify row_number() over(partition by t1.customer order by date2 , date1)=1
Order By t1.customer;