[英]Multiple counts in a single SQL query
我有以下三个不同的查询:
SELECT COUNT(*)
FROM [myDb].[dbo].[Properties] WHERE Bathtub is null
SELECT COUNT(*)
FROM [myDb].[dbo].[Properties] WHERE Bathroom is null
SELECT COUNT(*)
FROM [myDb].[dbo].[Properties] WHERE Toilet is null
我想在一个查询中查看其计数。 我怎样才能做到这一点? 谢谢。
使用子查询! 了解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
警告如果您担心性能会涉及开销
试试这个(这是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];
或这样写:
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
尝试结合自定义描述
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]
您可以执行此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 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.