2014-10-28 81 views
0

我試圖得到一個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

回答

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

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

輝煌!!!!!非常感謝你釘了它! – OneNathan 2014-10-29 00:10:24

+0

如何將查詢數據放入新表中? – OneNathan 2014-10-29 01:08:04

+0

更新了我的答案,以創建一個包含結果的新表格。並在表名之前使用散列(#)使其成爲臨時表。 – Ken 2014-10-29 01:12:26