1

表结构如下。第一个表是 subusage,下一个是 machinesubusage。两者都与 sub_usage_id 列相关联。我需要选择 subusage.product_key 及其相关的使用计数,如果 subusage.is_standalone 不为空,那么我需要从 subusage.usage_count 获取相关的使用计数,否则相关的使用计数将是该 sub_usage_id 的 machinesubusage 表中的行数。我已经针对以下两种情况编写了查询。我尝试使用 case 和 if 语句来组合这两个查询,但徒劳无功

SELECT SU.product_key,COUNT(*) FROM SubUsage SU
INNER JOIN MachineSubUsage MSU ON MSU.sub_usage_id = SU.sub_usage_id
WHERE SU.acct_id = 40897342 GROUP BY SU.product_key

SELECT SU.product_key, SU.usage_count FROM SubUsage SU
INNER JOIN MachineSubUsage MSU ON MSU.sub_usage_id = SU.sub_usage_id
WHERE SU.acct_id = 40897342 GROUP BY SU.product_key, SU.usage_count

表结构:

在此处输入图像描述

4

3 回答 3

1

试试这个:

SELECT 
  SU.product_key,
  SUM(CASE 
        WHEN su.is_standalone IS NOT NULL THEN su.usage_count
        ELSE MSU.SubUsageCount
      END) AS TotalCount
FROM SubUsage SU
INNER JOIN
(
   SELECT sub_usage_id, COUNT(*) AS SubUsageCount
   FROM  MachineSubUsage
   GROUP BY sub_usage_id
) AS MSU ON MSU.sub_usage_id = SU.sub_usage_id
WHERE SU.acct_id = 40897342 
GROUP BY SU.product_key;

如果您需要在另一个表中包含那些不匹配的产品密钥,请使用LEFT JOINwithISNULL()将 null 替换为零:

SELECT 
  SU.product_key,
  SUM(CASE 
        WHEN su.is_standalone IS NOT NULL THEN su.usage_count
        ELSE ISNULL(MSU.SubUsageCount, 0)
      END) AS TotalCount
FROM SubUsage SU
LEFT JOIN
(
   SELECT sub_usage_id, COUNT(*) AS SubUsageCount
   FROM  MachineSubUsage
   GROUP BY sub_usage_id
) AS MSU ON MSU.sub_usage_id = SU.sub_usage_id
WHERE SU.acct_id = 40897342 
GROUP BY SU.product_key;
于 2013-02-18T12:54:19.007 回答
0

在 SQLServer2005+ 中尝试这个请求

SELECT DISTINCT SU.product_key, SU.usage_count, 
       COUNT(*) OVER(PARTITION BY SU.product_key) 
FROM SubUsage SU JOIN MachineSubUsage MSU ON MSU.sub_usage_id = SU.sub_usage_id
WHERE SU.acct_id = 40897342
于 2013-02-18T13:35:52.123 回答
0

Mahmoud Gamal 发布了似乎是一个很好的答案。我将在阿米特的评论中解释原始案例陈述出了什么问题。这里是:

SELECT SU.product_key
, CASE WHEN SU.is_standalone IS NOT NULL THEN SU.usage_count ELSE COUNT(*) END 
FROM SubUsage SU INNER JOIN MachineSubUsage MSU ON MSU.sub_usage_id = SU.sub_usage_id 
WHERE SU.acct_id = 40897342 
GROUP BY SU.product_key, SU.usage_count 

应该在错误消息中显示的问题是 SU.is_standalone 包含在 select 子句中,但不包含在 group by 子句中。事实上,如果你做这个简单的更正,你可能会得到你想要的答案。

于 2013-02-18T14:10:31.323 回答