如何在这里使用案例

时间:2016-07-25 09:47:21

标签: sql sql-server

我需要创建一个SQL查询来从DB生成以下输出。

enter image description here

我正在寻找像这样的条件

  

当week_val为1时,则hour_val应来自week_val 2行。   否则hour_val来自同一行。

4 个答案:

答案 0 :(得分:2)

@Override
public void handleTag(final boolean opening, final String tag, final Editable output, final XMLReader xmlReader) {
    if (UL_TAG.equalsIgnoreCase(tag)) {
        if (opening) {   // handle <ul>
            lists.push(new Ul());
        } else {   // handle </ul>
            lists.pop();
            if (output.length() > 0 && output.charAt(output.length() - 1) == '\n') {
                output.delete(output.length() - 1, output.length());
            }
        }
    } else if (OL_TAG.equalsIgnoreCase(tag)) {
        if (opening) {   // handle <ol>
            lists.push(new Ol()); // use default start index of 1
        } else {   // handle </ol>
            lists.pop();
            if (output.length() > 0 && output.charAt(output.length() - 1) == '\n') {
                output.delete(output.length() - 1, output.length());
            }
        }
    } else if (LI_TAG.equalsIgnoreCase(tag)) {
        if (opening) {   // handle <li>
            lists.peek().openItem(output);
        } else {   // handle </li>
            lists.peek().closeItem(output, lists.size());
        }
    } else {
        Log.d("TagHandler", "Found an unsupported tag " + tag);
    }
}

答案 1 :(得分:1)

您可能需要使用CASE Statment

的子查询
SELECT CASE WHEN week_val =1 THEN (SELECT TOP 1 hour_val FROM TABLE NAME WHERE week_val <> 1)
       ELSE  hour_val
       END
FROM  TableName

答案 2 :(得分:1)

如果您确定将有一行使用week_val = 2,那么您可以避免使用子查询。

select week_val, 
       case week_val when 1 then lead(hour_val) over (order by week_val) else hour_val end as hour_val
  from t

答案 3 :(得分:1)

也许这个 - 加入而不是subselect:

SELECT
    t1.week_val,
    CASE t1.week_val WHEN 1 THEN t2.hour_val ELSE t1.hour_val END AS hour_val 
  FROM
    table_name t1 LEFT JOIN table_name t2 ON t2.week_val = t1.week_val + 1