2014-02-08 57 views
0

如何在子選擇中簡單地對多行進行硬編碼?使用子選擇選擇多個硬編碼行

我知道我能做到(How to select several hardcoded SQL rows?):

SELECT x.id, SUM(ISNULL(OtherTable.count_column,0)) 
FROM (SELECT 12 AS id 
    UNION 
SELECT 21 AS id 
    UNION 
SELECT 101 AS id 
/*AND so on */ 
) AS x 
LEFT JOIN OtherTable ON x.id = OtherTable.id 
Group BY x.id 

有沒有少尷尬和詳細的方式做到這一點?

我所真正需要的是:

SELECT id, SUM(ISNULL(count_column,0)) FROM OtherTable 
WHERE id IN (12, 21, 101,/*And So On*/) 
GROUP BY id 

在這種情況下,它不包括0的總和不存在的ID。有沒有一種方法可以包含沒有找到的ID?

我注意到SQL Server的PIVOT,但我不確定這是否使它更簡單/不太詳細。

我想我只是問有沒有更好的方法?

回答

0

請嘗試使用master..spt_values表。

SELECT x.id, SUM(ISNULL(OtherTable.count_column,0)) 
FROM 
(
SELECT DISTINCT number AS id 
FROM master..spt_values 
WHERE number >= 1 and number <= 10 
) AS x 
LEFT JOIN OtherTable ON x.id = OtherTable.id 
Group BY x.id 

OR

SELECT id, SUM(ISNULL(count_column,0)) 
FROM OtherTable 
WHERE id IN (
       SELECT DISTINCT number AS id 
       FROM master..spt_values 
       WHERE number >= 1 and number <= 10 
      ) 
GROUP BY id 

測試數據

DECLARE @OtherTable TABLE(ID INT, count_column INT) 
INSERT INTO @OtherTable VALUES 
(1, 10), (2,20),(3,30),(4,NULL),(5,50) 

查詢

SELECT x.id, SUM(ISNULL(t.count_column,0)) Total_Sum 
FROM 
(
SELECT DISTINCT number AS id 
FROM master..spt_values 
WHERE number >= 1 and number <= 7 
) AS x 
LEFT JOIN @OtherTable t ON x.id = t.id 
Group BY x.id 

結果集

╔════╦═══════════╗ 
║ id ║ Total_Sum ║ 
╠════╬═══════════╣ 
║ 1 ║  10 ║ 
║ 2 ║  20 ║ 
║ 3 ║  30 ║ 
║ 4 ║   0 ║ 
║ 5 ║  50 ║ 
║ 6 ║   0 ║ 
║ 7 ║   0 ║ 
╚════╩═══════════╝ 
+0

我本來應該更清楚,這些只是ID不是一個範圍。我將編輯問題。 – rileymat

0

剛宣佈其存儲你的IDSü中使用的「IN子句」臨時表。

DECLARE @temp TABLE(ID INT identity(1,1), yourIDs INT) 
INSERT INTO @temp VALUES 
(10),(20),(300),(400) 

做對加盟臨時表檢索count_column的總和與所有的ID,你想

select t.yourIDs, Sum(isnull(ot.count_column,0)) 
    from OtherTable ot 
    right JOIN @temp t on t.yourIDs=ot.id 
    group by t.yourIDs