【问题标题】:Create a new column from Select statement then combining it with another Select statement in one procedure to return one data table从 Select 语句创建一个新列,然后在一个过程中将其与另一个 Select 语句组合以返回一个数据表
【发布时间】:2021-12-06 16:45:45
【问题描述】:

我想对 SQL 表 Archive_Hits 中的数据进行计数,并创建一个列 programStarts 来显示该数据。然后我想把programStarts列和另一个Select语句结合起来显示一个数据表。

这是我的程序:

ALTER PROCEDURE [dbo].[testing2] @startdate datetime, @enddate datetime
AS
BEGIN

SELECT Archive_Hits.inst_id, Count(Archive_Hits.type) AS programStarts 
FROM Archive_Hits 
WHERE Archive_Hits.type<>'New' AND Archive_Hits.accessed_on BETWEEN  cast ( @startdate as date)  and cast ( @enddate as date)
GROUP BY Archive_Hits.inst_id


SELECT email,product_market,install_code, programStarts
FROM (Archive_ProgUsers INNER JOIN Archive_Installations ON Archive_ProgUsers.id = Archive_Installations.user_id) 
INNER JOIN Archive_Hits AS hitsCount ON hitsCount.inst_id = Archive_Installations.id
ORDER BY programStarts DESC

请注意,我尝试使用 UNION 和 UNION ALL 方法,但如果我在每个语句中没有相同数量的列,这将不起作用。

另外,第二个 select 语句返回错误,因为它无法识别第一个 Select 语句中新创建的列。

=============================== 这是一个示例结果表结果

【问题讨论】:

  • 您可以在列数较少的 SELECT 中添加“NULL”,以获得相同的数字。
  • 但是第二个 SELECT 当然不知道第一个 SELECT 的 programStarts 列。
  • 使第二个查询成为一个子查询,以表达式/列的形式返回一个值。因此,代替连接,只需为该表达式选择一个值。为什么不左连接到第二个表?
  • 提供样本数据和所需的输出
  • @eshirvana 刚刚用示例数据更新了我的帖子。

标签: sql asp.net sql-server stored-procedures


【解决方案1】:

您需要提供示例数据,但我认为这是您需要的:

SELECT
    email,
    product_market,
    install_code,
    Count(case when hitsCount.type <> 'New' and hitsCount.accessed_on BETWEEN cast(@startdate as date) and cast(@enddate as date) then 1 end) over (partition by inst_id) as programStarts
FROM Archive_ProgUsers
INNER JOIN Archive_Installations ON Archive_ProgUsers.id = Archive_Installations.user_id
INNER JOIN Archive_Hits AS hitsCount ON hitsCount.inst_id = Archive_Installations.id
ORDER BY programStarts DESC

好的,那么你需要这个:

SELECT
    email,
    product_market,
    install_code,
    programStarts
FROM Archive_ProgUsers
INNER JOIN Archive_Installations ON Archive_ProgUsers.id = Archive_Installations.user_id
INNER JOIN (
    SELECT inst_id 
        , Count(case when hitsCount.type <> 'New' and hitsCount.accessed_on BETWEEN cast(@startdate as date) and cast(@enddate as date) then 1 end) as programStarts
    From Archive_Hits
    GROUP BY Archive_Hits.inst_id 
) AS hitsCount ON hitsCount.inst_id = Archive_Installations.id
ORDER BY programStarts DESC

【讨论】:

  • 您的答案有效,看起来它为我提供了 programStarts 的准确数字。但是,它也不断为同一个用户重复相同的行。
  • @codernon hmmm... 然后是第二个解决方案
  • 第二个查询成功了!!你是最棒的!!!谢谢!
  • @codernon 不客气
猜你喜欢
  • 1970-01-01
  • 2011-02-16
  • 2021-01-05
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
相关资源
最近更新 更多