有没有更好的方法来使用Linq优化SQL查询?

时间:2017-04-07 09:34:02

标签: sql-server linq

我正在尝试从两个表中获取计数详细信息。计数取决于 table1.data 字段 以下是查询

SELECT 'ALL'    AS Type, 
Count(*) AS Cnt 
FROM   table1 
INNER JOIN table2 
ON table1.id = table2.id 
WHERE  table1.id = 2683 

UNION ALL 
SELECT 'NO TYPE' As Type, 
Count(*) AS Cnt 
FROM   table1 
INNER JOIN table2 
ON table1.id = table2.id 
WHERE  table1.id = 2683 
AND Isnull(table1.data, '') = '' 

UNION ALL 
SELECT Isnull(table1.data, '') As Type, 
Count(*)                    AS Cnt 
FROM   table1 
INNER JOIN table2 
ON table1.id = table2.id 
WHERE  table1.id = 2683 
AND Isnull(table1.data, '') <> '' 
GROUP  BY Isnull(table1.data, '') 

输出应为

Type             Cnt
--------------  -----
ALL               4
NO TYPE           0
Type1             3

我试图使用案例陈述,但我失败了。请提出任何建议。 的更新 实际的SQL查询是

SELECT 'ALL'    AS FloorNoteType, 
       Count(*) AS Cnt 
FROM   floor_notes 
       INNER JOIN floor_note_xref 
               ON floor_notes.floor_note_id = floor_note_xref.floor_note_id 
WHERE  floor_note_xref.inmate_id = 2683 
UNION ALL 
SELECT 'NO TYPE', 
       Count(*) AS Cnt 
FROM   floor_notes 
       INNER JOIN floor_note_xref 
               ON floor_notes.floor_note_id = floor_note_xref.floor_note_id 
WHERE  floor_note_xref.inmate_id = 2683 
       AND Isnull(floor_note_type, '') = '' 
UNION ALL 
SELECT Isnull(floor_note_type, '') AS FloorNoteType, 
       Count(*)                    AS Cnt 
FROM   floor_notes 
       INNER JOIN floor_note_xref 
               ON floor_notes.floor_note_id = floor_note_xref.floor_note_id 
WHERE  floor_note_xref.inmate_id = 2683 
       AND Isnull(floor_note_type, '') <> '' 
GROUP  BY Isnull(floor_note_type, '') 

1 个答案:

答案 0 :(得分:3)

您可以使用WITH ROLLUP子句的单个查询检索所有总计:

SELECT
  CASE WHEN 
            GROUPING(table1.data) = 1 THEN 'ALL'
       ELSE 
            ISNULL(table1.data, 'NO TYPE')
  END AS Type,
  count(*) Cnt
FROM 
    table1 
    INNER JOIN table2 ON table1.id = table2.id 
WHERE  table1.id = 2683 
GROUP  BY table1.data WITH ROLLUP

WITH ROLLUPGROUP BY子句中的每个字段生成分层次小计,一直到总计。

不参加小计的字段具有NULL值,这意味着空键和小计可能会混淆。 GROUPING(..)函数检查结果行是否是特定字段的总计。

在这种情况下,只有一个分组字段,因此GROUPING(table1.data)仅对与总计相对应的行返回1