在数据库的一个表中,我有12列,即month_1 .... month_12。
如果@m = 1可以,请向我的SQL查询添加条件
CREATE PROCEDURE XemDiem_Top5Month1
@m INT
AS
BEGIN
SELECT *
FROM XemDiem
WHERE (month_1 IN (SELECT TOP (5) month_1
FROM XemDiem
GROUP BY month_1
ORDER BY month_1DESC))
END
如果@m = 2可以
CREATE PROCEDURE XemDiem_Top5Month1
@m INT
AS
BEGIN
SELECT *
FROM XemDiem
WHERE (month_2 IN (SELECT TOP (5) month_2
FROM XemDiem
GROUP BY month_2
ORDER BY month_2 DESC))
END
以此类推....
我不想写太多查询,所以请帮忙
答案 0 :(得分:0)
将选择查询分配给字符串并连接您的参数。最后执行字符串。
Create proc XemDiem_Top5Month1
@m int
AS
BEGIN
Delcare @query nvarchar(max)
set @query='SELECT *
FROM XemDiem
WHERE
(
month_''+Convert(varchar(10),@m)+'' IN
(
SELECT TOP (5) month_''+Convert(varchar(10),@m)+''
FROM XemDiem
GROUP BY month_''+Convert(varchar(10),@m)+''
ORDER BY month_''+Convert(varchar(10),@m)+'' DESC
)
)'
execute(@query)
答案 1 :(得分:0)
declare @ishistoric varchar(100) ='month_1'
(SELECT *
FROM XemDiem
WHERE
(
CASE @ishistoric
WHEN 'month_1' THEN month_1
WHEN 'month_2' THEN month_2
...
WHEN 'month_12' THEN month_12
END IN
(
SELECT TOP (5) CASE @ishistoric
WHEN 'month_1' THEN month_1
WHEN 'month_2' THEN month_2
...
WHEN 'month_12' THEN month_12
END
FROM OSUSR_KIA_PRINTSTICKER
GROUP BY CASE @ishistoric
WHEN 'month_1' THEN month_1
WHEN 'month_2' THEN month_2
...
WHEN 'month_12' THEN month_12
END
ORDER BY CASE @ishistoric
WHEN 'month_1' THEN month_1
WHEN 'month_2' THEN month_2
...
WHEN 'month_12' THEN month_12
END DESC
)
))
像这样进行剩余查询,查询基于所提供的列,并且它将返回传递给参数的特定列的相应记录。