我有一个包含5列的表格,如下所示:
| ID | NAME | PO_NUMBER | DATE | STATS | | 1 | Jhon | 160101-001 | 2016-01-01 | 7 | | 2 | Jhon | 160101-002 | 2016-01-01 | 7 | | 3 | Jhon | 160102-001 | 2016-01-02 | 7 | | 4 | Jane | 160101-001 | 2016-01-01 | 7 | | 5 | Jane | 160102-001 | 2016-01-02 | 7 | | 6 | Jane | 160102-002 | 2016-01-02 | 7 | | 7 | Jane | 160102-003 | 2016-01-02 | 7 |
我需要显示所有值,但stats
字段没有重复,来自date
字段
喜欢这个
| ID | NAME | PO_NUMBER | DATE | STATS | | 1 | Jhon | 160101-001 | 2016-01-01 | 7 | | 2 | Jhon | 160101-002 | 2016-01-01 | null | | 3 | Jhon | 160102-001 | 2016-01-02 | 7 | | 4 | Jane | 160101-001 | 2016-01-01 | 7 | | 5 | Jane | 160102-001 | 2016-01-02 | 7 | | 6 | Jane | 160102-002 | 2016-01-02 | null | | 7 | Jane | 160102-003 | 2016-01-02 | null |
我遇到了希望的麻烦。感谢
答案 0 :(得分:2)
从您的示例数据中,您似乎只想显示以stats
结尾的po_number
001
。如果是这样,这应该是最简单的方法:
select id, name, po_number, date,
case when right(po_number, 3) = '001' then stats else null end as stats
from yourtable
如果您想要order by
po_number
,那么这是使用row_number
的一个选项:
select id, name, po_number, date,
case when rn = 1 then stats else null end as stats
from (
select *, row_number() over (partition by name, date order by po_number) as rn
from yourtable
) t
答案 1 :(得分:0)
因为您使用的是SQL 2012,所以可以使用LEAD()或LAG()窗口函数来比较DATE值
Remove from Most Recently Used list
答案 2 :(得分:0)
使用以下代码
;with temp as (
select id,name ,PO_NUMBER ,DATE, STATS,
LAG (STATS, 1, 0)
OVER (PARTITION BY name ,PO_NUMBER ,DATE ORDER BY id) AS PrevSTATS
from tableName
)
select id,name ,PO_NUMBER ,DATE,
case when STATS = PrevSTATS then null
else STATS end as STATS
from temp