我有一张桌子:
| LastName | FirstName | Title | isdefault |
+----------+-----------+----------------------+-----------+
| Davolio | Nancy | Sales Representative | 1 |
| Fuller | Andrew | Vice President, Sales| 1 |
| Fuller | Andrew | Vice President, Sales| 0 |
| Fuller | Andrew | Vice President, Sales| 0 |
| Leverling| Janet | Sales Representative | 0 |
| Leverling| Janet | Sales Representative | 0 |
| Leverling| Janet | Sales Representative | 0 |
在SQL Server数据库中。
我的查询是:
SELECT
LastName, FirstName, Title, isdefault
FROM
Employees
我希望选择相同的记录,isdefault = 0
。所以我的新输出应该是:
| LastName | FirstName | Title | isdefault |
+----------+-----------+----------------------+-----------+
| Leverling| Janet | Sales Representative | 0 |
| Leverling| Janet | Sales Representative | 0 |
| Leverling| Janet | Sales Representative | 0 |
我尝试使用GROUP BY
:
SELECT
LastName, FirstName, Def_flag
FROM
Employees
WHERE
Def_flag = 0
GROUP BY
LastName, FirstName, Def_flag
但结果并不能让我满意,因为安德鲁·富勒的记录也进入了表格。
我如何更改查询?
问候,亚历山大。
答案 0 :(得分:0)
您的意思是,Def_flag的所有条目都为0的员工<?p>
select
LastName,
FirstName,
Def_flag
from (
select
ROW_NUMBER() OVER (
PARTITION BY
LastName,FirstName
ORDER BY
Def_flag DESC
) i
LastName,
FirstName,
Def_flag
FROM Employees
) T
where
i = 1 and
Def_flag = 0
答案 1 :(得分:0)
假设isdefault有点,你可以这样做。否则使用sum(isdefault)= 0,尽管它仍然可以正常工作。我假设默认情况永远不会消极
SELECT LastName, FirstName, Title
FROM <yourtable>
GROUP BY LastName, FirstName, Title
HAVING sum(isdefault+0) = 0
这将返回
LastName FirstName Title
Leverling Janet Sales Representative
答案 2 :(得分:0)
SELECT e1.*
FROM Employees e1
left join (SELECT distinct LastName, FirstName FROM Employees t WHERE isdefault = 1 ) exclude
ON e1.FirstName = exclude.FirstName
AND e1.LastName = exclude.LastName
WHERE (Exclude.FirstName IS NULL AND Exclude.LastName IS NULL)
我假设FirstName + LastName是你的密钥。如果你有一个id,你应该替换它..