根据记录获取列

时间:2017-09-28 17:24:43

标签: sql-server dynamic-sql

在输入表中,值每周都在变化。因此,下周的E列将是A而不是F,此时我会想要E字段。

因此,必须选择具有A的字段,但具有A的字段应该是表中具有A作为记录的最后一个字段。

输入表:

public class MainActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //Fragment
            new Reproducir.LlenarDatosReproduccion();


            Toast.makeText(getApplicationContext(),"Entró al play",Toast.LENGTH_SHORT).show();

        }
    });

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public static class PlaceholderFragment extends Fragment {
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}


public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        if(position==0){
            return new Reproducir();
        }else {
            return PlaceholderFragment.newInstance(position + 1);
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "REPRODUCIR";
            case 1:
                return "PLAYLIST";
            case 2:
                return "CANCIONES";
        }
        return null;
    }
}

输出:

public class Reproducir extends Fragment {

private static TextView tvTitle,tvArtist;
FloatingActionButton fabPlay;
private String url="http://streaming.hotmixradio.fr/hotmixradio-hits-128.mp3";
private ImageView ivAlbum;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView=inflater.inflate(R.layout.tab_reproduccion,container,false);
    //new LlenarDatosReptoduccion();
    tvTitle=(TextView)rootView.findViewById(R.id.tv_title);
    //tvTitle.setText(url);
    tvArtist=(TextView)rootView.findViewById(R.id.tv_title);

    return rootView;

}

public static class LlenarDatosReproduccion extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Ups! Error.Parece que la url es inválida";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        Log.i("POSTExecute","Ingesó antes del try");
        try {
            Log.i("POSTExecute","Ingesó al try");

            JSONObject responseJSON = new JSONObject(result.toString());

            JSONObject cancionJSON = responseJSON.getJSONObject("cancion");
            tvTitle.setText(cancionJSON.get("title").toString());
            Log.d("ARTISTA",cancionJSON.get("artist").toString());
            //tvArtist.setText(cancionJSON.getString(2));


        } catch (JSONException e) {
            Log.i("POSTExecute","Ingesó al catch!");

            e.printStackTrace();
        }

        super.onPostExecute(result);
    }
}


private static String downloadUrl(String myUrl) throws IOException {
    Log.i("URL"," LA URL URL URL: "+myUrl);
    myUrl.replace(" ","%20");
    InputStream is=null;

    int lengh=500;

    try{

        return "{\"cancion\":{\"title\":\"Versace On The Floor (Vs David Guetta)\",\"artist\":\"BRUNO MARS\",\"duration\":\"18783\"}}";

    }finally {
        if(is!=null){
            is.close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我知道如果您需要一个逻辑来获取可以使用此代码的结果,那么您的数据会因某种原因而非标准化:

DECLARE @table TABLE (A varchar(3), B varchar(3),C varchar(3), D varchar(3), E varchar(3))

;WITH cte 
     AS (SELECT ColumnName 
                ,ColumnValue
                ,Row_number() 
                   OVER( 
                     partition BY ColumnName 
                     ORDER BY Rn) ResultOrder 
         FROM   (SELECT Row_number() OVER (ORDER BY (SELECT NULL))Rn,a ,b ,c ,d ,e FROM   @table) p 
            UNPIVOT ( ColumnValue 
                    FOR ColumnName IN( a ,b ,c ,d ,e)) AS unpvt), 
     cte1 
     AS (SELECT Ntile(5) 
                  OVER( 
                    ORDER BY ColumnName) ColumnId 
                ,* 
         FROM   cte), 
     cte2 
     AS (SELECT DISTINCT Isnull(NULLIF(ColumnId - 1, 0), 5) ColumnId 
                         ,ColumnName 
         FROM   cte1 
         WHERE  ColumnValue = 'F') 
SELECT result 
FROM   (SELECT CASE ColumnId 
                 WHEN 1 THEN 'A' 
                 WHEN 2 THEN 'B' 
                 WHEN 3 THEN 'C' 
                 WHEN 4 THEN 'D' 
                 WHEN 5 THEN 'E' 
               END Result 
               ,0  ResultOrder 
        FROM   cte2 
        UNION 
        SELECT ColumnValue 
               ,resultorder 
        FROM   cte1 a 
        WHERE  EXISTS (SELECT 1 
                       FROM   cte2 b 
                       WHERE  a.ColumnId = b.ColumnId)) AS R 
ORDER  BY resultorder 

结果

insert @table VALUES
('A','A','A','A','F')
,('12','32','43','23','2')

A    B    C    D    E
---- ---- ---- ---- ----
A    A    A    A    F
12   32   43   23   2

result
------
D
23
A

结果

insert @table VALUES
('F','A','A','A','A')
,('12','32','43','23','2')
A    B    C    D    E
---- ---- ---- ---- ----
F    A    A    A    A
12   32   43   23   2

result
------
E
A
2

说明:

  • CTE 表执行Unpivot表并创建行号以订购列名称和值
  • CT1 表使用NTILE创建一个基于列名的组来创建5个组
  • CTE2 表获取值为F
  • 的上一列
  • 选择是复杂的,如果没有必要,将ColumnId转换为ColumnName,

你可以使用

SELECT ColumnValue Result              
FROM   cte1 a 
WHERE  EXISTS (SELECT 1 
FROM   cte2 b 
WHERE  a.ColumnId = b.ColumnId)

Result
------
A
23

(2 row(s) affected)

OR

SELECT ColumnValue Result              
FROM   cte1 a 
WHERE  EXISTS (SELECT 1 
FROM   cte2 b 
WHERE  a.ColumnId = b.ColumnId) 
AND a.ResultOrder = 2

Result
------
23

(1 row(s) affected)