简体   繁体   中英

CONCAT columns without sub-query SQL Server

I was looking to see if there was a better approach to this query

The date field is formatted - 06-03-2018

I need a column that looks like eg Mar-18 eg

SELECT
CONCAT(P.[Month] + '-', p.[Year]) AS [Month-Year]
FROM
(
SELECT 
left(datename(MONTH,[Date]),3) AS [Month]
,right(YEAR([Date]),2) AS [Year]
FROM
Table1
)P

This gives me the result i want but i was wondering if there was anyway to get the same result without a sub-query. Thanks

为什么不将日期格式设置为

select format(convert(date, '06-03-2018', 103), 'MMM-yy')

The query you've provided isn't valid, you need a comma ( , ) between column declarations (which you're missing.

Anyway, the query can be simplified to:

SELECT LEFT(DATENAME(MONTH,[Date]),3) + '-' + RIGHT(YEAR([Date]),2) AS [Month-Year]
FROM Table1;

I haven't used CONCAT here, as there is no need (as either both values will be NULL or have a value).

You Can Do the concatenation directly

SELECT 
    CAST(LEFT(datename(MONTH, [Date]), 3) AS VARCHAR(20))
    +'-'+
    CAST(RIGHT(YEAR([Date]), 2) AS VARCHAR(20))
    FROM Table1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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