为SQL查询创建if语句

时间:2015-09-16 20:39:21

标签: sql-server if-statement case

我希望看到的视图类似于以下相同的示例,其中数据来自3个不同的表

sample resultant table

我想创建一个查询,用public class DatabaseConnector //extends ArrayList<String> { public static Cursor cursor ; Scanner scDict; InputStream stream = null; Context mContext; AssetManager mAssets; public static final String DATABASE_NAME = "Dictionary"; public static final String TABLE_NAME = "wordlist"; public static final String WORD_COLUMN_NAME = "word"; public static final String STATUS_COLUMN_NAME = "status"; public static final String [] columns = new String[]{WORD_COLUMN_NAME, STATUS_COLUMN_NAME}; private DatabaseOpenHelper ___databaseOpenHelper; // creates the database private SQLiteDatabase ___database; // for interacting with the database public DatabaseConnector(Context _context, AssetManager assets) { mContext = _context; mAssets = assets; ___databaseOpenHelper = new DatabaseOpenHelper(_context, DATABASE_NAME, null, 1); Log.w("DB connected", ___databaseOpenHelper.getDatabaseName()); createDbIfNecessary(); }; public void open() throws SQLException // opens/creates { ___database = ___databaseOpenHelper.getWritableDatabase(); // create OR open } public void createDbIfNecessary(){ this.open(); if(getDbCount() < 140000){ try { stream = mAssets.open("dictionary.dic"); } catch (IOException e) { System.out.println(Arrays.toString(e.getStackTrace())); } MainActivity.setLblProgress("This one-time task takes awhile: loading letter... "); LoadWords loadWords = new LoadWords(); loadWords.execute((Object[]) null); this.close(); } } public void close(){ if(___database != null) ___database.close(); } public int getDbCount(){ this.open(); return ___database.query(TABLE_NAME, columns, null, null, null, null, null).getCount(); } public long insertWord(String _word) { ContentValues __newWord; __newWord = new ContentValues(); __newWord.put(WORD_COLUMN_NAME, _word); __newWord.put(STATUS_COLUMN_NAME, true); long __row = ___database.insert(TABLE_NAME, null, __newWord); return __row; // -1 if can't insert } ////////////////////////////////////////////////////////////////////////////////////////////////// private class DatabaseOpenHelper extends SQLiteOpenHelper { public DatabaseOpenHelper(Context _context, String _name, CursorFactory _factory, int _version) { super(_context, _name, _factory, _version); } @Override public void onCreate(SQLiteDatabase _db) { _db.execSQL( "CREATE TABLE " + TABLE_NAME + "(" + WORD_COLUMN_NAME + " TEXT primary key , " //not null, " + STATUS_COLUMN_NAME + " BOOLEAN" + ");" ); // execute query to create the ___database } } // end class DatabaseOpenHelper ////////////////////////////////////////////////////////////////////////////////////////////////// private class LoadWords extends AsyncTask<Object, Integer, Void> { @Override protected Void doInBackground(Object... params) { long k = 0; scDict = new Scanner(stream).useDelimiter("\r\n"); long count = getDbCount(); Log.w("Start load at " , "" + count); String s = ""; while(k++ < count){ s = scDict.next(); } Log.w("Add after " , s); while (scDict.hasNext()) { s = scDict.next(); publishProgress((Integer)(int)s.charAt(0)); insertWord(s) ; return null; } protected void onProgressUpdate(Integer... progress) { int c = (int)progress[0]; MainActivity.setLastLetterProcessed((char) c); } @Override protected void onPostExecute(Void x) { MainActivity.popupMessage("Database has been created", mContext); } } } // end class DatabaseConnector companylocation选择每个rooms,但如果adddresscompany CA中的位置我不想在NYOR中选择任何其他位置。我看过CASE但我不确定如何在这种情况下使用它,因为我不想输入名称。现在我的查询是这样的

 SELECT DISTINCT TOP (100) PERCENT
     DBO.HOTEL.COMPANY, DBO.HOTEL.LOCATION AS LOCATION, DBO.AMOUNT.ROOMS, 
     DBO.PERSON.OWNERS, DBO.PERSON.ADDRESS
 FROM DBO.HOTEL INNER JOIN DBO.HOTEL.ID = DBO.AMOUNT.HOTEL_ID INNER JOIN
      DBO.HOTEL.ID = DBO.PERSON.HOTEL_ID
 WHERE (LOCATION = 'OR' OR LOCATION = 'CA' OR LOCATION = 'NY') AND
       DBO.HOTEL.OPEN_DATE >= 01/01/2015

2 个答案:

答案 0 :(得分:0)

您可以在此上下文中使用NOT EXISTS:

SELECT DISTINCT TOP (100) PERCENT
  DBO.HOTEL.COMPANY,
  DBO.HOTEL.LOCATION AS LOCATION,
  DBO.AMOUNT.ROOMS, 
  DBO.PERSON.OWNERS,
  DBO.PERSON.ADDRESS
FROM
  DBO.HOTEL INNER JOIN DBO.HOTEL.ID = DBO.AMOUNT.HOTEL_ID
  INNER JOIN DBO.HOTEL.ID = DBO.PERSON.HOTEL_ID
WHERE
  LOCATION = 'CA' OR (
    (LOCATION = 'OR' OR LOCATION = 'NY')
    AND 
    NOT EXISTS (
        SELECT * FROM DBO.HOTEL h
        WHERE h.id=DBO.HOTEL.ID AND LOCATION='CA'
      )
    )
  AND DBO.HOTEL.OPEN_DATE >= '01/01/2015'

答案 1 :(得分:0)

根据您的问题,我了解您希望选择每个公司的位置,房间和地址。如果公司在CA,您只需要列出。

你可以尝试这样的事情(这里的例子http://sqlfiddle.com/#!3/f9897/1):

create table hotel (
    company char(2),
    location char(2),
    rooms int,
    owners char(3),
    address varchar(20)
);

insert into hotel values 
('C1', 'NY', 32, 'BAP', '123 Appl'),
('C1', 'CA', 21, 'BAP', '123 Appl'),
('C1', 'OR', 24, 'BAP', '123 Appl'),
('C2', 'OR', 54, 'RED', '123 Appl'),
('C3', 'CA', 35, 'EDR', '123 Appl'),
('C4', 'NY', 14, 'LPD', '123 Appl'),
('C5', 'NY', 48, 'LPD', '123 Appl'),
('C6', 'CA', 98, 'WES', '123 Appl'),
('C6', 'OR', 56, 'WES', '123 Appl'),
('C7', 'OR', 61, 'YTR', '123 Appl'),
('C8', 'OR', 12, 'YTR', '123 Appl'),
('C9', 'CA', 25, 'MAD', '123 Appl'),
('C9', 'NY', 65, 'MAD', '123 Appl'),
('C9', 'OR', 38, 'MAD', '123 Appl');

select * from hotel
where location = 'CA'
    union all
select * from hotel
where company not in (select company from hotel where location = 'CA');

Result
company location    rooms   owners  address
C1      CA          21      BAP     123 Appl
C2      OR          54      RED     123 Appl
C3      CA          35      EDR     123 Appl
C4      NY          14      LPD     123 Appl
C5      NY          48      LPD     123 Appl
C6      CA          98      WES     123 Appl
C7      OR          61      YTR     123 Appl
C8      OR          12      YTR     123 Appl
C9      CA          25      MAD     123 Appl