我表中的一列是“DataSource”。数据源可以有两个值,比如“A”或“B”。我想在Datasource =“A”时总是拿行,但是,如果没有A的条目我想拿“B”。
如何在SQL Server中执行此操作?
编辑:
因此,对于一个产品ID(产品ID),一个产品ID可能有两行,每行包含一个不同的DataSource,另一个ProductID可能只有一个DataSource:
{ProductID DataSource}
{1 A},
{1 B},
{2 B}
在这里,我希望选择顶行和底行
答案 0 :(得分:2)
编辑后的几个选项...
SELECT
*
FROM
table
WHERE
DataSource = 'A'
OR DataSource = 'B' AND NOT EXISTS (SELECT * FROM table AS lookup WHERE ProductID = table.ProductID AND DataSource = 'A')
SELECT
*
FROM
table
INNER JOIN
(SELECT ProductID, MAX(DataSource) AS DataSource FROM table) AS lookup
ON lookup.ProductID = table.ProductID
AND lookup.DataSource = table.DataSource
WITH
sequenced AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY ProductID ORDER BY DataSource) AS sequence_id
FROM
table
)
SELECT
*
FROM
sequenced
WHERE
sequence_id = 1
答案 1 :(得分:1)
select ProductID from product where DataSource= 'A'
UNION
select id from DataSource where product not in (select ProductID from product where DataSource = 'A')
答案 2 :(得分:1)
SELECT top 1 *
from YourTable
ORDER BY DataSource ASC
其他
如果实际值不是'A'或'B',它们只是@A和@B变量的占位符
SELECT top 1 *
from YourTable
ORDER BY CASE DataSource WHEN @A THEN 0 ELSE 1 END ASC
或强>
如果有比AB更多的差异
SELECT top 1 *
from YourTable
ORDER BY CASE DataSource WHEN @A THEN 0 WHEN @B THEN 1 ELSE 2 END ASC
或
如果您需要按ProductId分组
select * from (
SELECT *,
ROW_NUMBER OVER(PARTITION BY ProductId ORDER BY CASE DataSource WHEN @A THEN 0 WHEN @B THEN 1 ELSE 2 END ASC) ordinal
from YourTable
) t
WHERE t.Ordinal = 1
答案 3 :(得分:0)
好的,如果我理解你的要求,那么这将有效
select TOP 1 * from yourtable where DATASOURCE = ISNULL(SELECT MAX(DATASOURCE) WHERE DATASOURCE="A","B")
这里的想法很简单,你想根据你的第一个偏好(“A”)的行是否可用来改变DATASOURCE条件,如果是,则应用“A”条件或应用“B”条件
答案 4 :(得分:0)
根据您的示例数据,这有效:
SELECT ProductID, MIN(DataSource)
FROM @tab
GROUP BY ProductID;
这是我的测试数据:
declare @tab table (ProductID int, DataSource char(1))
insert into @tab values (1, 'A');
insert into @tab values (1, 'B');
insert into @tab values (2, 'B');
如果表格中的列数多于您显示的列数:
SELECT T1.*
FROM @tab T1
JOIN
(
SELECT ProductID, MIN(DataSource) AS DataSource
FROM @tab
GROUP BY ProductID
) T2 ON T1.ProductID = T2.ProductID AND T1.DataSource = T2.DataSource