如何根据列来编写查询

时间:2013-11-25 11:27:22

标签: mysql

我有一个名为TableA的表,如下所示;

+----+---------------+--------------+--------------+
| Id |  Frequency    | Inserted_Date| Eligibility  |
+----+---------------+--------------+--------------+
|  1 | Halfyearly    |   23/8/2013  |              |
|  2 | Quaterly      |   24/11/2013 |              |
+----+---------------+--------------+--------------+

此处Eligibility列最初为空。我需要根据当月的频率编写一个查询,其中Eligibility设置为yes / no。

获得第1记录, 截至今日资格=否

获得第2记录, 截至今日资格=是

+----+---------------+--------------+--------------+
| Id |  Frequency    |Inserted_Date | Eligibility|
+----+---------------+--------------+--------------+
|  1 | Halfyearly    |   23/8/2013  |   No         |
|  2 | Quaterly      |   24/11/2013 |   Yes        |
+----+---------------+--------------+--------------+

我不知道如何编写查询来获取上述输出以及更多信息我需要每个月更改一次。

请帮帮我。

提前感谢大家的回复。

5 个答案:

答案 0 :(得分:1)

UPDATE TableA 
SET ELIGIBILITY = CASE WHEN DATEPART(MM,GETDATE()) = DATEPART(MM,DATE)
                  THEN 'YES'
                  ELSE 'NO' END

答案 1 :(得分:1)

我理解它的方式,如果是Inserted_Date = Jan 2013Frequency = 'Halfyearly',那么Eligibility = 1当前月份是Jan 2013, Jul 2013, Jan 2014, Jul 2014 etc..

UPDATE TableA
SET Eligibility = CASE WHEN (Frequency = 'Halfyearly' 
                            AND MONTH(Inserted_Date) % 6 = MONTH(NOW()) % 6) 
                         OR (Frequency = 'Quarterly' 
                            AND MONTH(Inserted_Date) % 3 = MONTH(NOW()) % 3)
                      THEN 'Yes'
                      ELSE 'No' 
                 END

如果你也有年度,你可以检查

MONTH(Inserted_Date) = MONTH(NOW())

SQLFiddle

上查看此内容

答案 2 :(得分:0)

使用CASE..WHEN

UPDATE tbl
SET Eligibility = 'Your value' Frequency WHEN 'Half Yearly' THEN 'No'
                                WHEN 'Quarterly' THEN 'Yes'

答案 3 :(得分:0)

“基于Inserted_Date,我需要设置Eligibility的值。”

然后使用

UPDATE tbl
SET Eligibility = CASE WHEN InsertedDate='' THEN 'No'
                            WHEN '' THEN 'Yes'

答案 4 :(得分:0)

您可以使用以下查询获得所需的输出:

SELECT ID,
       Frequency,
       Date,
       (CASE
           WHEN TO_CHAR (SYSDATE, 'mm') = TO_CHAR (Date, 'mm')
           THEN
              YEligibilility
           ELSE
              NEligibilility
        END)
          AS Eligibilility
  FROM (SELECT ID,
               Frequency,
               Date,
               'Yes' AS YEligibilility,
               'No' AS NEligibilility
               From TableA);