An aggregate may not appear in a computed column expression or check constraint. error while using MAX function - sql

I am receiving
An aggregate may not appear in a computed column expression or check constraint error
while using MAX function for a date column to create a table. Here is the code I'm using to create the table:
Create table Bills
(
BillNo INT NOT NULL,
MeterNo INT NOT NULL,
FirstDate datetime NOT NULL,
FirstDateReading INT NOT NULL,
CurrentDate as MAX(FirstDate),
CurrentDateReadng INT NOT NULL,
LastDate as DATEADD(m,-1,CurrentDate),
LastDateReading INT NOT NULL,
Usageinm3 as (CurrentDateReadng-LastDateReading),
Usageinlitres as (Usageinm3 * 1000),
TotalBill as (UsageinLitres * 3)
Primary Key (BillNo),
Foreign Key (MeterNo) References MeterReading(MeterNo)
);

Since you are defining the table structure, you should put the data type for each column, not the value.
Create table Bills
(
BillNo INT NOT NULL,
MeterNo INT NOT NULL,
FirstDate datetime NOT NULL,
FirstDateReading INT NOT NULL,
CurrentDate as DATE, <--should be the data type
...
If you are creating a table based on other tables, you should use something like
SELECT billno,
meterno,
firstdate,
firstdatereading,
MAX(firstdate)
...
INTO Bills
FROM sourcetable
WHERE conditions
GROUP BY billno,
meterno,
firstdate,
firstdatereading
...

Related

Сreating a calculated field from other tables

I want to create a calculated amount field in the sales table that will accept the total of the items related to this order, but I ran into a problem.
"subqueries cannot be used in the generated column expression."
Please tell me how you can do this, taking into account the fact that the architecture cannot be changed.
CREATE TABLE products (
id bigserial PRIMARY KEY,
name varchar(255) NOT NULL,
description varchar(255) NOT NULL,
price decimal NOT NULL
);
CREATE TABLE sales (
id bigserial PRIMARY KEY,
employee_id int NOT NULL,
created_at timestamp NOT NULL,
amount decimal GENERATED ALWAYS AS ( /* subqueris */ ) STORED
);
CREATE TABLE products_sales (
sales_id int NOT NULL,
product_id int NOT NULL,
PRIMARY KEY (sales_id, product_id)
);

Get a descending list of items using two tables

CREATE TABLE [dbo].[HistoricoSeries] (
[IDHistoricoSeries] INT IDENTITY (1, 1) NOT NULL,
[IDUtilizador] INT NOT NULL,
[codepisodio] INT NOT NULL,
CONSTRAINT [PK_historicoseries] PRIMARY KEY CLUSTERED ([IDHistoricoSeries] ASC),
CONSTRAINT [FK_96] FOREIGN KEY ([IDUtilizador]) REFERENCES [dbo].[Utilizadores] ([IDUtilizador]),
CONSTRAINT [FK_hse] FOREIGN KEY ([codepisodio]) REFERENCES [dbo].[EPISODIOS] ([codepisodio])
);
CREATE TABLE [dbo].[EPISODIOS] (
[idepisodio] INT IDENTITY (1, 1) NOT NULL,
[codepisodio] INT NOT NULL,
[codserie] INT NOT NULL,
[codtemporada] INT NOT NULL,
[numeroepisodio] INT NOT NULL,
[tituloepisodio] VARCHAR (53) NOT NULL,
[duracaominutos] INT NOT NULL,
PRIMARY KEY CLUSTERED ([codepisodio] ASC)
);
These are my table definitions.
string maisVistoEpisodio = "SELECT * FROM EPISODIOS WHERE EPISODIOS.codepisodio IN (SELECT codepisodio, count(codepisodio) AS mais_vistos FROM HISTORICOSERIES GROUP BY codepisodio ORDER BY COUNT (codepisodio) DESC)";
This is my SQL Server query that i've been from quite sometime hacking away with no results.
My end goal was to have a listing of the most watched episodes from the table EPISODIOS, but the error
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
arose itself and I don't know how to fix.
Can anyone shed a bit of light?
Thanks.
Your code looks like SQL Server. If so, you can use TOP WITH TIES in the subquery:
SELECT E.*
FROM EPISODIOS E
WHERE E.codepisodio IN (SELECT TOP (1) WITH TIES HS.codepisodio
FROM HISTORICOSERIES HS
GROUP BY HS.codepisodio
ORDER BY COUNT(*) DESC
)

Insert into a new Table in SQL gives error

Why am I getting an error?
--Q1
CREATE table Aorders (
Id INT IDENTITY NOT NULL,
CreatedDate Date NOT NULL,
BillingCountry varchar Not Null,
MerchId int Not null,
OrderStatus varchar Not null,
);
--Q2
select * from Aorders
--Q3 edited as suggested here but still get an error
INSERT INTO Aorders (CreatedDate, BillingCountry, MerchId, OrderStatus)
VALUES ('2001-01-01', 'Israel', 5 ,'Approved');
You must define the length of the varchar columns like:
CREATE table Aorders (
Id INT IDENTITY NOT NULL,
CreatedDate Date NOT NULL,
BillingCountry varchar(100) Not Null,
MerchId int Not null,
OrderStatus varchar(100) Not null,
);
From char and varchar (Transact-SQL):
When n isn't specified in a data definition or variable declaration
statement, the default length is 1
When doing an insert, the best practice is to list all the columns explicitly and to use standard formats for dates:
INSERT INTO Aorders (CreatedDate, BillingCountry, MerchId, OrderStatus)
VALUES ('2001-01-01', 'Israel', 5 ,'Approved');
Your specific error is because you have four values in the VALUES() list but there are five columns in the table.
You have not done your query properly. I think you want the ID to auto increment ,but you haven't declare that. Make changes as below:
CREATE table Aorders ( Id INT IDENTITY NOT NULL
,CreatedDate Date NOT NULL
,BillingCountry varchar Not Null
,MerchId int Not null
,OrderStatus varchar Not null);
Now enter the query as you have inserted. And also make sure proper date formats from documentation.

SQL How to convert this to a SubQuery?

Learning, be kind.
I am trying to understand how this works and I have done several successful conversions, but this one I am stumped on.
How do I take this code and convert it to a subquery? I'm a little lost.
SELECT o.FirstName + ' ' + o.LastName AS Driver, COUNT(DISTINCT s.vehicleID) NoOfBusesUsed
FROM Operators AS o, Runs AS r, Schedules AS s JOIN Trips AS t
ON s.scheduleID = t.scheduleID
WHERE r.BidDate BETWEEN '09/01/2004' AND '09/30/2004'
GROUP BY o.FirstName + ' ' + o.LastName
HAVING COUNT(s.vehicleID) > 1
Here is how my tables are setup. If more info is needed, I can post.
CREATE TABLE Operators
(
SeniorityNumber char(4) NOT NULL
CONSTRAINT ck_Operators_Seniority
CHECK (SeniorityNumber LIKE '[0-9][0-9][0-9][0-9]'),
FirstName varchar(25) NOT NULL,
LastName varchar(35) NOT NULL,
HireDate smalldatetime
CONSTRAINT ck_Operators_HireDate CHECK (HireDate <=Getdate())
)
CREATE TABLE Trips
(
RouteNumber varchar(4) NOT NULL,
StartLocation varchar(50) NOT NULL,
StartTime time NOT NULL,
EndLocation varchar(50) NOT NULL,
EndTime time NOT NULL,
EffectiveDate smalldatetime NOT NULL
CHECK (EffectiveDate >= cast('1/1/2000' as smalldatetime)),
CONSTRAINT ck_Trips_StartEnd CHECK (EndTime > StartTime)
)
CREATE TABLE Vehicles
(
Manufacturer varchar(50)
DEFAULT 'Gillig',
Model varchar(50),
ModelYear int
DEFAULT DatePart(yyyy,GetDate())
CHECK (ModelYear <= DatePart(yyyy,GetDate())),
PurchaseDate smalldatetime
)
GO
ALTER TABLE operators
ADD OperatorID int IDENTITY --Primary Key
GO
ALTER TABLE Operators
ADD CONSTRAINT pkOperators Primary key (OperatorID)
ALTER TABLE Vehicles
ADD VehicleID int IDENTITY Primary Key
ALTER TABLE Trips
ADD TripID int IDENTITY Primary key
GO
CREATE TABLE Runs
(
RunID int IDENTITY NOT NULL Primary Key,
OperatorID int NOT NULL REFERENCES Operators,
BidDate date NOT NULL
CONSTRAINT ckRunBidDate CHECK
(biddate <= dateadd(mm,6,getdate())) --getdate() + 180
)
GO
CREATE TABLE Schedules
(
ScheduleID int IDENTITY Primary Key,
RunID int NOT NULL,
VehicleID int NOT NULL,
CONSTRAINT fk_Schedules_Runs FOREIGN KEY (RunID)
REFERENCES Runs(RunID),
CONSTRAINT fk_Schedules_Vehicles FOREIGN KEY (VehicleID)
REFERENCES Vehicles
)
ALTER TABLE Trips
ADD ScheduleID int NULL REFERENCES Schedules
When you want to use a query as a sub-query you can use WITH statement or a derived table like:
With:
;WITH subQuery AS (
/* Your query here */
)
SELECT *
FROM subQuery
Derived table
SELECT *
FROM (
/* your query here */
) As subQuery
I think you should use a query like this:
SELECT
o.FirstName + ' ' + o.LastName AS Driver,
DT.cnt AS NoOfBusesUsed
FROM
Operators AS o
JOIN
(SELECT
r.OperatorID,
COUNT(DISTINCT s.VehicleID) AS cnt
FROM
Schedules s
JOIN
Runs r ON s.RunID = r.RunID
) AS DT
ON DT.OperatorID = o.OperatorID
WHERE
ISNULL(DT.cnt, 0) > 1

SQL Logic and Aggregate Issue

I have the following problem to solve in SQL :
d) A query that provides management information on take up of the various types of activities on offer. For each type of activity, the query should show the total number of individuals who took that type of activity and the average number of individuals taking each type of activity.
Here are my tables :
CREATE TABLE accommodations
(
chalet_number int PRIMARY KEY,
chalet_name varchar(40) NOT NULL,
no_it_sleeps number(2) NOT NULL,
indivppw number(4) NOT NULL
)
CREATE TABLE supervisors
(
supervisor_number int PRIMARY KEY,
supervisor_forename varchar(30) NOT NULL,
supervisor_surname varchar(30) NOT NULL,
mobile_number varchar(11) NOT NULL
)
CREATE TABLE visitors
(
visitor_ID int PRIMARY KEY,
group_ID int NOT NULL,
forename varchar(20) NOT NULL,
surname varchar(20) NOT NULL,
dob date NOT NULL,
gender varchar(1) NOT NULL
)
CREATE TABLE activities
(
activity_code varchar(10) PRIMARY KEY,
activity_title varchar(20) NOT NULL,
"type" varchar(20) NOT NULL
)
CREATE TABLE "groups"
(
group_ID int PRIMARY KEY,
group_leader varchar(20) NOT NULL,
group_name varchar(30)
number_in_group number(2) NOT NULL
)
CREATE TABLE bookings
(
group_ID int NOT NULL,
start_date date NOT NULL,
chalet_number int NOT NULL,
no_in_chalet number(2) NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
CONSTRAINT bookings_pk PRIMARY KEY(group_ID, chalet_number));
CREATE TABLE schedule
(
schedule_ID int PRIMARY KEY,
activity_code varchar(10) NOT NULL,
time_of_activity number(4,2) NOT NULL,
am_pm varchar(2) NOT NULL,
"date" date NOT NULL
)
CREATE TABLE activity_bookings
(
visitor_ID int NOT NULL,
schedule_ID int NOT NULL,
supervisor_number int NOT NULL,
comments varchar(200),
CONSTRAINT event_booking_pk PRIMARY KEY(visitor_ID, schedule_ID));
ALTER TABLE visitors
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE Schedule
ADD FOREIGN KEY (activity_code)
REFERENCES activities(activity_code)
ALTER TABLE bookings
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE bookings
ADD FOREIGN KEY (chalet_number)
REFERENCES accommodations(chalet_number)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (visitor_ID)
REFERENCES visitors(visitor_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (schedule_ID)
REFERENCES schedule(schedule_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (supervisor_number)
REFERENCES supervisors(supervisor_number)
I have the following solution:
SELECT activities."type", 'overalltotal' AS OT, ('overalltotal' / 'activities') AS AVG
FROM activities, schedule
WHERE 'overalltotal' = (SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type"
)
AND 'activities' = (SELECT COUNT(DISTINCT activities."type")
FROM activities
)
AND schedule.activity_code = activities.activity_code
GROUP BY activities."type";
I have implemented sample data and code to check the variables above:
SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type";
Result : 20
SELECT COUNT(DISTINCT activities."type")
FROM activities;
Result : 5
However when running the code :
ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause:
*Action:
EDIT:
Using Dave's Code i have the following output:
Snowboarding 15
sledding 19
Snowmobiling 6
Ice Skating 5
Skiing 24
How would i do the final part of the question?
and the average number of individuals taking each type of activity.
You must use double quotes around column names in Oracle, not single quotes. For example, "overalltotal". Single quotes are for text strings, which is why you're getting an invalid number error.
EDIT: This is probably the type of query you want to use:
SELECT activities."type", COUNT(*) AS total, COUNT(*)/(COUNT(*) OVER ()) AS "avg"
FROM activities a
JOIN schedule s ON a.activity_code=s.activity_code
JOIN activity_bookings ab ON s.schedule_ID=ab.schedule_ID
GROUP BY activities."type";
Basically, because each activity booking has one visitor id, we want to get all the activity bookings for each activity. We have to go through schedule to do that. They we group the rows by the activity type and count how many activity bookings we have for each type.