SQL Query用于查找具有不同值的表中的数据

时间:2015-08-25 13:41:16

标签: sql-server

尝试从表中获取不同的值,其中另一个字段=一个id而不是另一个。

select id from tbl1
where route = 28 but not = 30

id有多个条目,我试图找到只有路由28且没有路由30的id。以下是我尝试过的但没有成功:

select ID
FROM Table
Where route like '28' and route <> '30'

2 个答案:

答案 0 :(得分:1)

select id 
from tbl1 
group by id
having sum(case when route = 28 then 1 else 0 end) > 0
   and sum(case when route = 30 then 1 else 0 end) = 0

答案 1 :(得分:1)

另一种方法是使用import csv from collections import OrderedDict from xml.etree.ElementTree import ParseError import collections from __future__ import print_function def get_clientresponses_2(filename = 's.csv'): with open(filename, 'rU') as infile: reader = csv.DictReader(infile) # read the file as a dictionary for each row ({header : value}) data = {} for row in reader: for header, value in row.items(): try: data[header].append(value) except KeyError: data[header] = [value] client_responses = data['E'] #returns a list for client_response in client_responses: xml_string = (''.join(client_response)) xml_string = xml_string.replace('&amp;', '') try: root = ElementTree.XML(xml_string) # print(root) return root except ET.ParseError: print("catastrophic failure") continue def allocate_and_write_2(): with open(filename, 'r') as infile: reader = csv.DictReader(infile) # read the file as a dictionary for each row ({header : value}) header = set() results = [] # data = {} # this is not needed for the purpose of this organization for row in reader: for xml_data in get_clientresponses_2(): xml_dat = dict(flatten_dict(xml_data)) row.update(xml_dat) # just for XML data results.append(row) # everything else header.update(row.keys()) # can't forget headers # print(row) # returns dictionary of key values pairs (headers : values) # print(results) # returns list wrapper for dictionary # print(headers) #returns set of all headers headers_list = list(header) # print(headers_list) #list form of set with open('csv_output.csv', 'wt') as f: writer = csv.writer(f) writer.writerow(headers_list) for row in results: data = [row.get(x, '') for x in headers_list] # print(data) writer.writerow(data) # writer.writerows(zip(headers_list, data))

NOT EXISTS

如果条件变得更复杂或者您想要所有列,这种方法会更好。