表格中有21行。 2011年有7个,2012年有7个,2013年有7个。我想获得最近一年的7行。
SELECT S1, S2, S1 * S2 AS M
FROM BLGND
WHERE DID = @dID AND
PMID = @pmID AND
yearr IN (SELECT MAX(yearr) AS y FROM BLGND AS BLGND_1)
我在MS Visual Studio环境中使用上面的查询成功地带来了最新年份的行。但是,当我在ASP.NET页面中运行查询时,它会带来所有21条记录。
换句话说,yearr IN (SELECT MAX(yearr) AS y FROM BLGND AS BLGND_1)
没有任何区别。
yearr
列的类型为int
可能是什么问题?或者你知道更好的查询吗?
答案 0 :(得分:0)
你可以简单地写
SELECT S1, S2, S1 * S2 AS M
FROM BLGND
WHERE DID = @dID AND
PMID = @pmID AND
YEAR([fieldWithDate]) = @yearRequested
假设fieldWithDate
是smalldatetime
或datetime
字段,您希望从中获取年份值,@ yearRequested是您从代码传递给查询的参数。
您可以使用YEAR(expression) T-SQL函数
当然,如果搜索年份值的字段只是包含行年份值的整数,则查询更简单
SELECT S1, S2, S1 * S2 AS M
FROM BLGND
WHERE DID = @dID AND
PMID = @pmID AND
fieldWithYearValue = @yearRequested
如果您不想传递年份的参数,但只想检索特定用户的去年的行集,那么
SELECT S1, S2, S1 * S2 AS M
FROM BLGND
WHERE DID = @dID AND
PMID = @pmID AND
fieldWithYearValue = (SELECT MAX(fieldWithYearValue) FROM BLGND)