简体   繁体   English

查询以基于另一列的值从单个列返回多个值

[英]Query To Return Multiple Values From A Single Column Based On Value Of Another Column

I have a table with an EntryDate and a ChecklistDay column. 我有一个带有EntryDate和ChecklistDay列的表。 They are Date and Integer columns. 它们是日期和整数列。 I want to return two columns, one named StartDate and another EndDate, both getting their values from the EntryDate column. 我想返回两列,一列名为StartDate,另一列为EndDate,两者均从EntryDate列获取其值。 StartDate would be returned from... StartDate将从...返回

SELECT EntryDate AS StartDate FROM TABLE WHERE ChecklistDay = 1

EndDate would be returned from... EndDate将从...返回

SELECT EntryDate AS EndDate FROM TABLE WHERE ChecklistDay = 10

Now I only want to return a row if a value is returned for both StartDate and EndDate, meaning that a ChecklistDay must have both values 1 and 10 in order for it to select the two EntryDates and return a row. 现在,我只想在StartDate和EndDate都返回值的情况下返回一行,这意味着ChecklistDay必须同时具有值​​1和10才能选择两个EntryDates并返回一行。 What kind of query do I use here? 我在这里使用哪种查询?

You can join to the same table twice. 您可以两次加入同一张表。

select startDt.EntryDate as StartDate,
       endDt.EntryDate as EndDate
from table startDt
inner join table endDt
on startDt.id = endDt.id
where startDt.ChecklistDay = 1
and endDt.CheckListDay = 10

Would this help: 这对您有帮助吗?

Select CASE ChecklistDay WHEN 1 THEN EntryDate ELSE NULL as StartDate,   
CASE CheckListDay WHEN 10 THEN DateAdd(day, ChecklistDay, StartDate) ELSE NULL END as EndDate   
from Table

This should run in any ANSI compatible DBMS (Oracle, MySql, Sql Server, Postgresql, Informix, DB2, etc) 它应该在任何ANSI兼容的DBMS中运行(Oracle,MySql,Sql Server,Postgresql,Informix,DB2等)

SELECT
   CASE ChecklistDay WHEN 1 THEN EntryDate ELSE NULL END as StartDate
 , CASE CheckListDay WHEN 10 THEN EntryDate ELSE NULL END as EndDate
FROM
   TABLE
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM