Tuesday, October 22, 2013
SQL query for packages and Source path of the packages
Monday, April 23, 2012
is computer is 32 bit or 64 bit ?
--Finding computer is 32 bit or 64 bit is easy from SCCM... here is SQL query............
SELECT Distinct SYS.Netbios_Name0, CS.Model0,CPU.Name0 AS [CPU Name], CASE WHEN CPU.Is64Bit0 = 1
THEN 'Yes' ELSE 'No' END AS [CPU 64-Bit],ROUND(CONVERT(FLOAT,CPU.MaxClockSpeed0), -2)/1000
AS [CPU (GHz)],
ROUND(ROUND(CONVERT(FLOAT,MEM.TotalPhysicalMemory0) / 1048576, 2) , 1)
AS [RAM (GB)],[TPM Chip]=(SELECT v_GS_SYSTEM_DEVICES.Name0
FROM v_GS_SYSTEM_DEVICES WHERE v_GS_SYSTEM_DEVICES.ResourceID=SYS.ResourceID AND
v_GS_SYSTEM_DEVICES.Name0 LIKE '%Trusted Platform%') ,LDISK.DeviceID0,LDISK.Size0/1024
AS [Size (GB)],LDISK.FreeSpace0/1024 AS [Free Space (GB)] FROM v_R_System SYS LEFT JOIN
v_GS_LOGICAL_DISK LDISK on SYS.ResourceID = LDISK.ResourceID LEFT JOIN
v_GS_COMPUTER_SYSTEM CS on SYS.ResourceID = CS.ResourceID LEFT JOIN
v_GS_X86_PC_MEMORY MEM on SYS.ResourceID = MEM.ResourceID LEFT JOIN
v_GS_Processor CPU on SYS.ResourceID = CPU.ResourceID LEFT JOIN
v_GS_SYSTEM_DEVICES DEV on SYS.ResourceID = DEV.ResourceID
WHERE LDISK.DeviceID0 = 'C:' AND CS.Model0 NOT LIKE '%VMWARE%'
ORDER BY SYS.Netbios_Name0
Friday, February 17, 2012
C drive disk space information on my all machine
Wednesday, February 8, 2012
For a specific Advertisement status for last 3 Days…
---for a specific Advertisement status for last 3 Days… if we include the Set @AdvName = '%' line then and remove the above line in red color will show for all advertisements with last 3 days status
-- To include all we need to give % in SQL this is a tip
Declare @AdvName Varchar(256)
Set @AdvName = 'Lync_2010_Full_Install'
---Set @AdvName = '%'
Select adv.AdvertisementName
, adv.AdvertisementID
, s.Host
, LastAcceptanceMessageIDName
, LastAcceptanceStateName
, LastAcceptanceStatusTime
, LastStatusMessageIDName
, LastStateName
, LastStatusTime
, LastExecutionResult
From (
Select AdvertisementName
, AdvertisementID
From dbo.v_AdvertisementInfo
Where AdvertisementName Like @AdvName
) As adv
Join (
Select AdvertisementID
, ResourceID
, LastAcceptanceMessageIDName
, LastAcceptanceStateName
, LastAcceptanceStatusTime
, LastStatusMessageIDName
, LastStateName
, LastStatusTime
, LastExecutionResult
From dbo.v_ClientAdvertisementStatus
Where LastStatusTime >= DateAdd(d,-3,GetDate())
) As cas
On adv.AdvertisementID = cas.AdvertisementID
Join (
Select ResourceID
, Netbios_Name0 As Host
From dbo.v_R_System
Where Client0 = 1
And Active0 = 1
And Obsolete0 = 0
) As s
On cas.ResourceID = s.ResourceID
Order By
AdvertisementName
, Host
HeartBeat Discovery Status of specific collection of systems
select
CS.Name0,
max(AD.AgentTime) as 'Date/Time'
from
dbo.v_AgentDiscoveries ad
JOIN dbo.v_GS_COMPUTER_SYSTEM cs on AD.ResourceID = CS.ResourceId
join dbo.v_FullCollectionMembership FCM on FCM.ResourceID = CS.ResourceId
Where
AgentName = 'Heartbeat Discovery'
and FCM.CollectionID = 'SMS00001'
Group by
CS.Name0
Friday, January 27, 2012
AD computer Numbers vs SCCM Computer Numbers
read here more http://smsug.ca/blogs/garth_jones/archive/2008/12/03/how-to-add-ad-data-to-configmgr-reporting.aspx
AD it just another database, just like SQL server is. With that in mind there is nothing stopping you from using SQL to link to AD to give you data about your AD environment!
1) Create Linked Server using SSMS
exec master.dbo.sp_addlinkedserver 'ADSI', 'Active Directory Service Interfaces', 'ADSDSOObject', '<DC Name FQDN>'
2) Modify the security for ADSI using SSMS
exec master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'ADSI', @locallogin = NULL , @useself = N'False', @rmtuser = N'<Domian>\<User Id>', @rmtpassword = N'<Password>'
3) The hard part is over!
4) Create query to query AD and ConfigMgr
This query will list all PCs within AD that are NOT within ConfigMgr (or SMS)
select
AD.cn as 'PC Name(AD)',
AD.operatingSystem as 'OS (AD)',
AD.operatingSystemServicePack as 'SP (AD)'
from
openquery (ADSI,
'SELECT cn,
operatingSystem,
operatingSystemServicePack
FROM ''LDAP://<DC Name FQDN>''
WHERE objectCategory = ''Computer''') as AD
Where
AD.cn not in (Select name0 from v_GS_Computer_System as CS)
order by
AD.cn,
AD.operatingSystem,
AD.operatingSystemServicePack
This query will give you a count of all OS that are NOT within ConfigMgr (or SMS)
select
AD.operatingSystem as 'OS (AD)',
count(AD.operatingSystem)
from
openquery (ADSI,
'SELECT cn,
operatingSystem,
operatingSystemServicePack
FROM ''LDAP://gartek-dc.gartek.tst''
WHERE objectCategory = ''Computer''') as AD
Where
AD.cn not in (Select name0 from v_GS_Computer_System as CS)
Group by
AD.operatingSystem
order by
AD.operatingSystem
So what does this report look like.
So there you have it.
Tuesday, December 27, 2011
SQL Query to Show Any missing Boundaries in the SCCM Hierarchy
SELECT DISTINCT
v_R_System.Name0,
v_R_System.Client0,
v_RA_System_IPAddresses.IP_Addresses0,
v_RA_System_IPSubnets.IP_Subnets0,
v_RA_System_SMSAssignedSites.SMS_Assigned_Sites0
FROM v_R_System LEFT OUTER JOIN
v_RA_System_IPSubnets ON v_R_System.ResourceID = v_RA_System_IPSubnets.ResourceID LEFT OUTER JOIN
v_RA_System_IPAddresses ON v_R_System.ResourceID = v_RA_System_IPAddresses.ResourceID LEFT OUTER JOIN
v_RA_System_SMSAssignedSites ON v_R_System.ResourceID = v_RA_System_SMSAssignedSites.ResourceID
WHERE (v_RA_System_SMSAssignedSites.SMS_Assigned_Sites0 IS NULL)
AND (NOT (v_RA_System_IPAddresses.IP_Addresses0 IS NULL))
AND (v_R_System.Client0 IS NULL)
AND (NOT (v_RA_System_IPSubnets.IP_Subnets0 IS NULL))
order by v_RA_System_IPSubnets.IP_Subnets0
Thursday, October 13, 2011
SCCM Report: Server or Workstation Uptime Report
----This report will give you server uptime information:
SELECT os.Caption0 AS 'Operating System', cs.Name0 AS Name, DATEDIFF(hour, os.LastBootUpTime0, ws.LastHWScan) AS 'Uptime (in Hours)', CONVERT(varchar(20),
os.LastBootUpTime0, 100) AS 'Last Reboot Date/Time', CONVERT(varchar(20), ws.LastHWScan, 100) AS 'Last Hardware Inventory'
FROM v_GS_WORKSTATION_STATUS AS ws LEFT OUTER JOIN
v_GS_OPERATING_SYSTEM AS os ON ws.ResourceID = os.ResourceID INNER JOIN
v_GS_COMPUTER_SYSTEM AS cs ON cs.ResourceID = os.ResourceID
WHERE (os.Caption0 LIKE '%server%') AND (ws.LastHWScan <> 0) AND (cs.Name0 IS NOT NULL)
ORDER BY Name
----This report will give you Workstations uptime information:
SELECT TOP (100) PERCENT os.Caption0 AS 'Operating System', cs.Name0 AS Name, DATEDIFF(hour, os.LastBootUpTime0, ws.LastHWScan) AS 'Uptime (in Hours)',
CONVERT(varchar(20), os.LastBootUpTime0, 100) AS 'Last Reboot Date/Time', CONVERT(varchar(20), ws.LastHWScan, 100) AS 'Last Hardware Inventory'
FROM dbo.v_GS_WORKSTATION_STATUS AS ws LEFT OUTER JOIN
dbo.v_GS_OPERATING_SYSTEM AS os ON ws.ResourceID = os.ResourceID INNER JOIN
dbo.v_GS_COMPUTER_SYSTEM AS cs ON cs.ResourceID = os.ResourceID
WHERE (ws.LastHWScan <> 0) AND (cs.Name0 IS NOT NULL) AND (os.Caption0 LIKE '%xp%') OR
(os.Caption0 LIKE '%7%') OR
(os.Caption0 LIKE '%vista%')
ORDER BY Name
Thursday, May 12, 2011
SCCM State ID’s from Client end error (Focused on Patching )
TopicType | StateID | StateName | StateDescription |
300 | 0 | Compliance state unknown | Compliance state unknown |
300 | 1 | Compliant | Compliant |
300 | 2 | Non-compliant | Non-compliant |
300 | 3 | Conflict detected | Conflict detected |
301 | 0 | Enforcement state unknown | Enforcement state unknown |
301 | 1 | Installing update(s) | Installing update(s) |
301 | 2 | Waiting for restart | Waiting for restart |
301 | 3 | Waiting for another installation to complete | Waiting for another installation to complete |
301 | 4 | Successfully installed update(s) | Successfully installed update(s) |
301 | 5 | Pending system restart | Pending system restart |
301 | 6 | Failed to install update(s) | Failed to install update(s) |
301 | 7 | Downloading update(s) | Downloading update(s) |
301 | 8 | Downloaded update(s) | Downloaded update(s) |
301 | 9 | Failed to download update(s) | Failed to download update(s) |
301 | 10 | Waiting for maintenance window before installing | Waiting for maintenance window before installing |
302 | 0 | Evaluation state unknown | Evaluation state unknown |
302 | 1 | Evaluation activated | Evaluation activated |
302 | 2 | Evaluation succeeded | Evaluation succeeded |
302 | 3 | Evaluation failed | Evaluation failed |
400 | 0 | Detection state unknown | Detection state unknown |
400 | 1 | Not Required | Not Required |
400 | 2 | Not Detected | Not Detected |
400 | 3 | Detected | Detected |
401 | 0 | Compliance state unknown | Compliance state unknown |
401 | 1 | Compliant | Compliant |
401 | 2 | Non-Compliant | Non-Compliant |
401 | 3 | Conflict Detected | Conflict Detected |
401 | 4 | Error | Error |
402 | 0 | Enforcement state unknown | Enforcement state unknown |
402 | 1 | Enforcement started | Enforcement started |
402 | 2 | Enforcement waiting for content | Enforcement waiting for content |
402 | 3 | Waiting for another installation to complete | Waiting for another installation to complete |
402 | 4 | Waiting for maintenance window before installing | Waiting for maintenance window before installing |
402 | 5 | Restart required before installing | Restart required before installing |
402 | 6 | General failure | General failure |
402 | 7 | Pending installation | Pending installation |
402 | 8 | Installing update | Installing update |
402 | 9 | Pending system restart | Pending system restart |
402 | 10 | Successfully installed update | Successfully installed update |
402 | 11 | Failed to install update | Failed to install update |
402 | 12 | Downloading update | Downloading update |
402 | 13 | Downloaded update | Downloaded update |
402 | 14 | Failed to download update | Failed to download update |
500 | 0 | Detection state unknown | Detection state unknown |
500 | 1 | Update is not required | Update is not required |
500 | 2 | Update is required | Update is required |
500 | 3 | Update is installed | Update is installed |
501 | 0 | Scan state unknown | Scan state unknown |
501 | 1 | Scan is waiting for content | Scan is waiting for content |
501 | 2 | Scan is running | Scan is running |
501 | 3 | Scan completed | Scan completed |
501 | 4 | Scan is pending retry | Scan is pending retry |
501 | 5 | Scan failed | Scan failed |
501 | 6 | Scan completed with errors | Scan completed with errors |
501 | 7 | SMS 2003 client | SMS 2003 client |
800 | 100 | Client deployment started. | Client deployment started. |
800 | 301 | Unknown client deployment failure. | Unknown client deployment failure. |
800 | 302 | Failed to create the ccmsetup service. | Failed to create the ccmsetup service. |
800 | 303 | Failed to delete the ccmsetup service. | Failed to delete the ccmsetup service. |
800 | 304 | Cannot install over embedded OS with File Based Write Filter (FBWF) enabled on system drive. | Cannot install over embedded OS with File Based Write Filter (FBWF) enabled on system drive. |
800 | 305 | Native security mode is invalid on Windows 2000. | Native security mode is invalid on Windows 2000. |
800 | 306 | Failed to start ccmsetup download process. | Failed to start ccmsetup download process. |
800 | 307 | Invalid ccmsetup command line: | Invalid ccmsetup command line: |
800 | 308 | Failed to download file over WINHTTP at address: | Failed to download file over WINHTTP at address: |
800 | 309 | Failed to download files through BITS at address: | Failed to download files through BITS at address: |
800 | 310 | Failed to install BITS version: | Failed to install BITS version: |
800 | 311 | Can't verify that prerequisite file is MS signed: | Can't verify that prerequisite file is MS signed: |
800 | 312 | Failed to copy file because disk is full. | Failed to copy file because disk is full. |
800 | 313 | Client.msi installation failed with MSI error: | Client.msi installation failed with MSI error: |
800 | 314 | Failed to load ccmsetup.xml manifest file. | Failed to load ccmsetup.xml manifest file. |
800 | 315 | Failed to obtain client certificate. | Failed to obtain client certificate. |
800 | 316 | Prerequisite file is not MS signed: | Prerequisite file is not MS signed: |
800 | 317 | A reboot is required to continue installation. | A reboot is required to continue installation. |
800 | 318 | Can't install the client on the MP because the MP and client versions don't match. | Can't install the client on the MP because the MP and client versions don't match. |
800 | 319 | The operating system or service pack is not supported. | The operating system or service pack is not supported. |
800 | 400 | Client deployment succeeded. | Client deployment succeeded. |
800 | 500 | Client assignment started. | Client assignment started. |
800 | 601 | Unknown client assignment failure. | Unknown client assignment failure. |
800 | 602 | The following site code is invalid: | The following site code is invalid: |
800 | 603 | Failed to assign to MP: | Failed to assign to MP: |
800 | 604 | Failed to discover default management point. | Failed to discover default management point. |
800 | 605 | Failed to download site signing certificate. | Failed to download site signing certificate. |
800 | 606 | Failed to auto discover site code. | Failed to auto discover site code. |
800 | 607 | Site assignment failed. Client version is higher than the site version. | Site assignment failed. Client version is higher than the site version. |
800 | 608 | Failed to get Site Version from AD and SLP. | Failed to get Site Version from AD and SLP. |
800 | 609 | Failed to get Client Version. | Failed to get Client Version. |
800 | 700 | Client assignment succeeded. | Client assignment succeeded. |
1000 | 1 | Client is successfully communicating with the Management Point | Client is successfully communicating with the Management Point |
1000 | 2 | Client is failing to communicate with the Management Point | Client is failing to communicate with the Management Point |
1001 | 1 | Client is successfully retrieving a certificate from the local certificate store | Client is successfully retrieving a certificate from the local certificate store |
1001 | 2 | Client is failing to retrieve a certificate from the local certificate store | Client is failing to retrieve a certificate from the local certificate store |
1100 | 1 | Client is not ready for Native Mode | Client is not ready for Native Mode |
1100 | 2 | Client is ready for Native Mode | Client is ready for Native Mode |
Move SCCM Database to remote SQL server
Move SCCM Database to remote SQL server
a. Back up the site database on the current site database server and restore it on the new site database server computer using the SQL Server Management Studio.
b. Ensure the primary site server computer account has administrative privileges over the new site database server computer.
c. Close any open Configuration Manager console connections to the site server.
d. On the primary site server computer, use the hierarchy maintenance tool (Preinst.exe) to stop all site services with the following command: Preinst /stopsite.
e. On the primary site server computer, click Start, click All Programs, click Microsoft System Center, click Configuration Manager 2007, and click ConfigMgr Setup, or navigate to the .\bin\i386 directory of the Configuration Manager 2007 installation media and double-click Setup.exe.
f. Click Next on the Configuration Manager Setup Wizard Welcome page.
g. Click Perform site maintenance or reset this site on the Configuration Manager Setup Wizard Setup Options page.
h. Select Modify SQL Server configuration on the Configuration Manager Setup Wizard Site Maintenance page.
i. Enter the appropriate SQL Server name and instance (if applicable) for the new site database server as well as the site database name on the Configuration Manager Setup Wizard SQL Server Configuration page.
j. Configuration Manager Setup performs the SQL Server configuration process.
k. Restart the primary site server computer, and verify the site is functioning normally.
Tuesday, April 26, 2011
SQL query for Patches required systems as per collection with the SIZE of each update
Below is sql query for Patches required systems as per collection with the SIZE of each update
SELECT DISTINCT
TOP (100) PERCENT SYS.Name0 AS [Machine Name], UCS.Status AS [Patch Status Code], UI.BulletinID, UI.ArticleID, UI.Title,
dbo.v_FullCollectionMembership.ResourceID, dbo.v_Collection.CollectionID, UI.CI_ID, dbo.CI_Contents.SourceSize /(1024.0*1024) AS SizeinMB
FROM dbo.v_UpdateContents INNER JOIN
dbo.v_FullCollectionMembership INNER JOIN
dbo.v_Collection ON dbo.v_FullCollectionMembership.CollectionID = dbo.v_Collection.CollectionID INNER JOIN
dbo.v_R_System AS SYS LEFT OUTER JOIN
dbo.v_Update_ComplianceStatusAll AS UCS ON SYS.ResourceID = UCS.ResourceID INNER JOIN
dbo.v_UpdateInfo AS UI ON UCS.CI_ID = UI.CI_ID ON dbo.v_FullCollectionMembership.ResourceID = UCS.ResourceID ON
dbo.v_UpdateContents.CI_ID = UI.CI_ID INNER JOIN
dbo.CI_Contents ON dbo.v_UpdateContents.Content_ID = dbo.CI_Contents.Content_ID
WHERE (UCS.Status IN ('2')) AND (dbo.v_Collection.CollectionID = 'HCC000FB')
ORDER BY UI.ArticleID
Monday, April 18, 2011
SQL Report with the systems Names and Architecture for specific collection
finding the systems Names and Architecture for specific collection
SELECT dbo.v_Collection.CollectionID, dbo.v_GS_COMPUTER_SYSTEM.Name0, dbo.v_GS_COMPUTER_SYSTEM.SystemType0,
dbo.v_GS_COMPUTER_SYSTEM.UserName0, dbo.v_R_System.Operating_System_Name_and0
FROM dbo.v_Collection INNER JOIN
dbo.v_FullCollectionMembership ON dbo.v_Collection.CollectionID = dbo.v_FullCollectionMembership.CollectionID INNER JOIN
dbo.v_GS_COMPUTER_SYSTEM ON dbo.v_FullCollectionMembership.ResourceID = dbo.v_GS_COMPUTER_SYSTEM.ResourceID INNER JOIN
dbo.v_R_System ON dbo.v_GS_COMPUTER_SYSTEM.ResourceID = dbo.v_R_System.ResourceID
WHERE (dbo.v_Collection.CollectionID = 'CollectionID')
Required Patches based on collection ID
SELECT DISTINCT
TOP (100) PERCENT SYS.Name0 AS [Machine Name], UCS.Status AS [Patch Status Code],
CASE WHEN UCS.Status = '2' THEN 'Applicable' WHEN UCS.Status = '3' THEN 'Installed' ELSE '' END AS 'Patch Status', UI.BulletinID, UI.ArticleID, UI.Title,
dbo.v_FullCollectionMembership.ResourceID, dbo.v_Collection.CollectionID
FROM dbo.v_FullCollectionMembership INNER JOIN
dbo.v_Collection ON dbo.v_FullCollectionMembership.CollectionID = dbo.v_Collection.CollectionID INNER JOIN
dbo.v_R_System AS SYS LEFT OUTER JOIN
dbo.v_Update_ComplianceStatusAll AS UCS ON SYS.ResourceID = UCS.ResourceID INNER JOIN
dbo.v_UpdateInfo AS UI ON UCS.CI_ID = UI.CI_ID ON dbo.v_FullCollectionMembership.ResourceID = UCS.ResourceID
WHERE (UCS.Status IN ('3', '2')) AND (dbo.v_Collection.CollectionID = 'CollectionID')
ORDER BY UI.ArticleID
Wednesday, April 6, 2011
sccm For Desktops only report
For Desktops only report
SELECT TOP (100) PERCENT dbo.v_R_System.Name0 AS [Computer Name], dbo.v_R_System.User_Name0 AS [User Name],
dbo.v_R_System.User_Domain0 AS [Domain Name], dbo.v_GS_SYSTEM_ENCLOSURE.Manufacturer0 AS Manufacturer,
dbo.v_GS_COMPUTER_SYSTEM.Model0 AS Model, dbo.v_GS_SYSTEM_ENCLOSURE.SerialNumber0 AS [Serial Number],
dbo.v_GS_SYSTEM.SystemRole0 AS [System OS Type], dbo.v_GS_SYSTEM.SystemType0 AS [System Type]
FROM dbo.v_GS_SYSTEM_ENCLOSURE INNER JOIN
dbo.v_R_System ON dbo.v_GS_SYSTEM_ENCLOSURE.ResourceID = dbo.v_R_System.ResourceID INNER JOIN
dbo.v_GS_SYSTEM ON dbo.v_R_System.ResourceID = dbo.v_GS_SYSTEM.ResourceID INNER JOIN
dbo.v_GS_COMPUTER_SYSTEM ON dbo.v_GS_SYSTEM.ResourceID = dbo.v_GS_COMPUTER_SYSTEM.ResourceID
WHERE (dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '3') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '4') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '5') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '6') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '7') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '15') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '16')
ORDER BY [Computer Name]
SQL Report for only Laptop Computers
If your boss ask to get list of laptops which are managed by SMS or SCCM.what do you do and how do you get that. Right click on computer and go to resource explorer to identify the computer is Laptop or Desktop ?
You can identify if the computer is Laptop or Desktop based on its chassis Types.
Below are listed the Chassis types available to create SCCM collection or reports.
For Laptops Chassis Types : 8 , 9, 10, 11, 12, 14, 18, 21
For Desktop Chassis Type : 3, 4, 5, 6, 7, 15, 16
For server Chassis Type: 23
SELECT dbo.v_R_System.Name0 AS [Computer Name], dbo.v_R_System.User_Name0 AS [User Name], dbo.v_R_System.User_Domain0 AS [Domain Name],
dbo.v_GS_SYSTEM_ENCLOSURE.Manufacturer0 AS Manufacturer, dbo.v_GS_COMPUTER_SYSTEM.Model0 AS Model,
dbo.v_GS_SYSTEM_ENCLOSURE.SerialNumber0 AS [Serial Number], dbo.v_GS_SYSTEM.SystemRole0 AS [System OS Type],
dbo.v_GS_SYSTEM.SystemType0 AS [System Type]
FROM dbo.v_GS_SYSTEM_ENCLOSURE INNER JOIN
dbo.v_R_System ON dbo.v_GS_SYSTEM_ENCLOSURE.ResourceID = dbo.v_R_System.ResourceID INNER JOIN
dbo.v_GS_SYSTEM ON dbo.v_R_System.ResourceID = dbo.v_GS_SYSTEM.ResourceID INNER JOIN
dbo.v_GS_COMPUTER_SYSTEM ON dbo.v_GS_SYSTEM.ResourceID = dbo.v_GS_COMPUTER_SYSTEM.ResourceID
WHERE (dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '8') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '9') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '10') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '11') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '12') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '14') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '18') OR
(dbo.v_GS_SYSTEM_ENCLOSURE.ChassisTypes0 = '21')
SCCM report for hardware specs of all desktops and laptops on the domain
---select * from v_GS_SYSTEM_ENCLOSURE
SELECT distinct
CS.name0 as 'Computer Name',
CS.domain0 as 'Domain',
CS.UserName0 as 'User',
BIOS.SerialNumber0 as 'Bios serial',
SE.SerialNumber0 as 'System Enclosure serial',
CS.Manufacturer0 as 'Manufacturer',
CS.Model0 as 'model',
OS.Caption0 as 'OS',
RAA.SMS_Assigned_Sites0 as 'Site',
RAM.TotalPhysicalMemory0 as 'Total Memory',
sum(isnull(LDisk.Size0,'0')) as 'Hardrive Size',
sum(isnull(LDisk.FreeSpace0,'0')) AS 'Free Space',
CPU.MaxClockSpeed0 as 'Max CPU Speed',
CPU.Name0 as 'CPU Model',
CPU.Is64Bit0 as '64 Bit Compatible'
from
v_GS_COMPUTER_SYSTEM CS right join v_GS_PC_BIOS BIOS on BIOS.ResourceID = CS.ResourceID
right join v_GS_SYSTEM SYS on SYS.ResourceID = CS.ResourceID
right join v_GS_OPERATING_SYSTEM OS on OS.ResourceID = CS.ResourceID
right join v_RA_System_SMSAssignedSites RAA on RAA.ResourceID = CS.ResourceID
right join V_GS_X86_PC_MEMORY RAM on RAM.ResourceID = CS.ResourceID
right join v_GS_Logical_Disk LDisk on LDisk.ResourceID = CS.ResourceID
right join v_GS_Processor CPU on CPU.ResourceID = CS.ResourceID
right join v_GS_SYSTEM_ENCLOSURE SE on SE.ResourceID = CS.ResourceID
where
LDisk.DriveType0 =3
group by
CS.Name0,
CS.domain0,
CS.Username0,
BIOS.SerialNumber0,
SE.SerialNumber0,
CS.Manufacturer0,
CS.Model0,
OS.Caption0,
RAA.SMS_Assigned_Sites0,
RAM.TotalPhysicalMemory0,
CPU.MaxClockSpeed0,
CPU.Name0,
CPU.Is64Bit0
ORDER BY CS.name0
Thursday, March 24, 2011
Single system required Patch’s report from SQL
---Single system required Patch’s report from SQL
SELECT DISTINCT
SYS.Name0
AS [Machine Name], UCS.Status AS [Patch Status Code],
CASE WHEN UCS.Status = '2' THEN 'Applicable' WHEN UCS.Status = '3' THEN 'Installed' ELSE '' END AS 'Patch Status', UI.BulletinID, UI.ArticleID,
UI.Title
FROM
v_R_System AS SYS LEFT OUTER
JOIN
v_Update_ComplianceStatusAll
AS UCS ON SYS.ResourceID = UCS.ResourceID INNER
JOIN
v_UpdateInfo
AS UI ON UCS.CI_ID = UI.CI_ID
WHERE
(UCS.Status IN ('3', '2')) AND (SYS.Name0 = 'ServerName'
)
Tuesday, March 22, 2011
SQL Add-on Tool like SCCM Right Click tool : SQL Right Click Tool “SSMS Tools” http://www.ssmstoolspack.com/
It contains a few upgrades to the SSMS IDE that I thought were missing.
To see what's new and what got fixed in a release check the News page.
The current features include:
- SQL Snippets
- Window Connection Coloring
- Window Content History, Query Execution History and Current Window History
- Format SQL
- Search Table, View or Database Data
- Run one script on multiple databases
- Copy execution plan bitmaps to clipboard or file
- Search Results in Grid Mode
- Generate Insert statements from resultsets, tables or database
- Regions and Debug sections
- Running custom scripts from Object Explorer
- CRUD stored procedure generation
- New query template
- General options
And it's better than some non-free ones too. :)
Tuesday, March 8, 2011
SQL Tutorial - SELECT Statement
SQL Tutorial
SELECT Statement -- Extended Query Capabilities
This subsection details the remaining features of SELECT statements. The basics are at SELECT Statement Basics.The extended features are grouped as follows:
- Sorting Query Results -- using the ORDER BY clause
- Expressions -- in the SELECT clause and WHERE clause
- Literal -- self-defining values
- Function Call -- expression functions
- System Value -- builtin system values
- Special Construct -- special expression construct
- Numeric or String Operator -- expression operators
- Joining Tables -- in the FROM clause
- Outer Join -- extended join
- Self Join -- joining a table to itself
- Subqueries -- embedding a query in another
- Predicate Subqueries -- subqueries in logical expressions
- Scalar Subqueries -- subqueries in scalar expressions
- Table Subqueries -- subqueries in the FROM clause
- Grouping Queries -- using the GROUP BY clause, Set Function and HAVING clause
- GROUP BY Clause -- specifying grouping columns
- Set Functions -- summary functions
- HAVING Clause -- filtering grouped rows
- Aggregate Queries -- using Set Functions and the HAVING clause
- Union Queries -- using the query operator, UNION
- Union-Compatible Queries -- query requirements for Union
ORDER BY Clause
The ORDER BY clause is optional. If used, it must be the last clause in the SELECT statement. The ORDER BY clause requests sorting for the results of a query.When the ORDER BY clause is missing, the result rows from a query have no defined order (they are unordered). The ORDER BY clause defines the ordering of rows based on columns from the SELECT clause. The ORDER BY clause has the following general format:
ORDER BY column-1 [ASC|DESC] [ column-2 [ASC|DESC] ] ...column-1, column-2, ... are column names specified (or implied) in the select list. If a select column is renamed (given a new name in the select entry), the new name is used in the ORDER BY list. ASC and DESC request ascending or descending sort for a column. ASC is the default.
ORDER BY sorts rows using the ordering columns in left-to-right, major-to-minor order. The rows are sorted first on the first column name in the list. If there are any duplicate values for the first column, the duplicates are sorted on the second column (within the first column sort) in the Order By list, and so on. There is no defined inner ordering for rows that have duplicate values for all Order By columns.
Database nulls require special processing in ORDER BY. A null column sorts higher than all regular values; this is reversed for DESC.
In sorting, nulls are considered duplicates of each other for ORDER BY. Sorting on hidden information makes no sense in utilizing the results of a query. This is also why SQL only allows select list columns in ORDER BY.
For convenience when using expressions in the select list, select items can be specified by number (starting with 1). Names and numbers can be intermixed.
Example queries:
SELECT * FROM sp ORDER BY 3 DESC
sno | pno | qty |
---|---|---|
S1 | P1 | NULL |
S3 | P1 | 1000 |
S3 | P2 | 200 |
S2 | P1 | 200 |
SELECT name, city FROM s ORDER BY name
name | city |
---|---|
John | London |
Mario | Rome |
Pierre | Paris |
SELECT * FROM sp ORDER BY qty DESC, sno
sno | pno | qty |
---|---|---|
S1 | P1 | NULL |
S3 | P1 | 1000 |
S2 | P1 | 200 |
S3 | P2 | 200 |
Expressions
In the previous subsection on basic Select statements, column values are used in the select list and where predicate. SQL allows a scalar value expression to be used instead. A SQL value expression can be a:- Literal -- quoted string, numeric value, datetime value
- Function Call -- reference to builtin SQL function
- System Value -- current date, current user, ...
- Special Construct -- CAST, COALESCE, CASE
- Numeric or String Operator -- combining sub-expressions
Literals
A literal is a typed value that is self-defining. SQL supports 3 types of literals:- String -- ASCII text framed by single quotes ('). Within a literal, a single quote is represented by 2 single quotes ('').
- Numeric -- numeric digits (at least 1) with an optional decimal point and exponent. The format is
[ddd][[.]ddd][E[+|-]ddd]
- Date -- DATE 'yyyy-mm-dd'
- Time -- TIME 'hh:mm:ss[.fff]'
- Timestamp -- TIMESTAMP 'yyyy-mm-dd hh:mm:ss[.fff]'
- Interval -- INTERVAL [+|-] string interval-qualifier
SQL Functions
SQL has the following builtin functions:- SUBSTRING(exp-1 FROM exp-2 [FOR exp-3])
Extracts a substring from a string - exp-1, beginning at the integer value - exp-2, for the length of the integer value - exp-3. exp-2 is 1 relative. If FOR exp-3 is omitted, the length of the remaining string is used. Returns the substring.
- UPPER(exp-1)
Converts any lowercase characters in a string - exp-1 to uppercase. Returns the converted string.
- LOWER(exp-1)
Converts any uppercase characters in a string - exp-1 to lowercase. Returns the converted string.
- TRIM([LEADING|TRAILING|BOTH] [FROM] exp-1)
TRIM([LEADING|TRAILING|BOTH] exp-2 FROM exp-1)Trims leading, trailing or both characters from a string - exp-1. The trim character is a space, or if exp-2 is specified, it supplies the trim character. If LEADING, TRAILING, BOTH are missing, the default is BOTH. Returns the trimmed string.
- POSITION(exp-1 IN exp-2)
Searches a string - exp-2, for a match on a substring - exp-2. Returns an integer, the 1 relative position of the match or 0 for no match.
- CHAR_LENGTH(exp-1)
CHARACTER_LENGTH(exp-1)Returns the integer number of characters in the string - exp-1.
- OCTET_LENGTH(exp-1)
Returns the integer number of octets (8-bit bytes) needed to represent the string - exp-1.
- EXTRACT(sub-field FROM exp-1)
Returns the numeric sub-field extracted from a datetime value - exp-1. sub-field is YEAR, QUARTER, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR or TIMEZONE_MINUTE. TIMEZONE_HOUR and TIMEZONE_MINUTE extract sub-fields from the Timezone portion of exp-1. QUARTER is (MONTH-1)/4+1.
System Values
SQL System Values are reserved names used to access builtin values:- USER -- returns a string with the current SQL authorization identifier.
- CURRENT_USER -- same as USER.
- SESSION_USER -- returns a string with the current SQL session authorization identifier.
- SYSTEM_USER -- returns a string with the current operating system user.
- CURRENT_DATE -- returns a Date value for the current system date.
- CURRENT_TIME -- returns a Time value for the current system time.
- CURRENT_TIMESTAMP -- returns a Timestamp value for the current system timestamp.
SQL Special Constructs
SQL supports a set of special expression constructs:- CAST(exp-1 AS data-type)
Converts the value - exp-1, into the specified date-type. Returns the converted value.
- COALESCE(exp-1, exp-2 [, exp-3] ...)
Returns exp-1 if it is not null, otherwise returns exp-2 if it is not null, otherwise returns exp-3, and so on. Returns null if all values are null.
- CASE exp-1 { WHEN exp-2 THEN exp-3 } ... [ELSE exp-4] END
CASE { WHEN predicate-1 THEN exp-3 } ... [ELSE exp-4] ENDThe first form of the CASE construct compares exp-1 to exp-2 in each WHEN clause. If a match is found, CASE returns exp-3 from the corresponding THEN clause. If no matches are found, it returns exp-4 from the ELSE clause or null if the ELSE clause is omitted.
The second form of the CASE construct evaluates predicate-1 in each WHEN clause. If the predicate is true, CASE returns exp-3 from the corresponding THEN clause. If no predicates evaluate to true, it returns exp-4 from the ELSE clause or null if the ELSE clause is omitted.
Expression Operators
Expression operators combine 2 subexpressions to calculate a value. There are 2 basic types -- numeric and string.- String Operators
There is just one string operator - ||, for string concatenation. Both operands of || must be strings. The operator concatenates the second string to the end of the first. For example,
'ab' || 'cd' ==> 'abcd'
The numeric operators are common to most languages:
- + -- addition
- - -- subtraction
- * -- multiplication
- / -- division
- Integer -- TINYINT, SMALLINT, INT, BIGINT
- Exact -- NUMERIC, DECIMAL
- Approximate -- FLOAT, DOUBLE, REAL
The + and - operators can also be used as unary operators.
The numeric operators can be applied to datetime values, with some restrictions. The basic rules for datetime expressions are:
- A date, time, timestamp value can be added to an interval; result is a date, time, timestamp value.
- An interval value can be subtracted from a date, time, timestamp value; result is a date, time, timestamp value.
- An interval value can be added to or subtracted from another interval; result is an interval value.
- An interval can be multiplied by or divided by a standard numeric value; result is an interval value.
A special form can be used to subtract a date, time, timestamp value from another date, time, timestamp value to yield an interval value:
(datetime-1 - datetime-2) interval-qualifierThe interval-qualifier specifies the specific interval type for the result.
A second special form allows a ? parameter to be typed as an interval:
? interval-qualifier
Joining Tables
The FROM clause allows more than 1 table in its list, however simply listing more than one table will very rarely produce the expected results. The rows from one table must be correlated with the rows of the others. This correlation is known as joining.An example can best illustrate the rationale behind joins. The following query:
SELECT * FROM sp, pProduces:
sno | pno | qty | pno | descr | color |
---|---|---|---|---|---|
S1 | P1 | NULL | P1 | Widget | Blue |
S1 | P1 | NULL | P2 | Widget | Red |
S1 | P1 | NULL | P3 | Dongle | Green |
S2 | P1 | 200 | P1 | Widget | Blue |
S2 | P1 | 200 | P2 | Widget | Red |
S2 | P1 | 200 | P3 | Dongle | Green |
S3 | P1 | 1000 | P1 | Widget | Blue |
S3 | P1 | 1000 | P2 | Widget | Red |
S3 | P1 | 1000 | P3 | Dongle | Green |
S3 | P2 | 200 | P1 | Widget | Blue |
S3 | P2 | 200 | P2 | Widget | Red |
S3 | P2 | 200 | P3 | Dongle | Green |
A more usable query would correlate the rows from sp with rows from p, for instance matching on the common column -- pno:
SELECT *This produces:
FROM sp, p
WHERE sp.pno = p.pno
sno | pno | qty | pno | descr | color |
---|---|---|---|---|---|
S1 | P1 | NULL | P1 | Widget | Blue |
S2 | P1 | 200 | P1 | Widget | Blue |
S3 | P1 | 1000 | P1 | Widget | Blue |
S3 | P2 | 200 | P2 | Widget | Red |
The join in this example is known as an inner equi-join. equi meaning that the join predicate uses = (equals) to match the join columns. Other types of joins use different comparison operators. For example, a query might use a greater-than join.
The term inner means only rows that match are included. Rows in the first table that have no matching rows in the second table are excluded and vice versa (in the above join, the row in p with pno P3 is not included in the result.) An outer join includes unmatched rows in the result. See Outer Join below.
More than 2 tables can participate in a join. This is basically just an extension of a 2 table join. 3 tables -- a, b, c, might be joined in various ways:
- a joins b which joins c
- a joins b and the join of a and b joins c
- a joins b and a joins c
This query performs a 3 table join:
SELECT name, qty, descr, colorIt joins s to sp and sp to p, producing:
FROM s, sp, p
WHERE s.sno = sp.sno
AND sp.pno = p.pno
name | qty | descr | color |
---|---|---|---|
Pierre | NULL | Widget | Blue |
John | 200 | Widget | Blue |
Mario | 1000 | Widget | Blue |
Mario | 200 | Widget | Red |
Outer Joins
An inner join excludes rows from either table that don't have a matching row in the other table. An outer join provides the ability to include unmatched rows in the query results. The outer join combines the unmatched row in one of the tables with an artificial row for the other table. This artificial row has all columns set to null.The outer join is specified in the FROM clause and has the following general format:
table-1 { LEFT | RIGHT | FULL } OUTER JOIN table-2 ON predicate-1predicate-1 is a join predicate for the outer join. It can only reference columns from the joined tables. The LEFT, RIGHT or FULL specifiers give the type of join:
- LEFT -- only unmatched rows from the left side table (table-1) are retained
- RIGHT -- only unmatched rows from the right side table (table-2) are retained
- FULL -- unmatched rows from both tables (table-1 and table-2) are retained
SELECT pno, descr, color, sno, qty
FROM p LEFT OUTER JOIN sp ON p.pno = sp.pno
pno | descr | color | sno | qty |
---|---|---|---|---|
P1 | Widget | Blue | S1 | NULL |
P1 | Widget | Blue | S2 | 200 |
P1 | Widget | Blue | S3 | 1000 |
P2 | Widget | Red | S3 | 200 |
P3 | Dongle | Green | NULL | NULL |
Self Joins
A query can join a table to itself. Self joins have a number of real world uses. For example, a self join can determine which parts have more than one supplier:SELECT DISTINCT a.pno
FROM sp a, sp b
WHERE a.pno = b.pno
AND a.sno <> b.sno
pno |
---|
P1 |
Self joins are often used in subqueries. See Subqueries below.
Subqueries
Subqueries are an identifying feature of SQL. It is called Structured Query Language because a query can nest inside another query.There are 3 basic types of subqueries in SQL:
- Predicate Subqueries -- extended logical constructs in the WHERE (and HAVING) clause.
- Scalar Subqueries -- standalone queries that return a single value; they can be used anywhere a scalar value is used.
- Table Subqueries -- queries nested in the FROM clause.
Predicate Subqueries
Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct. Except for EXISTS, predicate subqueries must retrieve one column (in their select list.)- IN Subquery
The IN Subquery tests whether a scalar value matches the single query column value in any subquery result row. It has the following general format:
value-1 [NOT] IN (query-1)
NOT value-1 IN (query-1)For example, to list parts that have suppliers:
SELECT *
FROM p
WHERE pno IN (SELECT pno FROM sp)
pno | descr | color |
---|---|---|
P1 | Widget | Blue |
P2 | Widget | Red |
The Self Join example in the previous subsection can be expressed with an IN Subquery:
SELECT DISTINCT pno
FROM sp a
WHERE pno IN (SELECT pno FROM sp b WHERE a.sno <> b.sno)
pno |
---|
P1 |
Note that the subquery where clause references a column in the outer query (a.sno). This is known as an outer reference. Subqueries with outer references are sometimes known as correlated subqueries.
A quantified subquery allows several types of tests and can use the full set of comparison operators. It has the following general format:
value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1)The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row. The ANY, ALL, SOME specifiers give the type of match expected. ANY and SOME must match at least one row in the subquery. ALL must match all rows in the subquery, or the subquery must be empty (produce no rows).
For example, to list all parts that have suppliers:
SELECT *
FROM p
WHERE pno =ANY (SELECT pno FROM sp)
pno | descr | color |
---|---|---|
P1 | Widget | Blue |
P2 | Widget | Red |
A self join is used to list the supplier with the highest quantity of each part (ignoring null quantities):
SELECT *
FROM sp a
WHERE qty >ALL (SELECT qty FROM sp b
WHERE a.pno = b.pno
AND a.sno <> b.sno
AND qty IS NOT NULL)
sno | pno | qty |
---|---|---|
S3 | P1 | 1000 |
S3 | P2 | 200 |
The EXISTS Subquery tests whether a subquery retrieves at least one row, that is, whether a qualifying row exists. It has the following general format
EXISTS(query-1)Any valid EXISTS subquery must contain an outer reference. It must be a correlated subquery.
Note: the select list in the EXISTS subquery is not actually used in evaluating the EXISTS, so it can contain any valid select list (though * is normally used).
To list parts that have suppliers:
SELECT *
FROM p
WHERE EXISTS(SELECT * FROM sp WHERE p.pno = sp.pno)
pno | descr | color |
---|---|---|
P1 | Widget | Blue |
P2 | Widget | Red |
Scalar Subqueries
The Scalar Subquery can be used anywhere a value can be used. The subquery must reference just one column in the select list. It must also retrieve no more than one row.When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery. When the subquery returns no rows, a database null is used as the result of the subquery. Should the subquery retreive more than one row, it is a run-time error and aborts query execution.
A Scalar Subquery can appear as a scalar value in the select list and where predicate of an another query. The following query on the sp table uses a Scalar Subquery in the select list to retrieve the supplier city associated with the supplier number (sno column in sp):
SELECT pno, qty, (SELECT city FROM s WHERE s.sno = sp.sno)
FROM sp
pno | qty | city |
---|---|---|
P1 | NULL | Paris |
P1 | 200 | London |
P1 | 1000 | Rome |
P2 | 200 | Rome |
SELECT *
FROM sp
WHERE 'Blue' = (SELECT color FROM p WHERE p.pno = sp.pno)
sno | pno | qty |
---|---|---|
S1 | P1 | NULL |
S2 | P1 | 200 |
S3 | P1 | 1000 |
Table Subqueries
Table Subqueries are queries used in the FROM clause, replacing a table name. Basically, the result set of the Table Subquery acts like a base table in the from list. Table Subqueries can have a correlation name in the from list. They can also be in outer joins.The following two queries produce the same result:
SELECT p.*, qty
FROM p, sp
WHERE p.pno = sp.pno
AND sno = 'S3'
pno | descr | color | qty |
---|---|---|---|
P1 | Widget | Blue | 1000 |
P2 | Widget | Red | 200 |
SELECT p.*, qty
FROM p, (SELECT pno, qty FROM sp WHERE sno = 'S3')
WHERE p.pno = sp.pno
pno | descr | color | qty |
---|---|---|---|
P1 | Widget | Blue | 1000 |
P2 | Widget | Red | 200 |
Grouping Queries
A Grouping Query is a special type of query that groups and summarizes rows. It uses the GROUP BY Clause.A Grouping Query groups rows based on common values in a set of grouping columns. Rows with the same values for the grouping columns are placed in distinct groups. Each group is treated as a single row in the query result.
Even though a group is treated as a single row, the underlying rows can be subject to summary operations known as Set Functions whose results can be included in the query. The optional HAVING Clause supports filtering for group rows in the same manner as the WHERE clause filters FROM rows.
For example, grouping the sp table on the pno column produces 2 groups:
sno | pno | qty | |
---|---|---|---|
S1 | P1 | NULL | 'P1' Group |
S2 | P1 | 200 | |
S3 | P1 | 1000 | |
S3 | P2 | 200 | 'P2' Group |
- The P1 group contains 3 sp rows with pno='P1'
- The P2 group contains a single sp row with pno='P2'
Grouping the sp table on the qty column produces 3 groups:
sno | pno | qty | |
---|---|---|---|
S1 | P1 | NULL | NULL Group |
S2 | P1 | 200 | 200 Group |
S3 | P2 | 200 | |
S3 | P1 | 1000 | 1000 Group |
GROUP BY Clause
GROUP BY is an optional clause in a query. It follows the WHERE clause or the FROM clause if the WHERE clause is missing. A query containing a GROUP BY clause is a Grouping Query. The GROUP BY clause has the following general format:GROUP BY column-1 [, column-2] ...column-1 and column-2 are the grouping columns. They must be names of columns from tables in the FROM clause; they can't be expressions.
GROUP BY operates on the rows from the FROM clause as filtered by the WHERE clause. It collects the rows into groups based on common values in the grouping columns. Except nulls, rows with the same set of values for the grouping columns are placed in the same group. If any grouping column for a row contains a null, the row is given its own group.
For example,
SELECT pno
FROM sp
GROUP BY pno
pno |
---|
P1 |
P2 |
Set Functions
Set Functions are special summarizing functions used with Grouping Queries and Aggregate Queries. They summarize columns from the underlying rows of a group or aggregate.Using the Group By example from above, grouping the sp table on the pno column:
sno | pno | qty | |
---|---|---|---|
S1 | P1 | NULL | 'P1' Group |
S2 | P1 | 200 | |
S3 | P1 | 1000 | |
S3 | P2 | 200 | 'P2' Group |
sno | pno | qty | qty total | |
---|---|---|---|---|
S1 | P1 | NULL | 'P1' Group | 1200 |
S2 | P1 | 200 | ||
S3 | P1 | 1000 | ||
S3 | P2 | 200 | 'P2' Group | 200 |
SELECT pno, SUM(qty)
FROM sp
GROUP BY pno
pno | |
---|---|
P1 | 1200 |
P2 | 200 |
set-function ( [DISTINCT|ALL] column-1 )set-function is:
- COUNT -- count of rows
- SUM -- arithmetic sum of numeric column
- AVG -- arithmetic average of numeric column; should be SUM()/COUNT().
- MIN -- minimum value found in column
- MAX -- maximum value found in column
The Set Functions skip columns with nulls, summarizing non-null values. COUNT counts rows with non-null values, AVG averages non-null values, and so on. COUNT returns 0 when no non-null column values are found; the other functions return null when there are no values to summarize.
A Set Function argument can be a column or an scalar expression.
The DISTINCT and ALL specifiers are optional. ALL specifies that all non-null values are summarized; it is the default. DISTINCT specifies that distinct column values are summarized; duplicate values are skipped. Note: DISTINCT has no effect on MIN and MAX results.
COUNT also has an alternate format:
COUNT(*)... which counts the underlying rows regardless of column contents.
Set Function examples:
SELECT pno, MIN(sno), MAX(qty), AVG(qty), COUNT(DISTINCT sno)
FROM sp
GROUP BY pno
pno | ||||
---|---|---|---|---|
P1 | S1 | 1000 | 600 | 3 |
P2 | S3 | 200 | 200 | 1 |
SELECT sno, COUNT(*) parts
FROM sp
GROUP BY sno
sno | parts |
---|---|
S1 | 1 |
S2 | 1 |
S3 | 2 |
HAVING Clause
The HAVING Clause is associated with Grouping Queries and Aggregate Queries. It is optional in both cases. In Grouping Queries, it follows the GROUP BY clause. In Aggregate Queries, HAVING follows the WHERE clause or the FROM clause if the WHERE clause is missing.The HAVING Clause has the following general format:
HAVING predicateLike the WHERE Clause, HAVING filters the query result rows. WHERE filters the rows from the FROM clause. HAVING filters the grouped rows (from the GROUP BY clause) or the aggregate row (for Aggregate Queries).
predicate is a logical expression referencing grouped columns and set functions. It has the same restrictions as the select list for Grouping Queries and Aggregate Queries.
If the Having predicate evaluates to true for a grouped or aggregate row, the row is included in the query result, otherwise, the row is skipped (not included in the query result).
For example,
SELECT sno, COUNT(*) parts
FROM sp
GROUP BY sno
HAVING COUNT(*) > 1
sno | parts |
---|---|
S3 | 2 |
Aggregate Queries
An Aggregate Query can use Set Functions and a HAVING Clause. It is similar to a Grouping Query except there are no grouping columns. The underlying rows from the FROM and WHERE clauses are grouped into a single aggregate row. An Aggregate Query always returns a single row, except when the Having clause is used.An Aggregate Query is a query containing Set Functions in the select list but no GROUP BY clause. The Set Functions operate on the columns of the underlying rows of the single aggregate row. Except for outer references, any columns used in the select list must be arguments to Set Functions. See Set Functions above.
An aggregate query may also have a Having clause. The Having clause filters the single aggregate row. If the Having predicate evaluates to true, the query result contains the aggregate row. Otherwise, the query result contains no rows. See HAVING Clause above.
For example,
SELECT COUNT(DISTINCT pno) number_parts, SUM(qty) total_parts
FROM sp
number_parts | total_parts |
---|---|
2 | 1400 |
SELECT *
FROM p
WHERE (SELECT COUNT(*) FROM sp WHERE sp.pno=p.pno) > 0
pno | descr | color |
---|---|---|
P1 | Widget | Blue |
P2 | Widget | Red |
SELECT *
FROM p
WHERE (SELECT COUNT(DISTINCT sno) FROM sp WHERE sp.pno=p.pno) > 1
pno | descr | color |
---|---|---|
P1 | Widget | Blue |
Union Queries
The SQL UNION operator combines the results of two queries into a composite result. The component queries can be SELECT/FROM queries with optional WHERE/GROUP BY/HAVING clauses. The UNION operator has the following general format:query-1 UNION [ALL] query-2query-1 and query-2 are full query specifications. The UNION operator creates a new query result that includes rows from each component query.
By default, UNION eliminates duplicate rows in its composite results. The optional ALL specifier requests that duplicates be retained in the UNION result.
The component queries of a Union Query can also be Union Queries themselves. Parentheses are used for grouping queries.
The select lists from the component queries must be union-compatible. They must match in degree (number of columns). For Entry Level SQL92, the column descriptor (data type and precision, scale) for each corresponding column must match. The rules for Intermediate Level SQL92 are less restrictive. See Union-Compatible Queries.
Union-Compatible Queries
For Entry Level SQL92, each corresponding column of both queries must have the same column descriptor in order for two queries to be union-compatible. The rules are less restrictive for Intermediate Level SQL92. It supports automatic conversion within type categories. In general, the resulting data type will be the broader type. The corresponding columns need only be in the same data type category:- Character (String) -- fixed/variable length
- Bit String -- fixed/variable length
- Exact Numeric (fixed point) -- integer/decimal
- Approximate Numeric (floating point) -- float/double
- Datetime -- sub-category must be the same,
- Date
- Time
- Timestamp
- Date
- Interval -- sub-category must be the same,
- Year-month
- Day-time
- Year-month
UNION Examples
SELECT * FROM sp
UNION
SELECT CAST(' ' AS VARCHAR(5)), pno, CAST(0 AS INT)
FROM p
WHERE pno NOT IN (SELECT pno FROM sp)
sno | pno | qty |
---|---|---|
S1 | P1 | NULL |
S2 | P1 | 200 |
S3 | P1 | 1000 |
S3 | P2 | 200 |
P3 | 0 |
SQL Modification Statements
The remaining SQL-Data Statements (SQL DML) are the SQL Modification Statements, described in the next sub-section:- INSERT Statement -- add rows to tables
- UPDATE Statement -- modify columns in table rows
- DELETE Statement -- remove rows from tables
SQL-Data Statements | SQL Tutorial Main Page |
Copyright © 2002-2005 FFE Software, Inc. All Rights Reserved WorldWide