【问题标题】:Selecting multiple hard coded rows in with subselect使用子选择选择多个硬编码行
【发布时间】:2014-03-06 07:51:20
【问题描述】:

如何在子选择中简单地对多行进行硬编码?

我知道我可以做到 (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?

我注意到 SQL Server 的 PIVOT,但我不确定这是否使它更简单/不那么冗长。

我想我只是问有没有更好的方法?

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    只需声明一个临时表来存储您在“IN 子句”中使用的 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
    

    【讨论】:

      【解决方案2】:

      使用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
      

      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 ║
      ╚════╩═══════════╝
      

      【讨论】:

      • 我应该更清楚,那些只是 ID 不是一个范围。我将编辑问题。
      猜你喜欢
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 2017-08-27
      • 2021-07-25
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多