我在产品表
中有列,如下所示name varchar(100)
xdate datetime
如果我从产品表
中选择以下查询select name
, DateName( month , DateAdd( month , month(xdate) , 0 ) - 1 ) as xdate
from Products
选择查询结果,如下所示
名称(列) - xdate(列)
Computer May
Phone May
Mouse May
Grass April
Usb April
Glass February
问题:
如何显示结果如下
名称(列) - xdate(列)
Computer May
Phone
Mouse
Grass April
Usb
Glass February
我只想在选择查询中显示 xdate 以实现此目的。
任何帮助将不胜感激。
由于
答案 0 :(得分:2)
尝试此查询
select
name,
case when num = 1 then xdate else '' end as xdate
from
(
select
name,
DateName( month , DateAdd( month , month(xdate) , 0 ) - 1 ) as xdate ,
row_number() over (partition by YEAR(XDATE), MONTH(XDATE) order by xdate) as num,
xdate as real_date
from Products
) T
order by real_date
答案 1 :(得分:2)
您的数据是如何订购的?假设您有一个排序列(在下面的示例中为id),您可以在SQL Server 2012及更高版本上使用LAG函数:
DECLARE @Products TABLE
(id int, name varchar(100), xdate varchar(100))
INSERT INTO @Products (id, name, xdate)
VALUES
(1, 'Computer', 'May'),
(2, 'Phone', 'May'),
(3, 'Mouse', 'May'),
(4, 'Grass', 'April'),
(5, 'Usb', 'April'),
(6, 'Glass', 'February')
SELECT p.name,
CASE LAG(p.xdate, 1,0) OVER (ORDER BY p.id)
WHEN p.xdate THEN ''
ELSE p.xdate
END AS xdate
FROM @Products p
结果:
name xdate
Computer May
Phone
Mouse
Grass April
Usb
Glass February
答案 2 :(得分:2)
对于SQL 2012+,我认为George拥有最佳解决方案。
SELECT P.id,
name,
ISNULL(CA.xdate,'') AS xDate
FROM Products p
OUTER APPLY(
SELECT DateName( month , DateAdd( month , month(xdate) , 0 ) - 1 )
FROM Products
GROUP BY xdate
HAVING MIN(ID) = p.id
) CA(xdate)
ORDER BY ID
SELECT id,
name,
CASE WHEN ROW_NUMBER() OVER (PARTITION BY CA.xDate ORDER BY ID) = 1
THEN CA.xdate
ELSE ''
END AS xdate
FROM Products
CROSS APPLY(SELECT DateName( month , DateAdd( month , month(xdate) , 0 ) - 1 )) CA(xdate)
ORDER BY ID
答案 3 :(得分:1)
低技术(不太优雅)的解决方案(适用于SQL Server 2000):
select t.name, case when t.name = minSQ.minName then minSQ.mnth else '' end
from Products t
join (select MIN(name) minName, DATENAME(month,xdate) mnth from Products group by DATENAME(month,xdate)) minSQ on DateName(month, t.xdate) = minSQ.mnth
order by t.xdate