1

グループごとにアクティブなクライアントを計算するクエリがあり、グループごとにピックアップを計算する必要があります。

SELECT  [Category] = ISNULL(c.Category, 'Total'),
        COUNT (hs.ClientID) as '3 Mo Clients',
        (COUNT (hs.ClientID))/3 as MoAVG
      ,(select COUNT(PickupID)from Pickup where PickupDate between '2013-01-01' and '2013-03-30' group by CategCode) as '3 Mo Picups'

FROM    Category c 
        LEFT JOIN history hs
            ON hs.CategCode = c.CategCode 
            where ReccordDate between '2013-01-01' and '2013-03-30'
GROUP BY Category
WITH ROLLUP

このクエリはエラーをスローします:Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

4 行でグループ化を使用していない場合は機能しますが、グループごとにピックアップを分割しませんでした。これは、コードの 4 行で group by 句なしでどのように機能するかの例です。
それを修正する方法はありますか?

それを修正する方法はありますか?

4

1 に答える 1

2

この条件を追加してみてください: CategCode = c.CategCode

SELECT [Category] = ISNULL(c.Category, 'Total'),
       COUNT (hs.ClientID) as [3 Mo Clients],
       (COUNT (hs.ClientID))/3 as MoAVG
      ,(SELECT COUNT(PickupID) 
        FROM Pickup 
        WHERE PickupDate between '2013-01-01' and '2013-03-30'
          AND  CategCode = c.CategCode
       ) AS [3 Mo Picups]
FROM Category c LEFT JOIN history hs ON hs.CategCode = c.CategCode 
WHERE ReccordDate between '2013-01-01' and '2013-03-30'
GROUP BY c.CategCode, c.Category 
WITH ROLLUP

また

SELECT [Category] = ISNULL(c.Category, 'Total'),
       COUNT (hs.ClientID) as [3 Mo Clients],
       (COUNT (hs.ClientID))/3 as MoAVG,
       SUM(o.cnt) AS [3 Mo Picups]
FROM Category c LEFT JOIN history hs ON hs.CategCode = c.CategCode
                CROSS APPLY (
                             SELECT COUNT(PickupID) AS cnt
                             FROM Pickup 
                             WHERE PickupDate between '2013-01-01' and '2013-03-30'
                               AND  CategCode = c.CategCode
                             ) o
WHERE ReccordDate between '2013-01-01' and '2013-03-30'
GROUP BY c.Category 
WITH ROLLUP
于 2013-03-12T22:49:29.280 に答える