同一 select 语句中的聚合查询

发布于 2025-01-03 22:26:55 字数 300 浏览 0 评论 0原文

我有一个 select 语句,它返回 5 列(并且需要 1-2 分钟) 其中的一列是颜色(即只有红、蓝和黄三种颜色)。现在我想显示同一 select 语句中具有红色的行数、具有蓝色的行数和具有黄色的行数。

Select 语句是这样的

在此处输入图像描述

我想要这样的输出

在此处输入图像描述

有帮助吗?

I have a select statement which is returning me 5 columns (and it is taking 1-2 minutes)
one column in this is color (i.e. only three colors Red, Blue and Yellow). Now I want to show the count of the number of rows having Red, Number of rows having Blue and No. of rows having yellow in the same select statement.

Select statement is this

enter image description here

and I want output like this

enter image description here

Any help ?

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

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

发布评论

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

评论(2

戈亓 2025-01-10 22:26:55

您想要这个(对于 SQL Server 2005+):

SELECT  *, SUM(CASE WHEN Color = 'RED' THEN 1 ELSE 0 END) OVER() [RED],
        SUM(CASE WHEN Color = 'BLUE' THEN 1 ELSE 0 END) OVER() [BLUE],
        SUM(CASE WHEN Color = 'Yellow' THEN 1 ELSE 0 END) OVER() [Yellow]
FROM YourTable

You want this (For SQL Server 2005+):

SELECT  *, SUM(CASE WHEN Color = 'RED' THEN 1 ELSE 0 END) OVER() [RED],
        SUM(CASE WHEN Color = 'BLUE' THEN 1 ELSE 0 END) OVER() [BLUE],
        SUM(CASE WHEN Color = 'Yellow' THEN 1 ELSE 0 END) OVER() [Yellow]
FROM YourTable
长途伴 2025-01-10 22:26:55

使用 CTE(通用表表达式):

; 
WITH cte AS
( SELECT ...
  ... your query here
) 
WITH grp AS
( SELECT 
        color
      , COUNT(*) AS cnt
  FROM
        cte
  GROUP BY
        color
) 
SELECT 
      cte.*
    , (SELECT cnt FROM grp WHERE color = 'Red')    AS Red
    , (SELECT cnt FROM grp WHERE color = 'Blue')   AS Blue
    , (SELECT cnt FROM grp WHERE color = 'Yellow') AS Yellow
FROM 
      cte

Using CTEs (Common Table Expressions):

; 
WITH cte AS
( SELECT ...
  ... your query here
) 
WITH grp AS
( SELECT 
        color
      , COUNT(*) AS cnt
  FROM
        cte
  GROUP BY
        color
) 
SELECT 
      cte.*
    , (SELECT cnt FROM grp WHERE color = 'Red')    AS Red
    , (SELECT cnt FROM grp WHERE color = 'Blue')   AS Blue
    , (SELECT cnt FROM grp WHERE color = 'Yellow') AS Yellow
FROM 
      cte
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文