SQL concat并使用第一个日期进行转换

时间:2018-09-20 16:31:15

标签: sql

非常感谢您的事先帮助,在SQL下,我有一个包含4列的表: 一个月的价值数据 1个 2 3 4 5 6 7 8 9 10 11 12

b-year with data of(2012-2013-2014-2018)

c-客户编号,其数据类似于(1545112)

d-黑色列出金额值(1000-2000-3000)

我需要一个查询,以仅显示客户端在表格中出现的(mm-yyyy)格式的第一个日期。 例如,此处附有表格数据的图像 。 BR

enter image description here

1 个答案:

答案 0 :(得分:0)

对不起,如果我误解了您的要求。

如果您尝试仅显示客户端ID和它们以所需格式显示的第一个日期:

SELECT
    IDS,
    FORMAT(MIN(CONVERT(DATE, CONVERT(CHAR(4), [Year]) + '-'
        + CONVERT(VARCHAR(10), [Month]) + '-1')), 'MM-yyyy') AS FirstDate
FROM TableName
GROUP BY IDS

如果您需要访问其他列(如黑名单中的金额),则可以使用窗口功能轻松找到:

SELECT IDS, FirstDate, Blacklisted
FROM (
    SELECT
        IDS,
        RIGHT('00' + CONVERT(VARCHAR(10), [Month]), 2) + '-' + CONVERT(CHAR(4), [Year]) AS FirstDate,
        Blacklisted,
        ROW_NUMBER() OVER (PARTITION BY IDS ORDER BY [Year], [Month]) AS RowId
    FROM @Data
    ) T
WHERE RowId = 1

以下是尝试模拟测试数据的完整脚本:

DECLARE @Data TABLE (
    MONTH INT, YEAR INT, IDS INT, BLACKLISTED INT
)
INSERT @Data 
    SELECT 1, 2016, 11364948, 1
    UNION ALL SELECT 1, 2016, 11364948, 1
    UNION ALL SELECT 2, 2016, 11364948, 1
    UNION ALL SELECT 3, 2016, 11364948, 1
    UNION ALL SELECT 5, 2016, 11364948, 1
    UNION ALL SELECT 6, 2016, 11364948, 1
    UNION ALL SELECT 7, 2016, 11364948, 2
    UNION ALL SELECT 8, 2015, 11364948, 1
    UNION ALL SELECT 8, 2016, 11364948, 2
    UNION ALL SELECT 9, 2015, 11364948, 1
    UNION ALL SELECT 10, 2015, 11364948, 1
    UNION ALL SELECT 11, 2015, 11364948, 1
    UNION ALL SELECT 12, 2015, 11364948, 1

SELECT
    IDS,
    FORMAT(MIN(CONVERT(DATE, CONVERT(CHAR(4), [Year]) + '-'
        + CONVERT(VARCHAR(10), [Month]) + '-1')), 'MM-yyyy') AS FirstDate
FROM @Data
GROUP BY IDS

SELECT IDS, FirstDate, Blacklisted
FROM (
    SELECT
        IDS,
        RIGHT('00' + CONVERT(VARCHAR(10), [Month]), 2) + '-' + CONVERT(CHAR(4), [Year]) AS FirstDate,
        Blacklisted,
        ROW_NUMBER() OVER (PARTITION BY IDS ORDER BY [Year], [Month]) AS RowId
    FROM @Data
    ) T
WHERE RowId = 1