2015-09-07 68 views
0

我該如何解決以下問題?Msg 512,Level 16錯誤

Msg 512,Level 16,State 1,Line 1子查詢返回的值超過1。當子查詢遵循=,!=,<,< =,>,> =或當子查詢用作表達式時,這是不允許的。該語句已終止。

我試圖讓頻率,如:

| Frequency 
| 19 
| 23 

但不知何故,我不能將烘焙查詢得到比我更值:

SELECT ts.TimeDifference/ ts.EntryAmount as Frequency 
FROM 
(
    SELECT COUNT(*) as EntryAmount, 
    (
     SELECT DATEDIFF(d, t.minimum, t.maximum) 
     FROM (SELECT max(Date) AS maximum, min(Date) AS minimum FROM Times GROUP BY column1, column2, column3, column4 HAVING COUNT(*) > 1) t 
    ) AS TimeDifference 
    FROM Times 
) ts 

謝謝。

回答

1

你內心的子選擇將返回不止一個結果。您將得到第1,2,3和4列的最小和最大PER組合。擺脫子選擇,它將解決問題。

SELECT 
    DATEDIFF(d, ts.minimum, ts.maximum)/ ts.EntryAmount as Frequency 
    ,ts.column1, ts.column2, ts.column3, ts.column4 
FROM 
(
    SELECT 
     COUNT(*) as EntryAmount, 
     max(Date) AS maximum, 
     min(Date) AS minimum, 
     column1, column2, column3, column4 
    FROM Times 
    GROUP BY column1, column2, column3, column4 
    HAVING COUNT(*) > 1 
) ts 
+0

哇謝謝你。有用! –

0

您可以使用聚合函數:

SELECT ts.TimeDifference/ ts.EntryAmount as Frequency 
FROM 
(
    SELECT COUNT(*) as EntryAmount, 
    (
     SELECT Max(DATEDIFF(d, t.minimum, t.maximum)) 
     FROM (SELECT max(Date) AS maximum, min(Date) AS minimum FROM Times GROUP BY column1, column2, column3, column4 HAVING COUNT(*) > 1) t 
    ) AS TimeDifference 
    FROM Times 
) ts 
相關問題