SQL required to display all name branches that i h

2020-05-06 14:30发布

i have table called [Updated_SQLSOLD] with field name [Branch], [Barcode] and now i have 10 branches but not all branch has barcode

Example.

*[Branch]    *[Barcode]
----------------------
  branch1  |  25122225
  branch2  |  25122225
  branch3  |  25122225
  branch4  |  25122225
  branch5  |
  branch6  |
  branch7  |
  branch8  |  25122225
  branch9  |
  branch10 |
SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD] where [Barcode] = '25122225'

Result - - is

*[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

Thanks

4条回答
SAY GOODBYE
2楼-- · 2020-05-06 14:54

Use a self-JOIN for your table with a LEFT JOIN :

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

Demo

查看更多
男人必须洒脱
3楼-- · 2020-05-06 14:58

Do not consider any condition in your select statement. Simply write :

SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD] 

Or if you want to have condition and also null values :

SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD] where [Barcode] = '25122225' or NULLIF([Barcode],'') is null
查看更多
聊天终结者
4楼-- · 2020-05-06 15:03

Your question is incomplete. Obviously the answer to your question so far is

SELECT [Branch], [Barcode] FROM [MHO_Report].[dbo].[Updated_SQLSOLD] 

But I'm guessing that you have other Barcodes that you want to exclude? So is the question "where my Barcode or Barcode is null"? So:

SELECT [Branch], [Barcode] 
FROM [MHO_Report].[dbo].[Updated_SQLSOLD] 
where [Barcode] = '25122225' or [Barcode] is null   

Or something else?

查看更多
等我变得足够好
5楼-- · 2020-05-06 15:08

Hope this helps:

select Branch,
    case when Barcode = '25122225' then Barcode else 'Null' end as Barcode
from Branches
查看更多
登录 后发表回答