1

我需要从不同的表中检索具有不同条件的多个列。我有如下

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'

只是想知道有没有更好的方法来为上述条件重构更好的查询?

4

2 回答 2

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
于 2013-04-10T06:01:56.457 回答
2

将 table1 添加到 J W 的上述精彩查询中。

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
于 2013-04-10T07:09:22.310 回答