我有一个 WHERE
从逻辑上讲,我希望它带回短名称的第一个数字不匹配的结果。
短名称可以是:
1.1
1.2
2.1
2.2
样本数据无
where
条款:+-----------+--------+------+
| Shortname | number | ID |
+-----------+--------+------+
| 2.1 | 1 | 3333 |
| 1.1 | 60 | 3333 |
| 1.2 | 90 | 3333 |
| 2.1 | 50 | 4444 |
| 2.2 | 30 | 4444 |
| 1.1 | 80 | 5555 |
| 1.2 | 10 | 5555 |
+-----------+--------+------+
预期数据 WITH
where
条款:+-----------+--------+------+
| Shortname | number | ID |
+-----------+--------+------+
| 2.1 | 1 | 3333 |
| 1.1 | 60 | 3333 |
| 1.2 | 90 | 3333 |
+-----------+--------+------+
我试过代码:
SELECT shortname, number, id
FROM table
WHERE ((left(shortname,1) like '%1%') != ((left(shortname,1) like '%2%')
但它会产生错误:
Msg 102, Level 15, State 1, Line 21
Incorrect syntax near '!'.
澄清更新
我需要每个 ID 的结果,所以在上面的示例中有 ID 的 3333、4444 和 5555。我只想带回 ID
3333
因为它在每个 shortname
中不只有一个第一个字符值。 .它包含两个值 1
和 2
.因为我不想看到其他 ID,因为第一个数字上有短名称匹配 1 = 1 和 2 = 2 等。
最佳答案
如果您想返回 ID
shortname
中的多个第一个字符,然后首先查看获取不同的行数:
select id
from yourtable
group by id
having count(distinct left(shortname, 1)) > 1;
当与 ID 关联时,这应该会返回第一个字符为 2 和 1 的行。然后你可以用它来返回其余的数据:
;with cte as
(
select id
from yourtable
group by id
having count(distinct left(shortname, 1)) > 1
)
select
t.shortname,
t.number,
t.id
from yourtable t
inner join cte c
on t.id = c.id;
见 SQL Fiddle with Demo .这将返回:
| SHORTNAME | NUMBER | ID |
|-----------|--------|------|
| 2.1 | 1 | 3333 |
| 1.1 | 60 | 3333 |
| 1.2 | 90 | 3333 |
更灵活的选择是获取小数点之前的字符并验证您对所有数字的计数是否不同。为此,您将使用类似
CHARINDEX
的函数。随着LEFT
.;with cte as
(
select id
from yourtable
group by id
having count(distinct left(shortname, charindex('.', shortname)-1)) > 1
)
select
t.shortname,
t.number,
t.id
from yourtable t
inner join cte c
on t.id = c.id;
见 SQL Fiddle with Demo .这将返回:
| SHORTNAME | NUMBER | ID |
|-----------|--------|------|
| 2.1 | 1 | 3333 |
| 1.1 | 60 | 3333 |
| 1.2 | 90 | 3333 |
| 14.1 | 5 | 6666 |
| 14.2 | 78 | 6666 |
| 24.1 | 89 | 6666 |
关于SQL WHERE 语句在使用不同计数时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27564819/