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

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