如何在子选择中简单地对多行进行硬编码?
我知道我可以做(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
在这种情况下,对于不存在的ID,它不包括0的总和。有没有办法包含未找到的ID?
我注意到PIVOT
用于SQL Server,但我不确定这是否会使它变得更简单/更简洁。
我想我只是在问有没有更好的方法?
答案 0 :(得分: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 ║
╚════╩═══════════╝
答案 1 :(得分:0)
只需声明一个临时表,用于存储您在“IN Clause”中使用的ID。
DECLARE @temp TABLE(ID INT identity(1,1), yourIDs INT)
INSERT INTO @temp VALUES
(10),(20),(300),(400)
正确加入临时表,以针对您想要的所有ID检索count_column的总和
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