SQL选择where子句后

时间:2013-07-26 15:46:16

标签: sql-server select join

以下是设置:

Table 1: table_1
column_id
column_12
column_13
column_14

Table 2: table_2
column_id
column_21
column_22

选择声明:

DECLARE @Variable 
INT SET @Variable = 300

SELECT b.column_id, 
        b.column_12, 
        SUM(b.column_13) OVER (PARTITION BY b.column_id ORDER BY b.column_12) AS sum_column_13, 
        @Variable / nullif(SUM(b.column_13) OVER (PARTITION BY b.column_id ORDER BY b.column_12),0) AS divide_var, 
        (b.column_13*100) / nullif(b.column_14,0) AS divide_column_3 
FROM dbo.table_1 b 
WHERE b.column_12 IN ('AM','AJ','A-M','A-J','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q');

这很有效,所有公式都有效,并显示正确的结果 检索到b.column_id 检索到b.column_12 sum_column_13等于所有column_13值的总和(按column_id分区)
divide_var等于sum_column_13的潜水变量 divide_column_13等于column_13除以column_14

现在我正在尝试从@Variable检索table_2,而不是静态。

两个表都有column_id,可以将它们链接在一起。但是这个值并不是唯一的 @Variable的实际数字应来自table_2;通过对每个column_id的column_21的所有值求和。(类似于sum_column_13的东西)

我可以让两件事分开工作,但当我尝试将它们组合在一起时(使用JOIN或额外的SELECT类),一切都会变得疯狂。例如,在使用JOIN语句时,WHERE类仅适用于JOIN语句,而不适用于SELECT语句。我想象的应该是使用当前column_id的{​​{1}}结果,然后使用此结果从SELECT中检索所需的数据。

我理解我的解释不是很清楚。所以here is an SQLFiddle。 正如您所看到的,现在变量来自table_2中的两个值。 希望这会有所帮助。

谢谢,

1 个答案:

答案 0 :(得分:0)

以下是示例代码,我没有使用变量而是直接使用了列的总和,我也使用了CTE:

with tbl_2(col_id, col_sum) as
( select col_id, sum(column_21) col_sum from tbl_2 group by col_id)
SELECT b.column_id, 
        b.column_12, 
        SUM(b.column_13) OVER (PARTITION BY b.column_id ORDER BY b.column_12) AS sum_column_13, 
        col_sum / nullif(SUM(b.column_13) OVER (PARTITION BY b.column_id ORDER BY b.column_12),0) AS divide_var, 
        (b.column_13*100) / nullif(b.column_14,0) AS divide_column_3 
FROM dbo.table_1 b 
join tbl_2 on b.col_id=tbl_2.col_id
WHERE b.column_12 IN ('AM','AJ','A-M','A-J','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q');