1

I have this table and I'm trying to determine how many Tables (in a restaurant) are awaiting food. The table( in the database) has the following columns: TableNumber, ObjectType, ObjectDescription and Quantity (amongst others).

I made this query to see what is ordered, but would like to know how many unique tables are waiting for food.....

SELECT TableNumber AS TAFEL
    , COUNT (*) AS AANTAL
    , ObjectDescription AS PRODUCT
FROM TableMemory 
WHERE (ObjectType = 1 OR ObjectType = 17)
GROUP BY TableNumber, ObjectType, ObjectDescription
ORDER BY TableNumber

which gives me the following output...

TAFEL       AANTAL      PRODUCT             ### OF TABLES
----------- ----------- --------------------------------------------------
1           1           Black Jacks Hotdog         5                       
1           5           Friet Groot                                       
1           2           Friet Klein                                       
1           1           Friet Middel                                     
1           1           Knoflooksaus                                    
1           1           Uitsmijter Ham/kaas                              
1           1           Uitsmijter Lou                                   
3           1           Knoflooksaus                                      
3           1           New York Hotdog                                   
7           1           Broodje Gezond                                    
7           1           Knoflooksaus                                      
40          1           Friet Groot                                       
40          1           Met Uitjes                                        
60          1           Friet Middel                                      
60          1           Meenemen 

I tried to use count and distinct in the query but nothing I tried seems to give me an extra output for the unique number of tables(restaurant) which should be 5 in the above result.

Can anyone help me? Grateful in advance!

13
  • 2
    Please provide sample data and a tag for the database you are using. Commented Jul 28, 2021 at 22:42
  • 2
    Are you trying to add the number of distinct tables to this query? Or as a separate query? Either way please show your desired results. Commented Jul 28, 2021 at 22:45
  • @Dale K I would like to get another column in the grid which represents the number of tables i.e. ### OF TABLES... The query is only used to represent; not to ad anything in the DBTABLE. Commented Jul 28, 2021 at 22:52
  • 1
    As I said, please show your desired results so its clear. Commented Jul 28, 2021 at 22:52
  • 2
    If you don't know or cannot communicate what your resultset should be, then you and everyone else will struggle. Currently your resultset contains one row for each food (objectdescription) per table (tafel). Yet you ask about how many tables awaiting food - which is a single, scalar value. Mixing the terminology between languages and column names (vs. alias) adds to the confusion. In the end, you want that last column to represent the count of all tables awaiting any food and that value is the same for every row. Is that correct? Commented Jul 28, 2021 at 23:26

3 Answers 3

1

Firstly its very important to tell us if you are using a vintage version of SQL Server. A lot has changed since 2000!

Secondly, really you are going about obtaining your data the wrong way. You are trying to combine 2 sets of data which aren't related. The correct way to handle this is to pull 2 datasets, 1 with the number of tables (Gordon has already provided this), and one with the aggregated values per table (which you already have). If for some reason you really can't do this then see the option below using a simple sub-query.

SQL Server - Window Functions Not Supported

Use a simple sub-query, being careful to duplicate the where clauses.

SELECT TableNumber AS TAFEL
    , COUNT (*) AS AANTAL
    , ObjectDescription AS PRODUCT
    , (
      SELECT COUNT(DISTINCT TableNumber) 
      FROM TableMemory 
      WHERE ObjectType IN (1, 17)
    ) TableCount
FROM TableMemory 
WHERE ObjectType IN (1, 17)
GROUP BY TableNumber, ObjectType, ObjectDescription
ORDER BY TableNumber;

SQL Server - Window Functions Supported

With reference to Gordon's existing answer to a similar question (which I admit could be hard to translate, hence why I haven't flagged as a duplicate), you can do it as follows.

  1. Compute a row number partitioned by TableNumber.
  2. Count how many rows with row number = 1 there are. Because row number 1 will only exist once per TableNumber. Note I do this in a CROSS APPLY to avoid duplicating the logic twice, once in the SELECT and once in the GROUP BY.
WITH cte AS (
  SELECT TableNumber AS TAFEL
      , ObjectDescription AS PRODUCT
      , ROW_NUMBER() OVER (PARTITION BY TableNumber ORDER BY ObjectDescription) rn
  FROM TableMemory T
  WHERE ObjectType IN (1, 17)
)
SELECT TAFEL, PRODUCT
    , COUNT (*) AS AANTAL
    , SUM(RowToCount) OVER () TableCount
FROM cte
CROSS APPLY (VALUES (CASE WHEN rn = 1 THEN 1 ELSE 0 END)) AS X (RowToCount)
GROUP BY TAFEL, PRODUCT, RowToCount
ORDER BY TAFEL;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for you help! I pasted your code in VS2019 and got the following errors... Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'WITH'. Msg 195, Level 15, State 10, Line 4 'ROW_NUMBER' is not a recognized function name. Msg 156, Level 15, State 1, Line 10 Incorrect syntax near the keyword 'OVER'
@OldJan . . . Your question is tagged SQL Server. All supported versions support both CTEs (with) and row_number(). In fact, most unsupported versions do as well.
0

To add a column which contains the (repeated) [### OF TABLES] you could use CROSS JOIN

/* This will repeat the [### OF TABLES] for each row of the results */
;with
prod_cte as (
    SELECT TableNumber AS TAFEL
        , COUNT (*) AS AANTAL
        , ObjectDescription AS PRODUCT
    FROM TableMemory 
    WHERE (ObjectType = 1 OR ObjectType = 17)
    GROUP BY TableNumber, ObjectType, ObjectDescription),
total_cte as (
    SELECT COUNT(DISTINCT TableNumber) [### OF TABLES]
    FROM TableMemory 
    WHERE ObjectType IN (1, 17)) 
select p.*, t.*
from prod_cte p
     cross join total_cte t;

[Edit] Without the CTE to work in SQL 2000

select p.*, t.*
from (
    SELECT TableNumber AS TAFEL
        , COUNT (*) AS AANTAL
        , ObjectDescription AS PRODUCT
    FROM TableMemory 
    WHERE (ObjectType = 1 OR ObjectType = 17)
    GROUP BY TableNumber, ObjectType, ObjectDescription) p,
    (
    SELECT COUNT(DISTINCT TableNumber) [### OF TABLES]
    FROM TableMemory 
    WHERE ObjectType IN (1, 17)) t;

14 Comments

Hi Steve, thanks for your help! Pasted the code in VS2019 and got this... Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'with'. Msg 156, Level 15, State 1, Line 9 Incorrect syntax near the keyword 'ORDER'.
It's updated now. I deleted the ORDER BY clause in the upper CTE
Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'with'. Msg 170, Level 15, State 1, Line 8 Line 8: Incorrect syntax near ','.
Not sure window functions are needed in this case. As @DaleK pointed out SQL 2000 is ancient and not supported. And don't update to 2008R2 that's ancient and unsupported too
@SteveC Hi Steve, you are the best!!!!!!!!! It works! Thank you so much! And of course Dale and others too for your tine and effort!
|
0

Assuming that "tafel" is table, then just use count(distinct):

SELECT COUNT(DISTINCT TableNumber) 
FROM TableMemory 
WHERE ObjectType IN (1, 17);

If you want your original data with the number of distinct tables, then just add dense_rank() twice:

SELECT TableNumber AS TAFEL, COUNT (*) AS AANTAL,
       ObjectDescription AS PRODUCT,
       (-1 +
        DENSE_RANK() OVER (ORDER BY TableNumber ASC) +
        DENSE_RANK() OVER (ORDER BY TableNumber DESC)
       ) as num_tables
FROM TableMemory 
WHERE (ObjectType = 1 OR ObjectType = 17)
GROUP BY TableNumber, ObjectType, ObjectDescription
ORDER BY TableNumber;

4 Comments

The "Tafel" is the restaurant table people eat from..... The query in my question shoud be extended to determine the number of unique restaurant tables.... A bit confusing huh? BtW thanks answering!
It doesn't work either..... Thanks for your time! I'm going to bed now; It's almost three in the night here......
Interestingly, while neater that seems to be slower (as a rough cehck) than my row_number solution.
@DaleK . . . That is interesting, actually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.