SQL Query仅根据值返回记录集

时间:2014-10-28 23:26:38

标签: sql sql-server

我尝试获取SQL查询以返回一组基于int值设置为1的值

 Date           Name                Split         ID 
2014-09-02    Harry Potter         1            23
2014-09-02    Harry Potter         1            434
2014-09-02    Michael Jinks        0            24
2014-09-02    Sam Smith            1            12
2014-09-02    Sam Smith            1            244
2014-09-02    Kelly Jane           0            124
2014-09-03    Harry Potter         1            23
2014-09-03    Harry Potter         1            434

我希望它只返回用户使用Harry Potter的每条记录中的一个值,如果split设置为“1”,则忽略第二个记录ID

如果Split =“1”,它必须是if语句,然后查找最高记录并返回值,但我找不到任何东西可以做到这一点。

我试过了

select  distinct * from LOG where split = 1

应该返回类似这样的内容

Date           Name                Split         ID 
2014-09-02    Harry Potter         1            23
2014-09-02    Michael Jinks        0            24
2014-09-02    Sam Smith            1            12
2014-09-02    Kelly Jane           0            124
2014-09-03    Harry Potter         1            23

2 个答案:

答案 0 :(得分:2)

这个怎么样?

create table #temp(
    [date] smalldatetime,
    name varchar(100),
    split int,
    id int
)
insert into #temp
select '2014-09-02', 'Harry Potter', 1, 23 union all
select '2014-09-02', 'Harry Potter', 1, 434 union all
select '2014-09-02', 'Michael Jinks', 0, 24 union all
select '2014-09-02', 'Sam Smith', 1, 12 union all
select '2014-09-02', 'Sam Smith', 1, 244 union all
select '2014-09-02', 'Kelly Jane', 0, 124 union all
select '2014-09-03', 'Harry Potter', 1, 23 union all
select '2014-09-03', 'Harry Potter', 1, 434

-- Start
;with cte as(
    select
        *,
        row_number() over(partition by name order by [date], id) as rn -- For each name display first record with earliest date and lowest id
        --row_number() over(partition by name, [date] order by id) as rn -- For each name/date combination display first record with lowest id
    from #temp -- replace with your table name
)
select
    [date],
    name,
    split,
    id
from cte
where
    split = 1
    and rn = 1
-- End
drop table #temp

答案 1 :(得分:1)

如果您感兴趣的ID始终是最低ID,那么

SELECT Date, Name, Split, MIN(ID) 
FROM log
GROUP BY Date, Name, Split

更新新表格问题的答案。

SELECT Date, Name, Split, MIN(ID) as ID
INTO tablename
FROM log
GROUP BY Date, Name, Split