在阅读了Stackoverflow很长一段时间之后,今天轮到我问了一个问题!
表格结构
它与SQL Server 2005数据库的查询有关。我有以下表结构:
部件
下载
进口
我想得到什么
我正在尝试获取每个组件的最新下载状态。
我到目前为止
我已经开始编写此查询,但我的联接工作效果不佳:
SELECT c.id
FROM components as c
JOIN (
SELECT componentid, MAX(downloaddate) as downloaddate, id
FROM downloads
GROUP BY componentid, id
) d ON d.componentid = c.id
-- JOIN on imports here...
我的问题是用于连接的查询不正确。因为我需要为连接选择id,所以我在group by子句中添加了它,现在我为每个组件获取多条记录,而不是最新的组件。
如果我自己在连接中执行查询,这就是我得到的。
componentid downloaddate id
8882 2011-01-15 06:00:09.773 595862
8882 2011-01-16 06:00:09.847 598422
8882 2011-01-17 06:00:09.940 600971
8951 2010-11-15 03:00:22.550 450221
8951 2010-11-16 03:00:21.730 452431
8951 2010-11-17 03:00:21.920 454668
8961 2011-01-17 02:00:33.077 600532
8961 2011-01-17 02:00:59.070 600536
8983 2008-07-17 11:59:53.780 122
9005 2009-09-01 04:00:38.320 48918
9005 2009-09-02 04:00:36.260 49280
相反,我需要这样的事情:
componentid downloaddate id
8882 2011-01-17 06:00:09.940 600971
8951 2010-11-17 03:00:21.920 454668
8961 2011-01-17 02:00:59.070 600536
8983 2008-07-17 11:59:53.780 122
9005 2009-09-02 04:00:36.260 49280
有谁知道如何编写我的联接以达到预期的结果?
提前多多感谢
答案 0 :(得分:3)
您无法关联JOIN运算符。请改用APPLY:
SELECT c.id , d.downloaddate
FROM components as c
APPLY (
SELECT componentid, MAX(downloaddate) as downloaddate
FROM downloads
WHERE componentid = c.id
) as d;
实际上你也可以使用JOIN(因为内部查询实际上没有关联),但是不按ID分组,只是按组件分组:
SELECT c.id , d.downloaddate
FROM components as c
JOIN (
SELECT componentid, MAX(downloaddate) as downloaddate
FROM downloads
GROUP BY componentid
) as d ON c.id = d.componentid;
更新:
SELECT *
FROM components as c
APPLY (
SELECT TOP(1) componentid, downloaddate, id as downloadid
FROM downloads
WHERE componentid = c.id
ORDER BY downloaddate DESC
) as d
JOIN imports i on i.id = d.downloadid;
答案 1 :(得分:3)
您可以使用ROW_NUMBER函数解决此问题:
SELECT componentid, ROW_NUMBER() OVER (PARTITION BY componentid ORDER BY downloaddate DESC) as rowno
FROM downloads
WHERE rowno = 1