日期列中的SQL Extra数据

时间:2016-06-13 18:55:21

标签: sql sql-server join union

我的查询内容如下

Site_name  LOB date
Site 1    Sales 6/1
Site 1    Sales 6/2
...       ....  ..
Site 2    Sales 6/1
Site 2    Sales 6/2
...       ....  ..
Site 3    Consumer 6/1
Site 3    Consumer 6/1

在数据中我希望所有日期MTD和日期列中的额外两行。我希望这包含'MTD'和'Target',所以我的结果表看起来像这样

 Site_name  LOB date
    Site 1    Sales 6/1
    Site 1    Sales 6/2
    ...       ....  ..
    Site 1    Sales Target
    Site 1    Sales MTY

    Site 2    Sales 6/1
    Site 2    Sales 6/2
    ...       ....  ..
    Site 2    Sales Target
    Site 2    Sales MTY

    Site 3    Consumer 6/1
    Site 3    Consumer 6/1
    ...       ....     ...
    Site 3    Consumer Target
    Site 3    Consumer MTD

我对现有资料的基本查询是,我在这里找不到真正重要的地方。

   Select Distinct 
    Site_name, LOB, Day_date 
   where month(day_date)>=month(getdate()-5)
   and year(day_date)=year(getdate())

1 个答案:

答案 0 :(得分:0)

不确定你是否想要这个,但它可能会给你一个想法。
至少,它会按照您的要求生成结果:

;WITH tData(Site,LOB) as (SELECT 'Site 1','Sales' UNION ALL SELECT 'Site 2','Sales' UNION ALL SELECT 'Site 3','Consumer' ),
tDate(sDate) as (SELECT CAST('2016-06-01' as Date) UNION ALL SELECT '2016-06-02'),
DateCol(sDate,sOrder) as (SELECT CAST(sDate as VARCHAR), 0 FROM tDate UNION ALL SELECT 'Target', 1 UNION ALL SELECT 'MTD', 2)
SELECT tData.*, sDate as [Date]
FROM tData, DateCol
ORDER BY Site, sOrder, sDate

Site    LOB         Date
Site 1  Sales       2016-06-01
Site 1  Sales       2016-06-02
Site 1  Sales       Target
Site 1  Sales       MTD
Site 2  Sales       2016-06-01
Site 2  Sales       2016-06-02
Site 2  Sales       Target
Site 2  Sales       MTD
Site 3  Consumer    2016-06-01
Site 3  Consumer    2016-06-02
Site 3  Consumer    Target
Site 3  Consumer    MTD