在一个选择查询中组合两行

时间:2014-06-17 07:27:00

标签: sql sql-server

您好我很难在单个查询中组合两个记录(来自单个表)。我们的想法是,DATE_FIELD列是日期类型,ColA是整数数据类型。

为了进一步说明我的询问,我附上了一张图片

enter image description here

1。)是原始表。 2.)是否是所需的输出。

P.S。 DATE_FIELD的过滤器不是简单的" WHERE DATE_FIELD IN"条款。

例如,我想获得DATE_FIELD = 12/30/2013。然后我需要通过使用我从网上获得的这个查询以编程方式获得上一个9月DATE_FIELD,这是2013年9月30日:

CASE 
            WHEN MONTH(DATE_FIELD) < 10 
            THEN 
            (cast(CAST((DATE_FIELD)  - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
            ELSE 
            ( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END

这是我当前的sql脚本(无法获得上一个Sept过滤器的ColA等价物:

SELECT DATE_FIELD, ColA, 
CASE 
WHEN MONTH(DATE_FIELD) < 10 
 THEN 
 (cast(CAST((YEAR(DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
 ELSE 
 ( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END AS PREVIOUS, 
(
 SELECT ColA 
 FROM TABLE_A
 WHERE DATE_FIELD = 
 CASE 
  WHEN MONTH(DATE_FIELD) < 10 
  THEN 
  (cast(CAST((YEAR(DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
  ELSE 
  ( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
  END
) AS PYE_colA
FROM TABLE_A
WHERE DATE_FIELD = '12/30/2013'

谢谢!

1 个答案:

答案 0 :(得分:1)

使用同一个表进行交叉连接,并仅在where子句中使用CASE结构:

SELECT a.DATE_FIELD AS DATE_FIELD_1,
    a.ColA AS ColA_1,
    b.DATE_FIELD AS DATE_FIELD_2,
    b.ColA AS ColA_2
FROM TABLE_A a 
CROSS JOIN TABLE_A b
WHERE DATE_FIELD_1 = 'your date'
AND DATE_FIELD_2 = (
    CASE 
    WHEN MONTH(DATE_FIELD_1) < 10 
    THEN 
        (cast(CAST((YEAR(DATE_FIELD_1) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
    ELSE 
        ( cast(CAST((YEAR(DATE_FIELD_1)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
    END)
;

另一种基于Thorsten Kettners评论的可能性:

SELECT a.DATE_FIELD AS DATE_FIELD_1,
    a.ColA AS ColA_1,
    b.DATE_FIELD AS DATE_FIELD_2,
    b.ColA AS ColA_2
FROM TABLE_A a 
INNER JOIN TABLE_A b
ON b.DATE_FIELD = (
    CASE 
    WHEN MONTH(a.DATE_FIELD) < 10 
    THEN 
        (cast(CAST((YEAR(a.DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
    ELSE 
        ( cast(CAST((YEAR(a.DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
    END)
WHERE a.DATE_FIELD = 'your date'
;