SQL - 如何根据任何结果连接字符串?

发布于 2024-12-19 12:08:15 字数 336 浏览 2 评论 0原文

我正在尝试编写一个查询,该查询聚合许多行并返回单个字符串值来指示每列是否包含一个值。它需要检查每一列,如果该列包含“true”值,则连接字符串结果以表明这一点。

给定(在 SQL Server 2008 上):

      Col1 | Col2
Row1: 0      0
Row2: 0      1 

我需要一个结果,说明“Col1 没有 true,Col2 有 true”(逗号无关紧要)。

我的假设是,我需要将 CASEIF 语句与 ANY 运算符结合起来,但到目前为止,我还不清楚语法。

I'm trying to write a query which aggregates many rows and returns a single string value to indicate whether or not each column contains a value. It needs to examine each column and if the column contains a 'true' value, then concatenate the string result to indicate so.

Given (on SQL Server 2008):

      Col1 | Col2
Row1: 0      0
Row2: 0      1 

I need a result stating "Col1 has no true, Col2 has true" (the comma doesn't matter).

My assumption is that I need to combine a CASE or IF statement with an ANY operator, but so far the syntax escapes me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枕花眠 2024-12-26 12:08:15

以下查询将生成以下结果:对于您的数据,Col1 has no true, Col2 has true

SELECT CASE
          WHEN Col1Total = 0 THEN 'Col1 has no true'
          ELSE 'Col1 has true'
       END + ', ' +
   CASE
      WHEN Col2Total = 0 THEN 'Col2 has no true'
      ELSE 'col2 has true'
   END AS yourResult
FROM 
(
   SELECT SUM(Col1) AS Col1Total, SUM(Col2) AS Col2Total
   FROM yourTable
) AS t

The following query will produce these results: Col1 has no true, Col2 has true for your data:

SELECT CASE
          WHEN Col1Total = 0 THEN 'Col1 has no true'
          ELSE 'Col1 has true'
       END + ', ' +
   CASE
      WHEN Col2Total = 0 THEN 'Col2 has no true'
      ELSE 'col2 has true'
   END AS yourResult
FROM 
(
   SELECT SUM(Col1) AS Col1Total, SUM(Col2) AS Col2Total
   FROM yourTable
) AS t
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文