我有以下8条记录:
ID | Common ID | Reject
-------------------------
BB-1 | BB | YES
CB-1 | CB | YES
我的预期结果是:
SELECT A.ds_cnref AS 'Stock Ref', A.ds_fact, A.ds_cost, IIF(A.ds_fact='ITM1',A.ds_cost,'B') AS 'Cost Price' FROM DSPROD A
我只想在具有相同公共ID的所有记录的拒绝列为是时获取不同的记录。
答案 0 :(得分:3)
select min(ID), [Common ID], max(Reject)
from tablename
group by [Common ID]
having count(*) = count(case when Reject = 'YES' then 1 end)
如果[Common ID]的行数与YES相同,则返回!
HAVING
子句count(*)
会返回[Common ID]
的总行数。如果Reject = Yes,则case
表达式返回1,否则返回null。右侧count
返回case返回非空值的行数(即当Reject为yes时!)当行数相同时,HAVING
为真!
修改强>
在这种特定情况下,当拒绝列的值似乎为YES或NULL时,HAVING
可以简化为:
having count(*) = count(Reject)
但是,如果在列中找到其他值(如NO),则不会起作用。所以我推荐原始的HAVING
条款!
答案 1 :(得分:1)
SELECT MIN(ID), CommonID, MIN(Reject) as Reject
FROM yourtable
GROUP BY CommonID
HAVING MIN(ISNULL(Reject, '')) = MAX(ISNULL(Reject, ''))
AND MIN(ISNULL(Reject, '')) = 'Yes'
编辑:因为你有NULL值,需要在列
上使用ISNULL()答案 2 :(得分:0)
在GROUP BY
子句中使用WHERE
的子查询。
SELECT ID, [Common ID], Reject
FROM yourtable
WHERE (SELECT SUM(LEN(a.Reject))
FROM yourtable a
WHERE ID = a.ID
GROUP BY a.ID) IS NULL
输出:
SQL小提琴:
答案 3 :(得分:0)
使用row_number
窗口函数和not exists
。有点复杂,但应该做的工作:
with cte as(select *, row_number(partition by commonid order by id) rn from table)
select c.*
from cte c
where c.rn = 1 and
not exists(select * from table t
where t.commonid = c.commonid and
(t.reject is null or t.reject <> 'yes'))
答案 4 :(得分:0)
SELECT MIN(ID) as ID, [Common ID], MIN(Reject) as Reject
FROM Table1
GROUP BY [Common ID]
HAVING MIN(ISNULL(Reject, '')) = 'YES'
答案 5 :(得分:0)
这会对您有所帮助
select
(select top 1 ID from YourTable where CommonID= t.CommonID and reject=t.reject)ID,
CommonID,
Reject
from YourTable T
group by
CommonID,reject
having (Reject is not null)
答案 6 :(得分:0)
试试这个
SELECT MIN(ID) AS ID, ColumnID, MIN(Reject) AS Reject
FROM tableName
WHERE Reject='YES' AND ID LIKE '%1'
GROUP BY ColumnID
答案 7 :(得分:0)
这是实现预期结果的最简单方法。
SELECT ID, [Common ID], Reject
FROM YOURTABLE
WHERE REJECT = 'YES'
GROUP BY ID, COMMON ID