单个SQL查询中的多个计数

时间:2017-02-01 06:41:43

标签: sql sql-server

我有三个不同的查询:

  @media screen and (max-device-width: 1024px) and (orientation: portrait)
        {#cast1, #cast2, #cast3, #cast4, #cast5, #cast6, #cast7 
          {
            height: 26%;left: 5%;
          }
       } 

  @media screen and (max-width: 1024px)
       {#cast1, #cast2, #cast3, #cast4, #cast5, #cast6, #cast7 
          {
            height: 45%;left: 5%;
          }
       }

我想在一个查询中看到他们的计数。我怎样才能做到这一点?感谢。

5 个答案:

答案 0 :(得分:3)

使用子查询!学习SQL https://blog.sqlauthority.com/

的一些基础知识
SELECT 
(SELECT COUNT(*)
  FROM [myDb].[dbo].[Properties] WHERE Bathtub is  null) AS BathTub,

(SELECT COUNT(*)
  FROM [myDb].[dbo].[Properties] WHERE Bathroom is  null) AS Bathroom,

(SELECT COUNT(*)
  FROM [myDb].[dbo].[Properties] WHERE Toilet is  null) AS Toilet

警告如果您担心性能,则涉及案件的开销

答案 1 :(得分:1)

试试这个(这是oracle,我想在mysql中没有什么不同):

SELECT 
COUNT(CASE WHEN Bathtub IS NULL THEN 1 END) Bathtub, 
COUNT(CASE WHEN Bathroom IS NULL THEN 1 END) Bathroom,
COUNT(CASE WHEN Toilet IS NULL THEN 1 END) Toilet 
from [myDb].[dbo].[Properties];

答案 2 :(得分:1)

或者像这样写:

SELECT total-BT cnt_bt, total-BR cnt_br, total-TL cnt_tl FROM (
  SELECT COUNT(*) total, COUNT(Bathtub) BT, COUNT(Bathroom) BR, COUNT(Toilet) TL
  FROM [myDb].[dbo].[Properties]
) subq

答案 3 :(得分:1)

尝试使用自定义说明进行联合

SELECT COUNT(*), 'Bathtub is null counts' desc
  FROM [myDb].[dbo].[Properties] WHERE Bathtub is  null
union
SELECT COUNT(*),'Bathroom is null counts' desc
  FROM [myDb].[dbo].[Properties] WHERE Bathroom is  null
union
SELECT COUNT(*), 'Toilet is null counts' desc
  FROM [myDb].[dbo].[Properties] WHERE Toilet is  null

SELECT 
SUM(CASE WHEN Bathtub IS NULL THEN 1 ElSE 0 END) as Bathtub_count, 
SUM(CASE WHEN Bathroom IS NULL THEN 1 ElSE 0 END) as Bathroom_count,
SUM(CASE WHEN Toilet IS NULL THEN 1 ElSE 0 END) as Toilet_count
from [myDb].[dbo].[Properties]

答案 4 :(得分:1)

您可以执行此SQL SUM()功能。如下所示:

SELECT
    SUM(IF(Bathtub IS NULL, 1, 0)) AS Bathtub_count,
    SUM(IF(Bathroom IS NULL, 1, 0)) AS Bathroom_count,
    SUM(IF(Toilet IS NULL, 1, 0)) AS Toilet_count
FROM
    [ myDb ].[ dbo ].[ Properties ]