我有一个看起来像这样的表:
DECLARE @myTable TABLE (SampleID varchar(max), site varchar(max), SPDate date)
INSERT @myTable
SELECT 'A-1', 1, '9/1/2012' UNION ALL
SELECT 'A-2', 1, '10/1/2012' UNION ALL
SELECT 'A-3', 1, '10/15/2012' UNION ALL
SELECT 'A-5', 1, '5/1/2012' UNION ALL
SELECT 'A-4', 1, '1/1/2012' UNION ALL
SELECT 'B-1', 2, '11/1/2012' UNION ALL
SELECT 'B-2', 2, '8/1/2012' UNION ALL
SELECT 'B-3', 2, '5/1/2012' UNION ALL
SELECT 'B-4', 2, '4/1/2012' UNION ALL
SELECT 'C-1', 3, '10/1/2012' UNION ALL
SELECT 'C-2', 3, '10/15/2012' UNION ALL
SELECT 'C-3', 3, '7/1/2012' ;
我想要的是一个查询,它为我提供了所有日期>从今天起75天,然后按降序排序(例如,最近的日期首先)。
所以对于我的表,输出看起来像这样:
Site1 Site2 Site3
A-1 B-2 C-2
A-5 B-3 C-3
A-4 B-4
所以我知道如何将Site1,Site2和Site3查询分开,就像这样
SELECT SampleID FROM @myTable
WHERE DATEDIFF(DAY, SPDate, GETDATE()) > 75 AND
site=1 ORDER BY SPDate DESC
如何将这三个查询放入一个表中?
谢谢!
答案 0 :(得分:1)
您可以使用PIVOT
功能轻松执行此操作。如果您上面只显示了3个site
值,则可以对值进行硬编码,类似于:
select [Site1], [Site2], [Site3]
from
(
select SampleID,
'Site'+ cast(site as varchar(10)) SiteNumber
,row_number() over(partition by site order by spdate desc) rn
from myTable
where DateDiff(day, spdate, getdate()) >75
) src
pivot
(
max(SampleID)
for SiteNumber in ([Site1], [Site2], [Site3])
) piv;
但是你有不明数量的网站,那么你可以实现这个动态的sql版本:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Site'+ site)
from myTable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select SampleID,
''Site''+ cast(site as varchar(10)) SiteNumber
,row_number() over(partition by site order by spdate desc) rn
from myTable
where DateDiff(day, spdate, getdate()) >75
) x
pivot
(
max(SampleID)
for SiteNumber in (' + @cols + ')
) p '
execute(@query)
两者都产生相同的结果:
| SITE1 | SITE2 | SITE3 |
--------------------------
| A-1 | B-2 | C-3 |
| A-5 | B-3 | (null) |
| A-4 | B-4 | (null) |