我的数据结构与Select only last value of date?相同 ,但我需要获取每个日期的值,我标记它们。 Feroc问题的解决方案是仅提供最后日期。
localName Date_Time RH
BAG012 2014-10-09 17:17:58.000 16 <--
BAG012 2014-10-09 17:13:28.000 16
BAG012 2014-10-09 17:12:23.000 16
BAG012 2014-10-09 16:52:54.000 16
BAG012 2014-10-08 05:14:56.000 16 <--
BAG012 2014-10-08 04:45:31.000 16
BAG012 2014-10-08 04:44:08.000 16
SAG165 2014-10-28 11:22:14.000 698 <--
SAG165 2014-10-28 11:09:14.000 698
SAG165 2014-10-28 10:53:18.000 698
SAG165 2014-10-27 19:30:14.000 693 <--
SAG165 2014-10-27 19:14:51.000 693
SAG165 2014-10-27 19:13:56.000 693
这是我正在使用的代码:
WITH CTE AS
(
SELECT LTRIM(localName) as localName, CAST(year(Date_Time) as varchar)+'-'+CAST(month(Date_Time) as varchar)+'-'+CAST(day(Date_Time) as varchar) as date_time, RH, tank, mode,
RN = ROW_NUMBER() OVER (PARTITION BY localName ORDER BY Date_Time DESC)
FROM dbo.SMCData
)
SELECT DISTINCT Date_Time, localName, RH, tank, mode
FROM CTE
WHERE RN = 1
order by LocalName asc
以上两种情况均未对结果进行任何更改。
解答: 谢谢大家,以下对我有用:
WITH CTE AS
(
SELECT localName, Date_Time, RH,
RN = ROW_NUMBER() OVER (PARTITION BY localName, CAST(Date_Time AS date) ORDER BY Date_Time DESC)
FROM dbo.TableName
)
SELECT localName, Date_Time, RH
FROM CTE
WHERE RN = 1
ORDER BY localName, Date_Time;
答案 0 :(得分:1)
WITH CTE AS
(
SELECT localName, Date_Time, RH,
RN = ROW_NUMBER() OVER (PARTITION BY localName, CAST(Date_Time AS date) ORDER BY Date_Time DESC)
FROM dbo.TableName
)
SELECT localName, Date_Time, RH
FROM CTE
WHERE RN = 1
ORDER BY localName, Date_Time;
答案 1 :(得分:0)
使用select distinct:
SELECT DISTINCT date
FROM table_name
它将为您提供每个日期
答案 2 :(得分:0)
SELECT DISTINCT localName, Date , RH
FROM table_name
这应该给出唯一的日期和RH值以及相应的localName。
答案 3 :(得分:0)
按日期分组:
SELECT localName, MAX(date_time) AS max_date_time, MAX(rh) AS max_rh
FROM your_table
GROUP BY localName, CAST(date_time AS date)
这将为您提供每个本地名称的最后日期。
输出:
localName max_date_time max_rh
---------- ----------------------- -----------
BAG012 2014-10-08 05:14:56.000 16
BAG012 2014-10-09 17:17:58.000 16
SAG165 2014-10-27 19:30:14.000 693
SAG165 2014-10-28 11:22:14.000 698