我需要从不同的表中检索具有不同条件的多个列。 我的内容如下
SELECT
(SELECT COUNT(*) FROM Table1 WHERE Price >= 0 Price < 10) AS 'Group1',
(SELECT COUNT(*) FROM Table1 WHERE Price >= 10 AND Price < 20) AS 'Group2',
(SELECT COUNT(*) FROM Table1 WHERE Price >= 20 AND Price < 30) AS 'Group3',
(SELECT COUNT(*) FROM Table2 WHERE Price >= 0 Price < 10) AS 'Group4',
(SELECT COUNT(*) FROM Table2 WHERE Price >= 10 AND Price < 20) AS 'Group5',
(SELECT COUNT(*) FROM Table2 WHERE Price >= 20 AND Price < 30) AS 'Group6'
只是想知道有没有更好的方法来重构上述条件的更好的查询?
答案 0 :(得分:4)
有,
SELECT SUM(CASE WHEN Price >= 0 Price < 10 THEN 1 END) AS 'Group1',
SUM(CASE WHEN Price >= 10 AND Price < 20 THEN 1 END) AS 'Group2',
SUM(CASE WHEN Price >= 20 AND Price < 30 THEN 1 END) AS 'Group3',
SUM(CASE WHEN Price >= 0 Price < 10 THEN 1 END) AS 'Group4',
SUM(CASE WHEN Price >= 10 AND Price < 20 THEN 1 END) AS 'Group5',
SUM(CASE WHEN Price >= 20 AND Price < 30 THEN 1 END) AS 'Group6'
FROM table2
答案 1 :(得分:2)
通过J W将table1添加到上述精彩查询中。
SELECT SUM(CASE WHEN T1.Price >= 0 Price < 10 THEN 1 END) AS 'Group1',
SUM(CASE WHEN T1.Price >= 10 AND Price < 20 THEN 1 END) AS 'Group2',
SUM(CASE WHEN T1.Price >= 20 AND Price < 30 THEN 1 END) AS 'Group3',
SUM(CASE WHEN T2.Price >= 0 Price < 10 THEN 1 END) AS 'Group4',
SUM(CASE WHEN T2.Price >= 10 AND Price < 20 THEN 1 END) AS 'Group5',
SUM(CASE WHEN T2.Price >= 20 AND Price < 30 THEN 1 END) AS 'Group6'
FROM table1 T1, table2 T2