需要SQL来显示我拥有的所有名称分支,但并非所有分支都有我搜索的条形码
我有一个名为[Updated_SqlSeld]的表,字段名为[Branch],[Barcode],现在我有10个分支,但不是所有分支都有条形码 例如需要SQL来显示我拥有的所有名称分支,但并非所有分支都有我搜索的条形码,sql,sql-server,Sql,Sql Server,我有一个名为[Updated_SqlSeld]的表,字段名为[Branch],[Barcode],现在我有10个分支,但不是所有分支都有条形码 例如 *[Branch] *[Barcode] ---------------------- branch1 | 25122225 branch2 | 25122225 branch3 | 25122225 branch4 | 25122225 branch5 | branch6 | branch7
*[Branch] *[Barcode]
----------------------
branch1 | 25122225
branch2 | 25122225
branch3 | 25122225
branch4 | 25122225
branch5 |
branch6 |
branch7 |
branch8 | 25122225
branch9 |
branch10 |
结果是
*[Branch] *[Barcode]
----------------------
branch1 | 25122225
branch2 | 25122225
branch3 | 25122225
branch4 | 25122225
branch8 | 25122225
now how to display all branches even if no serial is available, like this
*[Branch] *[Barcode]
----------------------
branch1 | 25122225
branch2 | 25122225
branch3 | 25122225
branch4 | 25122225
branch5 | Null
branch6 | Null
branch7 | Null
branch8 | 25122225
branch9 | Null
branch10 | Null
谢谢
< P>不要在SELECT语句中考虑任何条件。简单地写下:SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD]
或者,如果希望有条件和空值:
SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD] where [Barcode] = '25122225' or NULLIF([Barcode],'') is null
希望这有助于:
select Branch,
case when Barcode = '25122225' then Barcode else 'Null' end as Barcode
from Branches
对具有
左联接的表使用自联接
:
SELECT u1.[Branch], u1.[Barcode]
FROM [MHO_Report].[dbo].[Updated_SQLSOLD] u1
LEFT JOIN [MHO_Report].[dbo].[Updated_SQLSOLD] u2
ON u1.[Branch] = u2.[Branch]
AND u1.[Barcode] = u2.[Barcode] -- this line is optional
AND u1.[Barcode] = 25122225 -- assuming [Barcode] is a numeric field,
-- no need for quotes
你的问题不完整。显然,到目前为止,你的问题的答案是
SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD]
但我猜你还有其他的条形码要排除?那么,“我的条形码或条形码为空”的问题是什么呢?因此:
还是其他什么?删除where子句或使用UNION ALL。使用NULLIF([Barcode],“”),它会将空字符串转换为空值。使用UNION ALL时按[Branch]排序。如果,如果类似这样的情况,我需要按分支分组``*[Branch]*[Barcode]第十三章分行1 | 2512225分行2 | 2512225分行3 | 2512225分行4 | 2512225分行5 | 34343434分行7 | 56565656分行8 | 2512225分行22 | 22222分行10 |4444444@rsupson如果您可以为分组提供示例数据和预期结果那么我将尝试为您提供适当的SQL查询。@rsupson对于您刚才在注释中提供的数据,每条记录只有一个分支,因此按分支分组不会给您提供不同的结果集。
SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD]
SELECT [Branch], [Barcode]
FROM [MHO_Report].[dbo].[Updated_SQLSOLD]
where [Barcode] = '25122225' or [Barcode] is null