SQL查询返回基于vaule

问题描述:

我试图得到一个SQL查询返回一组基于AA int值的值设置为1SQL查询返回基于vaule

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 

我希望它只返回一个值仅记录集从每次使用哈利波特的用户记录,如果拆分设置为“1”,则忽略第二个记录ID

它需要是if语句,如果Split =“1”然后查找最高记录和返回值,但没有我可以找到可以做到这一点。

我曾尝试

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 
+0

我想你想使用''上拆分= 1' – genisage 2014-10-28 23:31:00

+0

过滤后,选择DISTINCT'你应该包括你跑到上面的输出查询。 – Exupery 2014-10-28 23:32:08

+0

试图仍将返回所有的值,因为ID是不同的 – OneNathan 2014-10-28 23:33:10

这个怎么样?

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 
+0

它的作品,我只需要制定出如何将它应用到我的查询 – OneNathan 2014-10-28 23:36:10

+0

看到我的编辑的意见。 – 2014-10-28 23:38:34

+0

这似乎是一半的工作,但它现在放弃任何价值与相同的细节,看看哈利波特值是如何在两次它应该只返回2记录不是4 – OneNathan 2014-10-28 23:49:04

如果你感兴趣的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 
+0

辉煌!!!!!非常感谢你钉了它! – OneNathan 2014-10-29 00:10:24

+0

如何将查询数据放入新表中? – OneNathan 2014-10-29 01:08:04

+0

更新了我的答案,以创建一个包含结果的新表格。并在表名之前使用散列(#)使其成为临时表。 – Ken 2014-10-29 01:12:26